@bevel-software/platform-core-frontend 0.36.1 → 0.38.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 (23) hide show
  1. package/package.json +2 -2
  2. package/src/core/registry.ts +21 -2
  3. package/src/lib/api.ts +7 -1
  4. package/src/modules/auth/__tests__/useAuthState.test.ts +92 -0
  5. package/src/modules/auth/hooks/useAuthState.ts +4 -1
  6. package/src/modules/auth/index.ts +2 -0
  7. package/src/modules/auth/state/accountStorage.ts +32 -0
  8. package/src/modules/auth/state/tokenAccount.ts +53 -0
  9. package/src/modules/settings/settings-nav-items.tsx +24 -4
  10. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -5
  11. package/src/modules/toolbar/commands/actions.tsx +1 -0
  12. package/src/modules/toolbar/components/ProfileMenu.tsx +13 -1
  13. package/src/modules/toolbar/components/__tests__/ProfileMenu.app-sections.test.tsx +87 -0
  14. package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +1 -0
  15. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +2 -1
  16. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +80 -32
  17. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +78 -8
  18. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +10 -3
  19. package/src/modules/workspace/components/renderers/__tests__/pageConsentMemory.test.ts +177 -0
  20. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +249 -23
  21. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +52 -16
  22. package/src/modules/workspace/components/renderers/pageConsentMemory.ts +75 -0
  23. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +46 -11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.36.1",
