@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
@@ -18,6 +18,13 @@ import { AuthContext, type AuthContextValue } from '../../../auth/state/auth.con
18
18
  import { OpenChangeRequestsContext } from '../../state/open-change-requests.context';
19
19
  import { AdminContext, type AdminContextValue } from '../../../admin/state/admin.context';
20
20
  import { PR_STALE_EVENT } from '../../../../core/events';
21
+ import {
22
+ AppRegistryContext,
23
+ makeRegistry,
24
+ type FolderMenuContext,
25
+ type FolderMenuItemDef,
26
+ type FolderMenuTools,
27
+ } from '../../../../core/registry';
21
28
 
22
29
  // authFetch is the bearer-token wrapper around window.fetch. The Download
23
30
  // click test asserts the URL + ?download=1 flag, so we mock it at the
@@ -177,8 +184,16 @@ interface RenderOptions {
177
184
  clearUploadNotice?: ReturnType<typeof vi.fn>;
178
185
  fileTree?: FileTreeEntry | null;
179
186
  createFile?: ReturnType<typeof vi.fn>;
187
+ createDirectory?: ReturnType<typeof vi.fn>;
188
+ refreshFileTree?: ReturnType<typeof vi.fn>;
180
189
  deleteEntry?: ReturnType<typeof vi.fn>;
181
190
  moveEntry?: ReturnType<typeof vi.fn>;
191
+ /**
192
+ * The DEPLOYMENT's folder-menu entries (`AppRegistry.folderMenuItems`).
193
+ * Omitted is the real core shape — the registry is still provided, and it is
194
+ * empty, which is what every other test in this file renders against.
195
+ */
196
+ folderMenuItems?: FolderMenuItemDef[];
182
197
  /** The workspace id — the encoded branch name, so it decides "protected". */
183
198
  workspaceId?: string;
184
199
  openFilePath?: string | null;
@@ -218,14 +233,20 @@ interface RenderOptions {
218
233
 
219
234
  /** The router's current query, so a test can read what a click put there. */
220
235
  function LocationProbe() {
221
- const { search } = useLocation();
222
- return <span data-testid="location-search">{search}</span>;
236
+ const { search, pathname } = useLocation();
237
+ return (
238
+ <>
239
+ <span data-testid="location-search">{search}</span>
240
+ <span data-testid="location-pathname">{pathname}</span>
241
+ </>
242
+ );
223
243
  }
224
244
 
225
245
  function renderExplorer(opts: RenderOptions = {}) {
226
246
  const dispatchUpload = opts.dispatchUpload ?? vi.fn().mockResolvedValue(undefined);
227
247
  const clearUploadError = opts.clearUploadError ?? vi.fn();
228
248
  const createFile = opts.createFile ?? vi.fn().mockResolvedValue(undefined);
249
+ const createDirectory = opts.createDirectory ?? vi.fn().mockResolvedValue(undefined);
229
250
  const deleteEntry = opts.deleteEntry ?? vi.fn().mockResolvedValue(undefined);
230
251
  const moveEntry = opts.moveEntry ?? vi.fn().mockResolvedValue(undefined);
231
252
  // Distinguish "caller wants null tree" from "caller didn't pass anything".
@@ -245,16 +266,23 @@ function renderExplorer(opts: RenderOptions = {}) {
245
266
  clearUploadNotice: opts.clearUploadNotice ?? (() => {}),
246
267
  isUploading: opts.isUploading ?? false,
247
268
  openFilePath: opts.openFilePath ? atPath(opts.openFilePath) : null,
248
- refreshFileTree: async () => fileTree,
269
+ refreshFileTree: opts.refreshFileTree ?? (async () => fileTree),
249
270
  dispatchUpload,
250
271
  clearUploadError,
251
272
  createFile,
273
+ createDirectory,
252
274
  deleteEntry,
253
275
  moveEntry,
254
276
  ...(opts.workspaceId ? { workspaceId: opts.workspaceId } : {}),
277
+ // The two travel together in the app — `WorkspaceInfo.id` is
278
+ // `encodeURIComponent(branch)` and `workspaceBranch` is its decode — so
279
+ // the fixture must not hand out a pair that cannot exist.
280
+ workspaceBranch: decodeURIComponent(opts.workspaceId ?? 'ws-1'),
255
281
  });
282
+ const registry = makeRegistry({ folderMenuItems: opts.folderMenuItems ?? [] });
256
283
  const ui = (ws: WorkspaceContextValue, mine: Map<string, number>) => (
257
284
  <MemoryRouter initialEntries={opts.initialEntries ?? ['/']}>
285
+ <AppRegistryContext.Provider value={registry}>
258
286
  <AuthContext.Provider value={makeAuth()}>
259
287
  <AdminContext.Provider value={{ isAdmin: opts.isAdmin === true } as AdminContextValue}>
260
288
  <WorkspaceContext.Provider value={ws}>
@@ -295,6 +323,7 @@ function renderExplorer(opts: RenderOptions = {}) {
295
323
  </WorkspaceContext.Provider>
296
324
  </AdminContext.Provider>
297
325
  </AuthContext.Provider>
326
+ </AppRegistryContext.Provider>
298
327
  </MemoryRouter>
299
328
  );
300
329
  const minePaths = new Map([...(opts.minePaths ?? new Map<string, number>())].map(([k, n]) => [atPath(k), n]));
@@ -304,11 +333,14 @@ function renderExplorer(opts: RenderOptions = {}) {
304
333
  dispatchUpload,
305
334
  clearUploadError,
306
335
  createFile,
336
+ createDirectory,
307
337
  deleteEntry,
308
338
  ...result,
309
339
  /** Re-render the same explorer as though the user switched workspace. */
310
340
  switchWorkspace: (workspaceId: string) =>
311
- result.rerender(ui({ ...workspace, workspaceId }, minePaths)),
341
+ result.rerender(
342
+ ui({ ...workspace, workspaceId, workspaceBranch: decodeURIComponent(workspaceId) }, minePaths),
343
+ ),
312
344
  /**
313
345
  * What the refetch behind a PR_STALE_EVENT does to a tree whose request
314
346
  * is gone: `/mine` stops listing it, so its paths leave `minePaths`. The
@@ -1943,7 +1975,6 @@ describe('FileExplorer right-click: the viewport stub cleans up after itself', (
1943
1975
  // follows the destination, plus whatever else about it is worth knowing.
1944
1976
  describe('FileExplorer: delete and move ask first', () => {
1945
1977
  const DRAG_MIME = 'application/x-workspace-path';
1946
- const DRAG_KIND_MIME = 'application/x-workspace-kind';
1947
1978
  const KB = 'knowledge-base';
1948
1979
  const TREE: FileTreeEntry = rootedAtCheckout({
1949
1980
  name: '.',
@@ -1973,6 +2004,10 @@ describe('FileExplorer: delete and move ask first', () => {
1973
2004
  type: 'directory',
1974
2005
  children: [
1975
2006
  { name: 'nda.md', relativePath: `${KB}/KnowledgeBase/Legal/Old/nda.md`, type: 'file' },
2007
+ // The folder in Juan's case carries its own rules, which
2008
+ // travel with it — the reason the resolver answers the
2009
+ // same holders on both sides of its move.
2010
+ { name: 'access.md', relativePath: `${KB}/KnowledgeBase/Legal/Old/access.md`, type: 'file' },
1976
2011
  ],
1977
2012
  },
1978
2013
  ],
@@ -2047,12 +2082,11 @@ describe('FileExplorer: delete and move ask first', () => {
2047
2082
  fireEvent.click(screen.getByText('Legal'));
2048
2083
  }
2049
2084
 
2050
- async function dropOn(rowName: string, sourcePath: string, kind: 'file' | 'directory' = 'file') {
2085
+ async function dropOn(rowName: string, sourcePath: string) {
2051
2086
  await act(async () => {
2052
2087
  fireEvent.drop(screen.getByText(rowName), {
2053
2088
  dataTransfer: {
2054
- getData: (t: string) =>
2055
- t === DRAG_MIME ? sourcePath : t === DRAG_KIND_MIME ? kind : '',
2089
+ getData: (t: string) => (t === DRAG_MIME ? sourcePath : ''),
2056
2090
  files: [],
2057
2091
  },
2058
2092
  });
@@ -2084,7 +2118,9 @@ describe('FileExplorer: delete and move ask first', () => {
2084
2118
  it('counts every file under a folder, nested ones included', async () => {
2085
2119
  renderExplorer({ fileTree: TREE });
2086
2120
  await chooseDelete('Legal');
2087
- expect(screen.getByRole('dialog')).toHaveTextContent('Delete Legal and its 3 files?');
2121
+ // `contract.md`, `access.md`, `Old/nda.md` and `Old/access.md` — the
2122
+ // nested ones and the rules files count, because the delete takes them.
2123
+ expect(screen.getByRole('dialog')).toHaveTextContent('Delete Legal and its 4 files?');
2088
2124
  });
2089
2125
 
2090
2126
  it('deletes nothing on Cancel', async () => {
@@ -2345,11 +2381,12 @@ describe('FileExplorer: delete and move ask first', () => {
2345
2381
  * The one drag test that actually DRAGS.
2346
2382
  *
2347
2383
  * 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.
2384
+ * test, with the source path written in by hand. That skips the handshake:
2385
+ * `handleDragStart` writing the payload, and `handleDrop` reading it back
2386
+ * under the same MIME key — one key, the dragged row's path, since the
2387
+ * dialog stopped needing the row's kind. Stop setting the payload, rename
2388
+ * the key, or leave the row undraggable, and all of those tests still pass
2389
+ * while no real drag in the app does anything at all.
2353
2390
  *
2354
2391
  * This one grabs the row, lets the component's own `dragStart` fill a
2355
2392
  * DataTransfer that behaves like the browser's (what `setData` stores is
@@ -2384,7 +2421,6 @@ describe('FileExplorer: delete and move ask first', () => {
2384
2421
  });
2385
2422
  // The component put the drag's subject where the drop handler looks.
2386
2423
  expect(store.get(DRAG_MIME)).toBe(CONTRACT);
2387
- expect(store.get(DRAG_KIND_MIME)).toBe('file');
2388
2424
 
2389
2425
  await act(async () => {
2390
2426
  fireEvent.drop(screen.getByText('Sales'), { dataTransfer });
@@ -2534,21 +2570,26 @@ describe('FileExplorer: delete and move ask first', () => {
2534
2570
  expect(screen.getAllByText('Engineering: can no longer open')).toHaveLength(2);
2535
2571
  });
2536
2572
 
2537
- it('asks nothing about a folder being dragged, and says only what it always said', async () => {
2538
- const { moveEntry } = renderExplorer({ fileTree: TREE });
2539
- // A folder's access is its own access.md plus every file under it — not
2540
- // the question this lookup answers, so it is not asked.
2541
- await dropOn('Sales', `${KB}/KnowledgeBase/Legal/Old`, 'directory');
2542
-
2543
- const dialog = screen.getByRole('dialog');
2544
- expect(dialog).toHaveTextContent(
2545
- "Move Old to Sales? Access to it will follow Sales' rules from now on.",
2573
+ it('asks about a folder being dragged too, and names what its move costs', async () => {
2574
+ const { moveEntry } = renderExplorer({ fileTree: TREE, workspaceId: 'main' });
2575
+ // A folder's rules are the `access.md` files inside it, and they travel
2576
+ // with it — the resolver counts them where they land, so the question
2577
+ // is worth asking for a folder as much as for a file.
2578
+ answerAccess({ read: [group('Engineering')] }, {});
2579
+ await dropOn('Sales', `${KB}/KnowledgeBase/Legal/Old`);
2580
+ await waitFor(() =>
2581
+ expect(
2582
+ mockAuthFetch.mock.calls.some((c) => String(c[0]).includes('/access/prospective')),
2583
+ ).toBe(true),
2546
2584
  );
2547
- expect(screen.queryByText('Will lose access:')).not.toBeInTheDocument();
2548
- expect(screen.queryByText("Couldn't work out the access change.")).not.toBeInTheDocument();
2549
- expect(
2550
- mockAuthFetch.mock.calls.some((c) => String(c[0]).includes('/access/prospective')),
2551
- ).toBe(false);
2585
+ await act(async () => {});
2586
+
2587
+ const url = mockAuthFetch.mock.calls
2588
+ .map((c) => String(c[0]))
2589
+ .find((u) => u.includes('/access/prospective'))!;
2590
+ expect(url).toContain(`from=${encodeURIComponent('KnowledgeBase/Legal/Old')}`);
2591
+ expect(url).toContain(`toDir=${encodeURIComponent('KnowledgeBase/Sales')}`);
2592
+ expect(screen.getByText('Engineering: can no longer open')).toBeInTheDocument();
2552
2593
 
2553
2594
  // And it is still an ordinary move.
2554
2595
  await act(async () => {
@@ -2560,6 +2601,43 @@ describe('FileExplorer: delete and move ask first', () => {
2560
2601
  );
2561
2602
  });
2562
2603
 
2604
+ /**
2605
+ * Juan's case, in the dialog. `Legal/Old` carries its own `access.md`
2606
+ * (see the tree above), so the resolver answers the same holders on both
2607
+ * sides — that resolution is the BACKEND's, proven over a real tree in
2608
+ * `access-control.preview-relocation.test.ts` and
2609
+ * `workspace.tools.test.ts`; the route is a mock here, as it is in every
2610
+ * case in this suite.
2611
+ *
2612
+ * What this case proves is the half the dialog owns: given an answer with
2613
+ * nothing in it, the dialog says so. It used to say nothing here because
2614
+ * it asked nothing about a folder; now it says nothing because the answer
2615
+ * says nothing, and the two are not the same sentence.
2616
+ */
2617
+ it('says nobody loses access when the answer is the same on both sides of a folder move', async () => {
2618
+ renderExplorer({ fileTree: TREE });
2619
+ answerAccess(
2620
+ { read: [group('Engineering')], write: [group('Engineering')] },
2621
+ { read: [group('Engineering')], write: [group('Engineering')] },
2622
+ );
2623
+ const dialog = await (async () => {
2624
+ await dropOn('Sales', `${KB}/KnowledgeBase/Legal/Old`);
2625
+ await waitFor(() =>
2626
+ expect(
2627
+ mockAuthFetch.mock.calls.some((c) => String(c[0]).includes('/access/prospective')),
2628
+ ).toBe(true),
2629
+ );
2630
+ await act(async () => {});
2631
+ return screen.getByRole('dialog');
2632
+ })();
2633
+
2634
+ // Not "could not work it out" and not a warning either: the question
2635
+ // was asked, answered, and the answer is that nothing changes.
2636
+ expect(dialog).toHaveTextContent("Move Old to Sales? Nobody's access changes.");
2637
+ expect(screen.queryByText('Will lose access:')).not.toBeInTheDocument();
2638
+ expect(screen.queryByText("Couldn't work out the access change.")).not.toBeInTheDocument();
2639
+ });
2640
+
2563
2641
  it('never decorates the next move with the last one’s answer', async () => {
2564
2642
  renderExplorer({ fileTree: TREE });
2565
2643
  answerAccess({ read: [group('Engineering')] }, {});
@@ -3493,3 +3571,499 @@ describe('FileExplorer: the root is the checkout', () => {
3493
3571
  expect(screen.getByTestId('tree-empty-notice')).toHaveTextContent(/^This knowledge base is empty\./);
3494
3572
  });
3495
3573
  });
3574
+
3575
+ // ── A deployment's own entries in a folder's right-click menu ──
3576
+ //
3577
+ // `AppRegistry.folderMenuItems`. Core registers none — "New ontology" belongs
3578
+ // to the distribution that has ontologies — so the registration point and the
3579
+ // no-change-with-nothing-registered case are tested together: the second is
3580
+ // what a core deployment actually ships.
3581
+
3582
+ describe("FileExplorer folder menu: a deployment's own entries", () => {
3583
+ const TREE: FileTreeEntry = {
3584
+ name: '.',
3585
+ relativePath: '.',
3586
+ type: 'directory',
3587
+ children: [
3588
+ { name: 'reports', relativePath: 'reports', type: 'directory', children: [] },
3589
+ { name: 'brief.md', relativePath: 'brief.md', type: 'file' },
3590
+ ],
3591
+ };
3592
+
3593
+ /** An entry with the parts a test does not care about already filled in. */
3594
+ function anEntry(over: Partial<FolderMenuItemDef> & { id: string }): FolderMenuItemDef {
3595
+ return {
3596
+ label: over.id,
3597
+ appliesTo: () => true,
3598
+ run: () => {},
3599
+ ...over,
3600
+ };
3601
+ }
3602
+
3603
+ beforeEach(() => {
3604
+ cleanup();
3605
+ mockAuthFetch.mockReset();
3606
+ // The fixture's workspace is `ws-1`, which this model leaves unprotected —
3607
+ // so the write lookup short-circuits and no test here answers `/access`
3608
+ // unless it is about a protected branch and says so.
3609
+ configureBranchModel({ defaultBranch: 'main', protectedBranches: ['main'] });
3610
+ });
3611
+
3612
+ /** The labels of the open menu's items, top to bottom. */
3613
+ const menuLabels = () =>
3614
+ [...screen.getByRole('menu').querySelectorAll('[role="menuitem"]')].map((el) =>
3615
+ (el.textContent ?? '').trim(),
3616
+ );
3617
+
3618
+ /** Right-click a row and let any lookup the menu makes land. */
3619
+ async function openMenuOn(label: string) {
3620
+ fireEvent.contextMenu(screen.getByText(label));
3621
+ await act(async () => {});
3622
+ }
3623
+
3624
+ /** `/access` answering one verdict, for the protected-branch cases. */
3625
+ function answerCanWrite(canWrite: boolean) {
3626
+ mockAuthFetch.mockImplementation(async (url: string) =>
3627
+ String(url).includes('/access?')
3628
+ ? { ok: true, status: 200, json: async () => ({ canRead: true, canWrite }) }
3629
+ : undefined,
3630
+ );
3631
+ }
3632
+
3633
+ const separator = () => screen.queryByTestId('folder-menu-registered-separator');
3634
+
3635
+ it('shows a registered entry last, behind a separator, after the tree\'s own entries', async () => {
3636
+ renderExplorer({
3637
+ fileTree: TREE,
3638
+ folderMenuItems: [anEntry({ id: 'new-thing', label: 'New thing' })],
3639
+ });
3640
+ await openMenuOn('reports');
3641
+
3642
+ const labels = menuLabels();
3643
+ expect(labels).toContain('New thing');
3644
+ // Last, and after Delete — the tree's own vocabulary ends before it starts.
3645
+ expect(labels[labels.length - 1]).toBe('New thing');
3646
+ expect(labels.indexOf('New thing')).toBeGreaterThan(labels.indexOf('Delete'));
3647
+ const item = screen.getByRole('menuitem', { name: 'New thing' });
3648
+ expect(item.previousElementSibling).toBe(separator());
3649
+ });
3650
+
3651
+ it('draws registered entries in the order registered', async () => {
3652
+ renderExplorer({
3653
+ fileTree: TREE,
3654
+ folderMenuItems: [
3655
+ anEntry({ id: 'one', label: 'First thing' }),
3656
+ anEntry({ id: 'two', label: 'Second thing' }),
3657
+ anEntry({ id: 'three', label: 'Third thing' }),
3658
+ ],
3659
+ });
3660
+ await openMenuOn('reports');
3661
+
3662
+ expect(menuLabels().slice(-3)).toEqual(['First thing', 'Second thing', 'Third thing']);
3663
+ // One separator for the group, not one per entry.
3664
+ expect(screen.getAllByTestId('folder-menu-registered-separator')).toHaveLength(1);
3665
+ });
3666
+
3667
+ /**
3668
+ * The negative half of the registration point, and the shape core ships:
3669
+ * with nothing registered the menu is NOT "the same plus an empty group" —
3670
+ * there is no separator either, and the item list is untouched.
3671
+ */
3672
+ it('leaves the menu exactly as it is when nothing is registered', async () => {
3673
+ renderExplorer({ fileTree: TREE });
3674
+ await openMenuOn('reports');
3675
+ const asShipped = menuLabels();
3676
+ expect(separator()).toBeNull();
3677
+ cleanup();
3678
+
3679
+ renderExplorer({
3680
+ fileTree: TREE,
3681
+ folderMenuItems: [anEntry({ id: 'new-thing', label: 'New thing' })],
3682
+ });
3683
+ await openMenuOn('reports');
3684
+ // Nothing of the tree's own moved, changed or disappeared — the entry is
3685
+ // an addition and only that.
3686
+ expect(menuLabels()).toEqual([...asShipped, 'New thing']);
3687
+ });
3688
+
3689
+ it('registers nothing of its own', () => {
3690
+ expect(makeRegistry({}).folderMenuItems).toEqual([]);
3691
+ });
3692
+
3693
+ it('offers them on every folder, and on no file row', async () => {
3694
+ renderExplorer({
3695
+ fileTree: TREE,
3696
+ folderMenuItems: [anEntry({ id: 'new-thing', label: 'New thing' })],
3697
+ });
3698
+ await openMenuOn('reports');
3699
+ expect(screen.getByRole('menuitem', { name: 'New thing' })).toBeInTheDocument();
3700
+
3701
+ fireEvent.keyDown(document, { key: 'Escape' });
3702
+ fireEvent.contextMenu(screen.getAllByText(KB_DIR)[0]);
3703
+ await act(async () => {});
3704
+ expect(screen.getByRole('menuitem', { name: 'New thing' })).toBeInTheDocument();
3705
+
3706
+ fireEvent.keyDown(document, { key: 'Escape' });
3707
+ await openMenuOn('brief.md');
3708
+ // A file's menu is out of scope: the entries are a folder's verbs.
3709
+ expect(screen.queryByRole('menuitem', { name: 'New thing' })).toBeNull();
3710
+ expect(separator()).toBeNull();
3711
+ });
3712
+
3713
+ it('tells appliesTo the path, the branch, the write verdict and whether the branch is protected', async () => {
3714
+ const appliesTo = vi.fn(() => true);
3715
+ renderExplorer({
3716
+ fileTree: TREE,
3717
+ folderMenuItems: [anEntry({ id: 'new-thing', appliesTo })],
3718
+ });
3719
+ await openMenuOn('reports');
3720
+
3721
+ expect(appliesTo).toHaveBeenCalledWith({
3722
+ path: kbPath('reports'),
3723
+ branch: 'ws-1',
3724
+ canWrite: true,
3725
+ branchProtected: false,
3726
+ } satisfies FolderMenuContext);
3727
+ });
3728
+
3729
+ it('tells appliesTo the branch is protected, and what the viewer may write there', async () => {
3730
+ answerCanWrite(false);
3731
+ const appliesTo = vi.fn(() => true);
3732
+ renderExplorer({
3733
+ fileTree: TREE,
3734
+ workspaceId: 'main',
3735
+ folderMenuItems: [anEntry({ id: 'new-thing', appliesTo })],
3736
+ });
3737
+ await openMenuOn('reports');
3738
+ await waitFor(() =>
3739
+ expect(appliesTo).toHaveBeenCalledWith(
3740
+ expect.objectContaining({ branch: 'main', branchProtected: true, canWrite: false }),
3741
+ ),
3742
+ );
3743
+ // Asked as a folder, repo-relative — the question the access route answers.
3744
+ // (The menu's Download preflight asks about the same row on the same
3745
+ // route, workspace-relative; this is the write lookup, not that one.)
3746
+ expect(mockAuthFetch.mock.calls.map((c) => String(c[0]))).toContain(
3747
+ `/api/workspace/main/access?path=${encodeURIComponent('reports')}&kind=folder`,
3748
+ );
3749
+ });
3750
+
3751
+ it('leaves an entry out of the folders its appliesTo refuses', async () => {
3752
+ const writableOnly = anEntry({
3753
+ id: 'new-thing',
3754
+ label: 'New thing',
3755
+ appliesTo: (folder) => folder.canWrite,
3756
+ });
3757
+
3758
+ answerCanWrite(false);
3759
+ renderExplorer({ fileTree: TREE, workspaceId: 'main', folderMenuItems: [writableOnly] });
3760
+ await openMenuOn('reports');
3761
+ await waitFor(() => expect(mockAuthFetch).toHaveBeenCalled());
3762
+ await act(async () => {});
3763
+ expect(screen.queryByRole('menuitem', { name: 'New thing' })).toBeNull();
3764
+ expect(separator()).toBeNull();
3765
+ cleanup();
3766
+
3767
+ answerCanWrite(true);
3768
+ renderExplorer({ fileTree: TREE, workspaceId: 'main', folderMenuItems: [writableOnly] });
3769
+ await openMenuOn('reports');
3770
+ expect(await screen.findByRole('menuitem', { name: 'New thing' })).toBeInTheDocument();
3771
+ });
3772
+
3773
+ it('leaves out an entry whose appliesTo throws, logs it, and keeps the rest of the menu', async () => {
3774
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
3775
+ try {
3776
+ renderExplorer({
3777
+ fileTree: TREE,
3778
+ folderMenuItems: [
3779
+ anEntry({
3780
+ id: 'broken',
3781
+ label: 'Broken thing',
3782
+ appliesTo: () => {
3783
+ throw new Error('no idea');
3784
+ },
3785
+ }),
3786
+ anEntry({ id: 'fine', label: 'Fine thing' }),
3787
+ ],
3788
+ });
3789
+ await openMenuOn('reports');
3790
+
3791
+ expect(screen.queryByRole('menuitem', { name: 'Broken thing' })).toBeNull();
3792
+ // The other registered entry, and the tree's own, are unaffected.
3793
+ expect(screen.getByRole('menuitem', { name: 'Fine thing' })).toBeInTheDocument();
3794
+ expect(screen.getByRole('menuitem', { name: /New folder/ })).toBeInTheDocument();
3795
+ expect(screen.getByRole('menuitem', { name: /Delete/ })).toBeInTheDocument();
3796
+ expect(errorSpy.mock.calls.map((c) => String(c[0])).join('\n')).toContain(
3797
+ 'Folder menu entry "broken" failed appliesTo',
3798
+ );
3799
+ } finally {
3800
+ errorSpy.mockRestore();
3801
+ }
3802
+ });
3803
+
3804
+ it('says a broken appliesTo once per menu, not once per render', async () => {
3805
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
3806
+ const complaints = () =>
3807
+ errorSpy.mock.calls.filter((c) => String(c[0]).includes('"broken" failed appliesTo')).length;
3808
+ try {
3809
+ // On a protected branch the write lookup actually goes out, and it
3810
+ // answers `true` where the menu had assumed `false` — so the verdict
3811
+ // MOVES, the folder the predicates are asked about is rebuilt, and
3812
+ // every predicate is asked a second time.
3813
+ answerCanWrite(true);
3814
+ const broken = anEntry({
3815
+ id: 'broken',
3816
+ label: 'Broken thing',
3817
+ appliesTo: () => {
3818
+ throw new Error('no idea');
3819
+ },
3820
+ });
3821
+ renderExplorer({ fileTree: TREE, workspaceId: 'main', folderMenuItems: [broken] });
3822
+ await openMenuOn('reports');
3823
+ await waitFor(() => expect(mockAuthFetch).toHaveBeenCalled());
3824
+ await act(async () => {});
3825
+
3826
+ expect(complaints()).toBe(1);
3827
+
3828
+ // A second opening is a second menu, and says so again.
3829
+ fireEvent.keyDown(document, { key: 'Escape' });
3830
+ await openMenuOn('reports');
3831
+ await act(async () => {});
3832
+ expect(complaints()).toBe(2);
3833
+ } finally {
3834
+ errorSpy.mockRestore();
3835
+ }
3836
+ });
3837
+
3838
+ it('creates what an action asks for through the workspace\'s own routes, and refreshes the tree', async () => {
3839
+ const createDirectory = vi.fn().mockResolvedValue(undefined);
3840
+ const createFile = vi.fn().mockResolvedValue(undefined);
3841
+ const refreshFileTree = vi.fn().mockResolvedValue(null);
3842
+ let seen: { folder: FolderMenuContext; tools: FolderMenuTools } | null = null;
3843
+ renderExplorer({
3844
+ fileTree: TREE,
3845
+ createDirectory,
3846
+ createFile,
3847
+ refreshFileTree,
3848
+ folderMenuItems: [
3849
+ anEntry({
3850
+ id: 'new-thing',
3851
+ label: 'New thing',
3852
+ run: async (folder, tools) => {
3853
+ seen = { folder, tools };
3854
+ await tools.createFolder(`${folder.path}/Thing`);
3855
+ await tools.createFolder(`${folder.path}/Thing/Parts`);
3856
+ await tools.createFile(`${folder.path}/Thing/index.md`, '# Thing\n');
3857
+ await tools.refreshTree();
3858
+ },
3859
+ }),
3860
+ ],
3861
+ });
3862
+ await openMenuOn('reports');
3863
+ await act(async () => {
3864
+ fireEvent.click(screen.getByRole('menuitem', { name: 'New thing' }));
3865
+ });
3866
+
3867
+ // The SAME calls `New file` and `New folder` make — so the access rules,
3868
+ // the platform-file rules and the protected-branch rules reach an entry
3869
+ // without the entry knowing they exist.
3870
+ expect(createDirectory.mock.calls).toEqual([
3871
+ [kbPath('reports/Thing')],
3872
+ [kbPath('reports/Thing/Parts')],
3873
+ ]);
3874
+ expect(createFile).toHaveBeenCalledWith(kbPath('reports/Thing/index.md'), '# Thing\n');
3875
+ expect(refreshFileTree).toHaveBeenCalled();
3876
+ // The action is told exactly what the predicate was told.
3877
+ expect(seen!.folder).toEqual({
3878
+ path: kbPath('reports'),
3879
+ branch: 'ws-1',
3880
+ canWrite: true,
3881
+ branchProtected: false,
3882
+ } satisfies FolderMenuContext);
3883
+ expect(Object.keys(seen!.tools).sort()).toEqual([
3884
+ 'createFile',
3885
+ 'createFolder',
3886
+ 'openPath',
3887
+ 'refreshTree',
3888
+ 'showError',
3889
+ ]);
3890
+ });
3891
+
3892
+ it('opens a path an action asks it to open', async () => {
3893
+ renderExplorer({
3894
+ fileTree: TREE,
3895
+ folderMenuItems: [
3896
+ anEntry({
3897
+ id: 'new-thing',
3898
+ label: 'New thing',
3899
+ run: (folder, tools) => tools.openPath(`${folder.path}/Thing/index.md`),
3900
+ }),
3901
+ ],
3902
+ });
3903
+ await openMenuOn('reports');
3904
+ await act(async () => {
3905
+ fireEvent.click(screen.getByRole('menuitem', { name: 'New thing' }));
3906
+ });
3907
+
3908
+ expect(screen.getByTestId('location-pathname').textContent).toContain('index.md');
3909
+ });
3910
+
3911
+ /**
3912
+ * The route refuses, not the menu: an entry that creates into a folder the
3913
+ * viewer may not write gets the server's own sentence, and it is shown
3914
+ * through the same `window.alert` a refused "New folder" uses — the two must
3915
+ * not drift into two different ways of saying the same no.
3916
+ */
3917
+ it('shows a refused create the way New folder shows one', async () => {
3918
+ const refusal = 'You don\'t have permission to write to "reports"';
3919
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
3920
+ try {
3921
+ const createDirectory = vi.fn().mockRejectedValue(new Error(refusal));
3922
+ renderExplorer({
3923
+ fileTree: TREE,
3924
+ workspaceId: 'main',
3925
+ createDirectory,
3926
+ folderMenuItems: [
3927
+ anEntry({
3928
+ id: 'new-thing',
3929
+ label: 'New thing',
3930
+ run: (folder, tools) => tools.createFolder(`${folder.path}/Thing`),
3931
+ }),
3932
+ ],
3933
+ });
3934
+ answerCanWrite(true);
3935
+ await openMenuOn('reports');
3936
+ await act(async () => {
3937
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'New thing' }));
3938
+ });
3939
+
3940
+ expect(alertSpy).toHaveBeenCalledTimes(1);
3941
+ expect(String(alertSpy.mock.calls[0][0])).toBe(`New thing failed:\n${refusal}`);
3942
+ alertSpy.mockClear();
3943
+
3944
+ // The tree's own New folder, refused by the same route, says the same
3945
+ // thing in the same place.
3946
+ await act(async () => {
3947
+ fireEvent.click(screen.getByLabelText('New folder in reports'));
3948
+ });
3949
+ const input = screen.getByPlaceholderText('folder name');
3950
+ await act(async () => {
3951
+ fireEvent.change(input, { target: { value: 'Thing' } });
3952
+ fireEvent.keyDown(input, { key: 'Enter' });
3953
+ });
3954
+ expect(String(alertSpy.mock.calls[0][0])).toContain(refusal);
3955
+ // One route, so one refusal: both asked the same workspace call.
3956
+ expect(createDirectory.mock.calls).toEqual([
3957
+ [kbPath('reports/Thing')],
3958
+ [kbPath('reports/Thing')],
3959
+ ]);
3960
+ } finally {
3961
+ alertSpy.mockRestore();
3962
+ }
3963
+ });
3964
+
3965
+ it('closes the menu when an entry\'s action fails, and when it succeeds', async () => {
3966
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
3967
+ try {
3968
+ renderExplorer({
3969
+ fileTree: TREE,
3970
+ folderMenuItems: [
3971
+ anEntry({
3972
+ id: 'boom',
3973
+ label: 'Boom',
3974
+ run: () => {
3975
+ throw new Error('fell over');
3976
+ },
3977
+ }),
3978
+ anEntry({ id: 'quiet', label: 'Quiet' }),
3979
+ ],
3980
+ });
3981
+
3982
+ await openMenuOn('reports');
3983
+ await act(async () => {
3984
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Boom' }));
3985
+ });
3986
+ expect(screen.queryByRole('menu')).toBeNull();
3987
+ expect(String(alertSpy.mock.calls[0][0])).toBe('Boom failed:\nfell over');
3988
+
3989
+ await openMenuOn('reports');
3990
+ await act(async () => {
3991
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Quiet' }));
3992
+ });
3993
+ expect(screen.queryByRole('menu')).toBeNull();
3994
+ } finally {
3995
+ alertSpy.mockRestore();
3996
+ }
3997
+ });
3998
+
3999
+ it('reports a rejected action, and one that reports itself, the same way', async () => {
4000
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
4001
+ try {
4002
+ renderExplorer({
4003
+ fileTree: TREE,
4004
+ folderMenuItems: [
4005
+ anEntry({ id: 'rejects', label: 'Rejects', run: async () => { throw new Error('said no'); } }),
4006
+ anEntry({
4007
+ id: 'reports',
4008
+ label: 'Reports',
4009
+ run: (_folder, tools) => tools.showError('said no'),
4010
+ }),
4011
+ ],
4012
+ });
4013
+
4014
+ await openMenuOn('reports');
4015
+ await act(async () => {
4016
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Rejects' }));
4017
+ });
4018
+ await openMenuOn('reports');
4019
+ await act(async () => {
4020
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Reports' }));
4021
+ });
4022
+
4023
+ expect(alertSpy.mock.calls.map((c) => String(c[0]))).toEqual([
4024
+ 'Rejects failed:\nsaid no',
4025
+ 'Reports failed:\nsaid no',
4026
+ ]);
4027
+ } finally {
4028
+ alertSpy.mockRestore();
4029
+ }
4030
+ });
4031
+
4032
+ it('is reached and run with the keyboard, exactly as the tree\'s own entries are', async () => {
4033
+ const user = userEvent.setup();
4034
+ const run = vi.fn();
4035
+ renderExplorer({
4036
+ fileTree: TREE,
4037
+ folderMenuItems: [anEntry({ id: 'new-thing', label: 'New thing', run })],
4038
+ });
4039
+ await openMenuOn('reports');
4040
+
4041
+ const registered = screen.getByRole('menuitem', { name: 'New thing' });
4042
+ // An ordinary button, like `New folder` — nothing takes it out of the tab
4043
+ // order and nothing refuses its activation.
4044
+ expect(registered.tagName).toBe(screen.getByRole('menuitem', { name: /New folder/ }).tagName);
4045
+ expect(registered).not.toHaveAttribute('aria-disabled');
4046
+ expect(registered).not.toHaveAttribute('disabled');
4047
+
4048
+ // Tab in from the row the menu was opened on and collect what the keyboard
4049
+ // reaches, so "reachable" is the keyboard's answer and not an assumption
4050
+ // about the DOM.
4051
+ screen.getByText('reports').closest('button')!.focus();
4052
+ const reached: string[] = [];
4053
+ for (let i = 0; i < 30 && document.activeElement !== registered; i++) {
4054
+ await user.tab();
4055
+ const el = document.activeElement as HTMLElement | null;
4056
+ if (el?.getAttribute('role') === 'menuitem') reached.push((el.textContent ?? '').trim());
4057
+ }
4058
+ expect(document.activeElement).toBe(registered);
4059
+ // The tree's own entries are reached the same way, on the way in.
4060
+ expect(reached).toContain('New folder');
4061
+ expect(reached).toContain('New thing');
4062
+
4063
+ await act(async () => {
4064
+ await user.keyboard('{Enter}');
4065
+ });
4066
+ expect(run).toHaveBeenCalledTimes(1);
4067
+ expect(screen.queryByRole('menu')).toBeNull();
4068
+ });
4069
+ });