3
+ "version": "0.38.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.36.1"
48
+ "@bevel-software/platform-shared": "0.38.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@modelcontextprotocol/client": "^2.3.1",
@@ -89,12 +89,31 @@ export interface AdminMenuItemHelpers {
89
89
  * Skills & Tools is NOT one of these. It is an `AppDef`, reached from the app
90
90
  * switcher.
91
91
  */
92
+ /**
93
+ * A labelled section of the profile menu an app defines (see
94
+ * {@link AdminMenuItem.section}). Rows naming the same `id` share it; the
95
+ * label and order are the first such row's.
96
+ */
97
+ export interface AdminMenuSection {
98
+ id: string;
99
+ /** The section's heading, such as "Infrastructure only". */
100
+ label: string;
101
+ /** Position among the app's sections; 100 when absent. */
102
+ order?: number;
103
+ }
104
+
92
105
  export interface AdminMenuItem {
93
106
  id: string;
94
107
  label: ReactNode;
95
108
  icon?: ReactNode;
96
- /** 'admin' rows render under the "Admin only" section (admin users only). */
97
- section?: 'default' | 'admin';
109
+ /**
110
+ * 'admin' rows render under the "Admin only" section (admin users only).
111
+ * An {@link AdminMenuSection} puts the row under a section of the app's own,
112
+ * labelled, between the default rows and "Admin only" — for rows meant for
113
+ * the holders of a role the app defines. Who sees each row is still its
114
+ * `isShown`; the section shows while any of its rows does.
115
+ */
116
+ section?: 'default' | 'admin' | AdminMenuSection;
98
117
  /** Merge position among core + registered rows of the same section. */
99
118
  order?: number;
100
119
  /**
package/src/lib/api.ts CHANGED
@@ -110,6 +110,12 @@ export interface AuthFetchOptions {
110
110
  * Network failures always signal, whatever this returns.
111
111
  */
112
112
  isApplicationResponse?: (response: Response) => boolean;
113
+ /**
114
+ * The session token to send instead of reading the stored one now: a caller
115
+ * that checked whose token it is sends exactly that token, never one another
116
+ * tab put in its place between the check and the request. `null` sends none.
117
+ */
118
+ token?: string | null;
113
119
  }
114
120
 
115
121
  /**
@@ -123,7 +129,7 @@ export async function authFetch(
123
129
  init?: RequestInit,
124
130
  opts: AuthFetchOptions = {},
125
131
  ): Promise<Response> {
126
- const token = getToken();
132
+ const token = opts.token !== undefined ? opts.token : getToken();
127
133
  const headers = new Headers(init?.headers);
128
134
  if (token) headers.set('Authorization', `Bearer ${token}`);
129
135
 
@@ -0,0 +1,92 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { act, renderHook, waitFor } from '@testing-library/react';
3
+ import { accountKeyPrefix, useAuthState } from '..';
4
+ import { getToken, setToken } from '../../../lib/api';
5
+
6
+ /**
7
+ * Signing out clears what the account kept in this browser, through the real
8
+ * hook and `localStorage`; only the server's answer about the session is stubbed.
9
+ */
10
+ const A_ENTRY = `${accountKeyPrefix('user-a')}htmlPage.allowedWrite.digest`;
11
+ const B_ENTRY = `${accountKeyPrefix('user-b')}htmlPage.allowedWrite.digest`;
12
+
13
+ /** The session the server answers: `user-a`, or an expired token. */
14
+ function stubSession(status = 200) {
15
+ vi.stubGlobal(
16
+ 'fetch',
17
+ vi.fn(async () =>
18
+ status === 200
19
+ ? new Response(JSON.stringify({ id: 'user-a', email: 'a@example.com', name: 'A' }), { status: 200, headers: { 'content-type': 'application/json' } })
20
+ : new Response('{}', { status }),
21
+ ),
22
+ );
23
+ }
24
+
25
+ async function signedIn() {
26
+ setToken('token-a');
27
+ stubSession();
28
+ const { result } = renderHook(() => useAuthState());
29
+ await waitFor(() => expect(result.current.user?.id).toBe('user-a'));
30
+ return result;
31
+ }
32
+
33
+ describe('useAuthState signing out', () => {
34
+ beforeEach(() => {
35
+ window.localStorage.clear();
36
+ window.localStorage.setItem(A_ENTRY, '1');
37
+ window.localStorage.setItem(B_ENTRY, '2');
38
+ window.localStorage.setItem('bevel.htmlPage.height', '300');
39
+ });
40
+ afterEach(() => {
41
+ vi.restoreAllMocks();
42
+ vi.unstubAllGlobals();
43
+ });
44
+
45
+ it("clears the signed-out account's entries and leaves another account's", async () => {
46
+ const auth = await signedIn();
47
+ expect(window.localStorage.getItem(A_ENTRY)).toBe('1');
48
+
49
+ act(() => auth.current.logout());
50
+
51
+ expect(auth.current.user).toBeNull();
52
+ expect(getToken()).toBeNull();
53
+ expect(window.localStorage.getItem(A_ENTRY)).toBeNull();
54
+ expect(window.localStorage.getItem(B_ENTRY)).toBe('2');
55
+ expect(window.localStorage.getItem('bevel.htmlPage.height')).toBe('300');
56
+ });
57
+
58
+ it("never reaches another account whose id starts with the signed-out one's, whatever the id holds", async () => {
59
+ const others = ['user-a.b', 'user-a/b', 'user-a%2Fb', 'user-a b', 'user-ab', 'user-a@example.com'];
60
+ for (const other of others) window.localStorage.setItem(`${accountKeyPrefix(other)}entry`, '1');
61
+ const auth = await signedIn();
62
+
63
+ act(() => auth.current.logout());
64
+
65
+ expect(window.localStorage.getItem(A_ENTRY)).toBeNull();
66
+ for (const other of others) expect(window.localStorage.getItem(`${accountKeyPrefix(other)}entry`)).toBe('1');
67
+ expect(new Set(others.map(accountKeyPrefix)).size).toBe(others.length);
68
+ });
69
+
70
+ it('still signs out when the storage cannot be listed', async () => {
71
+ const auth = await signedIn();
72
+ vi.spyOn(Storage.prototype, 'key').mockImplementation(() => {
73
+ throw new DOMException('The operation is insecure.', 'SecurityError');
74
+ });
75
+
76
+ act(() => auth.current.logout());
77
+
78
+ expect(auth.current.user).toBeNull();
79
+ expect(getToken()).toBeNull();
80
+ });
81
+
82
+ it('keeps the entries when a session ends without signing out: they are still only that account\'s', async () => {
83
+ setToken('expired');
84
+ stubSession(401);
85
+ const { result } = renderHook(() => useAuthState());
86
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
87
+
88
+ expect(result.current.user).toBeNull();
89
+ expect(window.localStorage.getItem(A_ENTRY)).toBe('1');
90
+ expect(window.localStorage.getItem(B_ENTRY)).toBe('2');
91
+ });
92
+ });
@@ -3,6 +3,7 @@ import type { AuthUser } from '@bevel-software/platform-shared';
3
3
  import type { AuthContextValue } from '../state/auth.context';
4
4
  import { loginWithPassword, fetchCurrentUser } from '../services/auth.api';
5
5
  import { getToken, setToken, clearToken } from '../../../lib/api';
6
+ import { clearAccountStorage } from '../state/accountStorage';
6
7
  import { consumeSsoCallback, OAUTH_ERROR_KEY } from '../services/sso';
7
8
 
8
9
  export function useAuthState(): AuthContextValue {
@@ -44,10 +45,12 @@ export function useAuthState(): AuthContextValue {
44
45
  }, []);
45
46
 
46
47
  const logout = useCallback(() => {
48
+ // What the account kept in this browser leaves with it.
49
+ if (user) clearAccountStorage(user.id);
47
50
  clearToken();
48
51
  setTokenState(null);
49
52
  setUser(null);
50
- }, []);
53
+ }, [user]);
51
54
 
52
55
  return useMemo(() => ({
53
56
  user,
@@ -9,4 +9,6 @@ export type { AccountReferences, AccountSummary } from './services/account.api';
9
9
  export { takePostLoginRedirect } from './services/sso';
10
10
  export type { LoginProviders } from './services/sso';
11
11
  export { AuthContext, useAuth, type AuthContextValue } from './state/auth.context';
12
+ export { accountKeyPrefix } from './state/accountStorage';
13
+ export { AccountChangedError, accountFetch } from './state/tokenAccount';
12
14
  export { useSignInMethods } from './state/use-sign-in-methods';
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What one signed-in account keeps in this browser's `localStorage`: entries
3
+ * under a prefix that names the account, which signing out clears as one.
4
+ *
5
+ * The account id is URI-encoded and closed with a `/`, which encoding never
6
+ * leaves in an id, so no account's prefix is the start of another's, whatever
7
+ * its id holds.
8
+ */
9
+ const ACCOUNT_KEY_ROOT = 'bevel.account/';
10
+
11
+ /** The prefix of every entry this account keeps. May throw on an id that cannot be encoded: callers treat it as storage that will not store. */
12
+ export function accountKeyPrefix(accountId: string): string {
13
+ return `${ACCOUNT_KEY_ROOT}${encodeURIComponent(accountId)}/`;
14
+ }
15
+
16
+ /**
17
+ * Remove every entry this account keeps, and no other's. Never throws: signing
18
+ * out must finish whatever the browser's storage does, and a storage that
19
+ * cannot be touched is one nothing can be read back from either.
20
+ */
21
+ export function clearAccountStorage(accountId: string): void {
22
+ try {
23
+ const storage = window.localStorage;
24
+ const prefix = accountKeyPrefix(accountId);
25
+ const keys = Array.from({ length: storage.length }, (_, i) => storage.key(i));
26
+ for (const key of keys) {
27
+ if (key?.startsWith(prefix)) storage.removeItem(key);
28
+ }
29
+ } catch {
30
+ // Nothing more can be done here; the entries still answer to this account alone.
31
+ }
32
+ }
@@ -0,0 +1,53 @@
1
+ import { authFetch, getToken } from '../../../lib/api';
2
+
3
+ /**
4
+ * The account a session token belongs to: its `userId` claim, or null when
5
+ * there is no token or it cannot be read. The claim is read, not verified:
6
+ * the server verifies the token on every request, and this only asks whose it
7
+ * is. A token renewed for the same account (a password change) keeps its
8
+ * account.
9
+ */
10
+ function accountOf(token: string | null): string | null {
11
+ try {
12
+ const payload = token?.split('.')[1];
13
+ if (!payload) return null;
14
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
15
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
16
+ const bytes = Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
17
+ const claims = JSON.parse(new TextDecoder().decode(bytes)) as { userId?: unknown };
18
+ return typeof claims.userId === 'string' && claims.userId ? claims.userId : null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /** What `accountFetch` throws, sending nothing, when the session is not the expected account's. */
25
+ export class AccountChangedError extends Error {
26
+ constructor() {
27
+ super('You signed in as another account in another tab. Reload this page to use its tools as that account.');
28
+ this.name = 'AccountChangedError';
29
+ }
30
+ }
31
+
32
+ /**
33
+ * A fetch that sends only as `accountId`. The stored session token is shared
34
+ * by every tab: a sign-in in another tab replaces it, while this tab's auth
35
+ * state still names the account it signed in as. Something decided for that
36
+ * account (a page's remembered Allow) must not reach the server with another
37
+ * account's token. Each request reads the token ONCE, throws
38
+ * `AccountChangedError` without sending anything unless it is `accountId`'s
39
+ * (no token, or one that cannot be read, included), and sends exactly that
40
+ * token, so a token swapped in after the check is never the one sent.
41
+ */
42
+ export function accountFetch(accountId: string): (input: string, init?: RequestInit) => Promise<Response> {
43
+ return async (input, init) => {
44
+ let token: string | null;
45
+ try {
46
+ token = getToken();
47
+ } catch {
48
+ token = null;
49
+ }
50
+ if (accountOf(token) !== accountId) throw new AccountChangedError();
51
+ return authFetch(input, init, { token });
52
+ };
53
+ }
@@ -163,9 +163,18 @@ export function isSettingsNavPath(pathname: string): boolean {
163
163
  return SETTINGS_NAV_PATHS.includes(normalizeSettingsPath(pathname));
164
164
  }
165
165
 
166
+ /** One of the app's own labelled sections, with its rows sorted. */
167
+ export interface AppMenuSection {
168
+ id: string;
169
+ label: string;
170
+ items: AdminMenuItem[];
171
+ }
172
+
166
173
  export interface MenuSections {
167
174
  defaultItems: AdminMenuItem[];
168
175
  adminItems: AdminMenuItem[];
176
+ /** The app's own sections (see `AdminMenuItem.section`), in their order; drawn between the two above. */
177
+ appSections: AppMenuSection[];
169
178
  }
170
179
 
171
180
  /**
@@ -180,10 +189,21 @@ export function useMenuSections(): MenuSections {
180
189
  const registry = useAppRegistry();
181
190
  return useMemo(() => {
182
191
  const all = [...CORE_MENU_ITEMS, ...registry.adminMenuItems];
192
+ const byOrder = (a: AdminMenuItem, b: AdminMenuItem) => (a.order ?? 100) - (b.order ?? 100);
183
193
  const bySection = (section: 'default' | 'admin') =>
184
- all
185
- .filter((item) => (item.section ?? 'default') === section)
186
- .sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
187
- return { defaultItems: bySection('default'), adminItems: bySection('admin') };
194
+ all.filter((item) => (item.section ?? 'default') === section).sort(byOrder);
195
+ // The app's sections: one per id, its label and order from the first row naming it.
196
+ const sections = new Map<string, AppMenuSection & { order: number }>();
197
+ for (const item of all) {
198
+ const section = item.section;
199
+ if (typeof section !== 'object') continue;
200
+ const entry = sections.get(section.id) ?? { id: section.id, label: section.label, order: section.order ?? 100, items: [] };
201
+ entry.items.push(item);
202
+ sections.set(section.id, entry);
203
+ }
204
+ const appSections = [...sections.values()]
205
+ .sort((a, b) => a.order - b.order)
206
+ .map(({ id, label, items }) => ({ id, label, items: items.sort(byOrder) }));
207
+ return { defaultItems: bySection('default'), adminItems: bySection('admin'), appSections };
188
208
  }, [registry]);
189
209
  }
@@ -51,6 +51,14 @@ describe('coreCommandActions', () => {
51
51
  row({ id: 'node-label', label: <b>Fancy</b>, path: '/fancy' }),
52
52
  ],
53
53
  adminItems: [row({ id: 'roles', label: 'App roles', path: '/roles-and-members' })],
54
+ // A row in a section of the app's own, for the holders of a role it defines (here: Ada), admin or not.
55
+ appSections: [
56
+ {
57
+ id: 'infra',
58
+ label: 'Infrastructure only',
59
+ items: [row({ id: 'executors', label: 'Executors', path: '/agents/executors', isShown: (u: { email: string }) => u.email === 'ada@example.com' })],
60
+ },
61
+ ],
54
62
  };
55
63
  const all = coreCommandActions({ apps: APPS, settings });
56
64
 
@@ -61,9 +69,15 @@ describe('coreCommandActions', () => {
61
69
  'Go to Knowledge',
62
70
  'Go to Skills & Tools',
63
71
  'Settings: Secrets',
72
+ 'Settings: Executors',
64
73
  ]);
65
74
  });
66
75
 
76
+ it('offers a row of the app\'s own section only to whom its isShown names, admin or not', () => {
77
+ const other = ctx({ isAdmin: true, user: { ...USER, email: 'bob@example.com' } });
78
+ expect(labels(visibleActions(all, other))).not.toContain('Settings: Executors');
79
+ });
80
+
67
81
  it('adds Invite people and the admin settings for an admin', () => {
68
82
  expect(labels(visibleActions(all, ctx({ isAdmin: true })))).toEqual([
69
83
  'Create new page',
@@ -72,6 +86,7 @@ describe('coreCommandActions', () => {
72
86
  'Go to Knowledge',
73
87
  'Go to Skills & Tools',
74
88
  'Settings: Secrets',
89
+ 'Settings: Executors',
75
90
  'Settings: App roles',
76
91
  ]);
77
92
  });
@@ -96,7 +111,7 @@ describe('coreCommandActions', () => {
96
111
  const onSelect = vi.fn(({ navigate }: { navigate(to: string): void }) => navigate('/chosen'));
97
112
  const [action] = coreCommandActions({
98
113
  apps: [],
99
- settings: { defaultItems: [row({ id: 'x', label: 'X', path: '/declared', onSelect })], adminItems: [] },
114
+ settings: { defaultItems: [row({ id: 'x', label: 'X', path: '/declared', onSelect })], adminItems: [], appSections: [] },
100
115
  }).filter((a) => a.id === 'settings:x');
101
116
  const c = ctx();
102
117
  void action.run(c);
@@ -109,7 +124,7 @@ describe('coreCommandActions', () => {
109
124
  const isShown = vi.fn((user: { email: string }) => user.email === 'ada@example.com');
110
125
  const actions = coreCommandActions({
111
126
  apps: [],
112
- settings: { defaultItems: [row({ id: 'undo', label: 'Ask again', onSelect: vi.fn(), isShown })], adminItems: [] },
127
+ settings: { defaultItems: [row({ id: 'undo', label: 'Ask again', onSelect: vi.fn(), isShown })], adminItems: [], appSections: [] },
113
128
  });
114
129
  expect(labels(visibleActions(actions, ctx()))).toContain('Settings: Ask again');
115
130
  expect(labels(visibleActions(actions, ctx({ user: { ...USER, email: 'bob@example.com' } })))).not.toContain(
@@ -125,7 +140,7 @@ describe('coreCommandActions', () => {
125
140
 
126
141
  describe('shortcut hints', () => {
127
142
  it('come from the table the shortcuts are bound by, and only for bound commands', () => {
128
- const all = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [] } });
143
+ const all = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [], appSections: [] } });
129
144
  const hint = (id: string) => all.find((a) => a.id === id)?.shortcut;
130
145
  expect(hint('new-page')).toEqual({ key: 'c' });
131
146
  expect(hint('invite')).toEqual({ key: 'i', shift: true });
@@ -144,7 +159,7 @@ describe('shortcut hints', () => {
144
159
  });
145
160
 
146
161
  describe('suggestedActions', () => {
147
- const all = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [] } });
162
+ const all = coreCommandActions({ apps: APPS, settings: { defaultItems: [], adminItems: [], appSections: [] } });
148
163
  const suggest = (c: CommandContext) => labels(suggestedActions(visibleActions(all, c), c));
149
164
 
150
165
  it('suggests the commonest verbs and the way to the other app', () => {
@@ -159,7 +174,7 @@ describe('suggestedActions', () => {
159
174
  });
160
175
 
161
176
  describe('mergeCommandActions / visibleActions', () => {
162
- const core = coreCommandActions({ apps: [], settings: { defaultItems: [], adminItems: [] } });
177
+ const core = coreCommandActions({ apps: [], settings: { defaultItems: [], adminItems: [], appSections: [] } });
163
178
 
164
179
  it('puts the registry’s commands after core’s and drops a reused id', () => {
165
180
  const error = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -222,6 +222,7 @@ function settingsActions(settings: MenuSections): CommandAction[] {
222
222
  };
223
223
  return [
224
224
  ...settings.defaultItems.map((item) => toAction(item, false)),
225
+ ...settings.appSections.flatMap((section) => section.items.map((item) => toAction(item, false))),
225
226
  ...settings.adminItems.map((item) => toAction(item, true)),
226
227
  ].filter((a): a is CommandAction => a !== null);
227
228
  }
@@ -89,7 +89,7 @@ export function ProfileMenu() {
89
89
  const navigate = useNavigate();
90
90
  const { user, logout } = useAuth();
91
91
  const { isAdmin, unreadCount } = useAdmin();
92
- const { defaultItems, adminItems } = useMenuSections();
92
+ const { defaultItems, adminItems, appSections } = useMenuSections();
93
93
  const [open, setOpen] = useState(false);
94
94
  // Per-row dialog open flags, keyed by item id. A plain map (rather than one
95
95
  // "active dialog" slot) preserves the historical behavior where two dialogs
@@ -184,6 +184,10 @@ export function ProfileMenu() {
184
184
  // Rows offered to this person right now (see `AdminMenuItem.isShown`).
185
185
  const shownDefaultItems = defaultItems.filter((item) => item.isShown?.(user) ?? true);
186
186
  const shownAdminItems = adminItems.filter((item) => item.isShown?.(user) ?? true);
187
+ // The app's sections, each with the rows offered to this person; a section none of whose rows is shown is left out.
188
+ const shownAppSections = appSections
189
+ .map((section) => ({ ...section, items: section.items.filter((item) => item.isShown?.(user) ?? true) }))
190
+ .filter((section) => section.items.length > 0);
187
191
 
188
192
  return (
189
193
  <div className="relative">
@@ -271,6 +275,13 @@ export function ProfileMenu() {
271
275
 
272
276
  {shownDefaultItems.map(renderRow)}
273
277
 
278
+ {shownAppSections.map((section) => (
279
+ <div key={section.id} role="group" aria-labelledby={`profile-menu-section-${section.id}-label`}>
280
+ <MenuLabel id={`profile-menu-section-${section.id}-label`}>{section.label}</MenuLabel>
281
+ {section.items.map(renderRow)}
282
+ </div>
283
+ ))}
284
+
274
285
  {isAdmin && shownAdminItems.length > 0 && (
275
286
  <div role="group" aria-labelledby="profile-menu-admin-section-label">
276
287
  <MenuLabel id="profile-menu-admin-section-label">Admin only</MenuLabel>
@@ -293,6 +304,7 @@ export function ProfileMenu() {
293
304
  {/* Dialogs opened by the menu rows above. Mounted at the menu root so they
294
305
  persist independently of the (transient) dropdown. */}
295
306
  {renderDialogs(defaultItems)}
307
+ {renderDialogs(appSections.flatMap((section) => section.items))}
296
308
  {isAdmin && renderDialogs(adminItems)}
297
309
  </div>
298
310
  );
@@ -0,0 +1,87 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { render, screen, within } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { MemoryRouter } from 'react-router-dom';
5
+ import { AuthContext, type AuthContextValue } from '../../../auth';
6
+ import { AdminContext } from '../../../admin';
7
+ import { AppRegistryContext, makeRegistry, type AdminMenuItem } from '../../../../core/registry';
8
+ import { ProfileMenu } from '../ProfileMenu';
9
+
10
+ /**
11
+ * The profile menu with sections of the app's own, as an app contributes them
12
+ * through the registry: a labelled group between the default rows and "Admin
13
+ * only", for whom each row's `isShown` names — admin or not — and no heading
14
+ * for a section none of whose rows is offered.
15
+ */
16
+
17
+ const INFRA = { id: 'infra', label: 'Infrastructure only', order: 10 };
18
+ const holder = (email: string) => (user: { email: string }) => user.email === email;
19
+
20
+ const rows: AdminMenuItem[] = [
21
+ { id: 'agents-settings', section: INFRA, label: 'Agents', path: '/agents/settings', isShown: holder('ada@example.com') },
22
+ { id: 'executors', section: INFRA, order: 5, label: 'Executors', path: '/agents/executors', isShown: holder('ada@example.com') },
23
+ { id: 'billing', section: { id: 'billing', label: 'Billing only' }, label: 'Invoices', path: '/invoices', isShown: () => false },
24
+ ];
25
+
26
+ function mount(email: string, isAdmin: boolean) {
27
+ const auth: AuthContextValue = {
28
+ user: { id: 'u', email, name: 'Ada Lovelace', avatarUrl: '' },
29
+ token: 'token',
30
+ isLoading: false,
31
+ login: async () => {},
32
+ logout: () => {},
33
+ };
34
+ render(
35
+ <MemoryRouter>
36
+ <AppRegistryContext.Provider value={makeRegistry({ adminMenuItems: rows })}>
37
+ <AuthContext.Provider value={auth}>
38
+ <AdminContext.Provider
39
+ value={{
40
+ isAdmin,
41
+ unreadCount: 0,
42
+ lastSeen: null,
43
+ markSeen: () => {},
44
+ refresh: () => {},
45
+ rolesConfigCorrupted: false,
46
+ rolesConfigErrors: [],
47
+ runRolesRecovery: async () => {},
48
+ }}
49
+ >
50
+ <ProfileMenu />
51
+ </AdminContext.Provider>
52
+ </AuthContext.Provider>
53
+ </AppRegistryContext.Provider>
54
+ </MemoryRouter>,
55
+ );
56
+ }
57
+
58
+ describe('ProfileMenu: the app\'s own sections', () => {
59
+ it('draws the section for a person its rows are for, admin or not, its rows in their order', async () => {
60
+ mount('ada@example.com', false);
61
+ await userEvent.click(screen.getByRole('button', { name: 'Ada Lovelace' }));
62
+ const section = screen.getByRole('group', { name: 'Infrastructure only' });
63
+ expect(within(section).getAllByRole('button').map((b) => b.textContent)).toEqual(['Executors', 'Agents']);
64
+ // Not an admin: no Admin only section, and the section nobody is offered has no heading.
65
+ expect(screen.queryByText('Admin only')).toBeNull();
66
+ expect(screen.queryByText('Billing only')).toBeNull();
67
+ });
68
+
69
+ it('draws it for an admin its rows are for too, after the default rows and before Admin only', async () => {
70
+ mount('ada@example.com', true);
71
+ await userEvent.click(screen.getByRole('button', { name: 'Ada Lovelace' }));
72
+ const section = screen.getByRole('group', { name: 'Infrastructure only' });
73
+ const lastDefault = screen.getByRole('button', { name: 'Account' });
74
+ const adminHeading = screen.getByText('Admin only');
75
+ expect(within(section).getAllByRole('button').map((b) => b.textContent)).toEqual(['Executors', 'Agents']);
76
+ expect(lastDefault.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
77
+ expect(section.compareDocumentPosition(adminHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
78
+ });
79
+
80
+ it('draws nothing of it for anyone else, even an admin', async () => {
81
+ mount('bob@example.com', true);
82
+ await userEvent.click(screen.getByRole('button', { name: 'Ada Lovelace' }));
83
+ expect(screen.queryByText('Infrastructure only')).toBeNull();
84
+ expect(screen.queryByRole('button', { name: 'Executors' })).toBeNull();
85
+ expect(screen.getByText('Admin only')).toBeInTheDocument();
86
+ });
87
+ });
@@ -21,6 +21,7 @@ vi.mock('../../../settings/settings-nav-items', () => ({
21
21
  useMenuSections: () => ({
22
22
  defaultItems: [{ id: 'account', label: 'Account', path: '/account' }],
23
23
  adminItems: [hidden('hidden-a', 'Hidden A'), hidden('hidden-b', 'Hidden B')],
24
+ appSections: [],
24
25
  }),
25
26
  }));
26
27
 
@@ -94,7 +94,8 @@ export function HtmlRenderer({
94
94
  // chase it; and a distribution's document carries its inlined libraries,
95
95
  // which a key built from it would compare on every render.
96
96
  const viewKey = useMemo(() => ({ reloadKey, mode, savedValue, filePath }), [reloadKey, mode, savedValue, filePath]);
97
- const { toolBridge, cards } = useHtmlToolBridge({ iframeRef, filePath, viewKey });
97
+ // The source a preview's document is built from is the saved content.
98
+ const { toolBridge, cards } = useHtmlToolBridge({ iframeRef, filePath, viewKey, source: savedValue });
98
99
 
99
100
  const dirty = !readOnly && value !== savedValue;
100
101