@bevel-software/platform-core-frontend 0.33.0 → 0.34.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 (59) hide show
  1. package/package.json +2 -2
  2. package/src/lib/__tests__/api.test.ts +28 -1
  3. package/src/lib/api.ts +4 -2
  4. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  5. package/src/modules/access/api.ts +3 -4
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  8. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  9. package/src/modules/admin/services/groups.api.ts +11 -1
  10. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  11. package/src/modules/agents/components/ConnectAsChoice.tsx +81 -0
  12. package/src/modules/agents/connect-as.ts +15 -0
  13. package/src/modules/agents/index.ts +5 -0
  14. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  15. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  16. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +13 -0
  17. package/src/modules/audit/components/AuditLogPage.tsx +9 -0
  18. package/src/modules/audit/services/audit.api.ts +5 -0
  19. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  20. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  21. package/src/modules/auth/components/AccountPage.tsx +8 -2
  22. package/src/modules/auth/services/account.api.ts +18 -2
  23. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  24. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  25. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  26. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  27. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  28. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  29. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  30. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  31. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  32. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  33. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +112 -2
  34. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  35. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +38 -4
  36. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +91 -2
  37. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  38. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +26 -0
  39. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  40. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  41. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  42. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  43. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  44. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  45. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  46. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  47. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  48. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  49. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  50. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  51. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  52. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  53. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  54. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  55. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  56. package/src/modules/workspace/index.ts +21 -2
  57. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  58. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  59. package/src/modules/workspace/utils/fileTree.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.33.0",
3
+ "version": "0.34.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.33.0"
48
+ "@bevel-software/platform-shared": "0.34.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@modelcontextprotocol/client": "^2.3.1",
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
 
3
- import { authFetch, API_UNREACHABLE_EVENT } from '../api';
3
+ import { authFetch, API_UNREACHABLE_EVENT, getToken, setToken } from '../api';
4
4
 
5
5
  /** Counts API_UNREACHABLE_EVENT dispatches for the span of one test. */
6
6
  function watchUnreachable(): { seen: () => number; stop: () => void } {
@@ -131,3 +131,30 @@ describe('authFetch application-level responses', () => {
131
131
  expect(watcher.seen()).toBe(1);
132
132
  });
133
133
  });
134
+
135
+ describe('authFetch on a 401', () => {
136
+ beforeEach(() => {
137
+ vi.restoreAllMocks();
138
+ localStorage.clear();
139
+ });
140
+
141
+ it('clears the token the request carried', async () => {
142
+ setToken('old');
143
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response('', { status: 401 }));
144
+ await authFetch('/api/me');
145
+ expect(getToken()).toBeNull();
146
+ });
147
+
148
+ it('keeps a replacement stored while the refused request was in flight', async () => {
149
+ // A password change hands back a new token while requests sent with the
150
+ // old one are still out; their 401s arrive after it is stored.
151
+ setToken('old');
152
+ let answer: (r: Response) => void = () => {};
153
+ vi.spyOn(globalThis, 'fetch').mockReturnValueOnce(new Promise<Response>((resolve) => { answer = resolve; }));
154
+ const inFlight = authFetch('/api/me');
155
+ setToken('replacement');
156
+ answer(new Response('', { status: 401 }));
157
+ await inFlight;
158
+ expect(getToken()).toBe('replacement');
159
+ });
160
+ });
package/src/lib/api.ts CHANGED
@@ -114,7 +114,9 @@ export interface AuthFetchOptions {
114
114
 
115
115
  /**
116
116
  * Fetch wrapper that injects the Authorization header from localStorage.
117
- * On 401 responses, clears the stored token.
117
+ * On 401 responses, clears the stored token — but only if it is still the one
118
+ * this request carried: a password change stores a replacement while older
119
+ * requests are in flight, and their 401s must not sign the changer out.
118
120
  */
119
121
  export async function authFetch(
120
122
  input: RequestInfo | URL,
@@ -141,7 +143,7 @@ export async function authFetch(
141
143
  signalUnreachable();
142
144
  }
143
145
 
144
- if (response.status === 401) {
146
+ if (response.status === 401 && getToken() === token) {
145
147
  clearToken();
146
148
  }
147
149
 
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
- import { render, screen, within } from '@testing-library/react';
2
+ import { render, screen, waitFor, within } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
4
  import type { FileTreeEntry } from '@bevel-software/platform-shared';
5
5
  import type { AccessResponse } from '../api';
@@ -139,3 +139,55 @@ describe('ManageAccessDialog add row: picking several in a row', () => {
139
139
  expect(screen.getAllByRole('button', { name: /GTM Team/ })).toHaveLength(1); // the chip's Remove
140
140
  });
141
141
  });
142
+
143
+ /**
144
+ * A TYPED NAME SHARED BY A ROLE AND A GROUP. A bare name in an access rule
145
+ * means the role when one exists, so Enter on an exact typed match picks the
146
+ * role; the group of the same name is still reachable from its own row.
147
+ */
148
+ describe('ManageAccessDialog add row: Enter on a name shared by a role and a group', () => {
149
+ async function typeAndShare(name: string): Promise<void> {
150
+ const user = userEvent.setup();
151
+ render(<ManageAccessDialog entry={ENTRY} onClose={() => {}} />);
152
+ const field = await screen.findByPlaceholderText(FIELD);
153
+ await user.type(field, name.toLowerCase());
154
+ // Enter resolves against the loaded suggestions — wait for them.
155
+ await screen.findAllByRole('button', { name: new RegExp(name) });
156
+ await user.keyboard('{Enter}');
157
+ expect(screen.getByRole('button', { name: `Remove ${name}` })).toBeInTheDocument();
158
+ await user.click(screen.getByRole('button', { name: /^share$/i }));
159
+ await waitFor(() => expect(api.grantAccess).toHaveBeenCalled());
160
+ }
161
+
162
+ it('picks the ROLE when both a role and a group are named Admin', async () => {
163
+ api.suggestPrincipals.mockResolvedValue({
164
+ roles: ['Admin'],
165
+ groups: ['Admin'],
166
+ people: [],
167
+ peopleWithheld: false,
168
+ });
169
+ await typeAndShare('Admin');
170
+ expect(api.grantAccess).toHaveBeenCalledWith(
171
+ 'ws-1',
172
+ expect.objectContaining({ principal: { kind: 'role', role: 'Admin' } }),
173
+ );
174
+ expect(api.grantAccess).not.toHaveBeenCalledWith(
175
+ 'ws-1',
176
+ expect.objectContaining({ principal: { kind: 'group', group: 'Admin' } }),
177
+ );
178
+ });
179
+
180
+ it('picks the GROUP when no role shares its name', async () => {
181
+ api.suggestPrincipals.mockResolvedValue({
182
+ roles: [],
183
+ groups: ['Admin'],
184
+ people: [],
185
+ peopleWithheld: false,
186
+ });
187
+ await typeAndShare('Admin');
188
+ expect(api.grantAccess).toHaveBeenCalledWith(
189
+ 'ws-1',
190
+ expect.objectContaining({ principal: { kind: 'group', group: 'Admin' } }),
191
+ );
192
+ });
193
+ });
@@ -209,10 +209,9 @@ export function asInheritedError(err: unknown): InheritedRevokeError | null {
209
209
  /**
210
210
  * A grantable principal — a person (by email), a role (an app-defined
211
211
  * capability from the registry, or a legacy roles.yaml role), or a group (a
212
- * people-set from the active group source — IdP-synced or manual). Groups are
213
- * written as bare-name tokens (bare names resolve group-first); the backend
214
- * writes role grants as explicit `role/<Name>` tokens itself — the dialog
215
- * just sends `kind: 'role'`. The separate kinds exist so the backend
212
+ * people-set from the active group source — IdP-synced or manual). The backend
213
+ * writes groups as explicit `group/<Name>` tokens and roles as `role/<Name>`
214
+ * tokens itself, never a bare name — the dialog just sends the kind. The separate kinds exist so the backend
216
215
  * validates each against the right namespace.
217
216
  */
218
217
  export type Principal =
@@ -373,7 +373,7 @@ function NoAccountNote({ help = NO_ACCOUNT_HELP }: { help?: string }) {
373
373
 
374
374
  /**
375
375
  * A principal's row/chip identity. Kind is PART of it: a group and a role
376
- * sharing a name are DIFFERENT principals server-side (bare token vs
376
+ * sharing a name are DIFFERENT principals server-side (`group/<name>` vs
377
377
  * `role/<name>`), so they key — and chip — separately (`g:` vs `r:`). One
378
378
  * name picked as both is two chips, and each grants its own kind.
379
379
  */
@@ -739,7 +739,7 @@ function buildRows(data: AccessResponse | null, myEmail: string): PrincipalRow[]
739
739
  list.principals ?? list.roles.map((name) => ({ name, kind: 'role' as const }));
740
740
  const touchCollective = (c: ResolvedPrincipal): PrincipalRow => {
741
741
  // Rows are keyed by KIND + name (`g:`/`r:`/`p:`) — the backend treats a
742
- // bare `Product` (group) and `role/Product` (role) as DIFFERENT
742
+ // `group/Product` (group) and `role/Product` (role) as DIFFERENT
743
743
  // principals, so a group and a role sharing a name are two rows, each
744
744
  // mutating its own grant. Collapsing them to one row silently pointed
745
745
  // every edit at the group and hid the role's grant entirely. A plugin
@@ -1258,16 +1258,16 @@ export function ManageAccessDialog({
1258
1258
 
1259
1259
  // Resolve the CURRENT typed query into a principal to append as a chip: an
1260
1260
  // exact group/role match or a free-typed email. (Suggestion clicks append
1261
- // directly.) Group first — bare grant tokens resolve group-first, so a name
1262
- // shared by both defaults to the audience concept; the role stays reachable
1263
- // via its own suggestion row.
1261
+ // directly.) Role first — a bare name in an access rule means the role when
1262
+ // one exists, so a typed name shared by both picks what that name means; the
1263
+ // group stays reachable via its own suggestion row.
1264
1264
  const addPending: Principal | null = useMemo(() => {
1265
1265
  const q = query.trim();
1266
1266
  if (!q) return null;
1267
- const groupHit = suggest?.groups?.find((g) => g.toLowerCase() === q.toLowerCase());
1268
- if (groupHit) return { kind: 'group', group: groupHit };
1269
1267
  const roleHit = suggest?.roles?.find((g) => g.toLowerCase() === q.toLowerCase());
1270
1268
  if (roleHit) return { kind: 'role', role: roleHit };
1269
+ const groupHit = suggest?.groups?.find((g) => g.toLowerCase() === q.toLowerCase());
1270
+ if (groupHit) return { kind: 'group', group: groupHit };
1271
1271
  if (EMAIL_RE.test(q)) return { kind: 'user', email: q, displayName: q.split('@')[0] };
1272
1272
  return null;
1273
1273
  }, [query, suggest]);
@@ -266,6 +266,26 @@ describe('DirectoryGroupsPage', () => {
266
266
  await waitFor(() => expect(deleteGroup).toHaveBeenCalledWith('product'));
267
267
  });
268
268
 
269
+ it('the delete confirm counts and names only the rules the roster lists, with no hidden-content line', async () => {
270
+ renderPage();
271
+ await userEvent.click(await screen.findByRole('button', { name: 'Delete Product' }));
272
+
273
+ const dialog = within(screen.getByRole('dialog'));
274
+ expect(dialog.getByText(/1 access rule\b/)).toBeInTheDocument();
275
+ expect(dialog.getByText(/docs\/roadmap\.md/)).toBeInTheDocument();
276
+ expect(dialog.queryByText(/cannot read/)).not.toBeInTheDocument();
277
+ });
278
+
279
+ it('the delete confirm with no listed rules does not claim nothing is shared — unreadable rules may exist', async () => {
280
+ renderPage();
281
+ await userEvent.click(await screen.findByRole('button', { name: 'Delete Design' }));
282
+
283
+ const dialog = within(screen.getByRole('dialog'));
284
+ expect(dialog.getByText('No access rule you can read references this group.')).toBeInTheDocument();
285
+ expect(dialog.queryByText(/Nothing is shared/)).not.toBeInTheDocument();
286
+ expect(dialog.queryByText(/lose nothing/)).not.toBeInTheDocument();
287
+ });
288
+
269
289
  it('idp mode: read-only roster, no mutation controls, membership note shown', async () => {
270
290
  vi.mocked(getGroupsRoster).mockResolvedValue(IDP_ROSTER);
271
291
  renderPage();
@@ -346,6 +366,37 @@ describe('DirectoryGroupsPage', () => {
346
366
  expect(screen.queryByText('Loading…')).not.toBeInTheDocument();
347
367
  });
348
368
 
369
+ it('names every rule whose bare group name resolves to a same-named role, with the group/ spelling', async () => {
370
+ vi.mocked(getGroupsRoster).mockResolvedValue({
371
+ mode: 'idp',
372
+ groups: [
373
+ {
374
+ canonical: 'admin',
375
+ displayName: 'Admin',
376
+ members: ['mallory@example.com'],
377
+ referencedBy: [],
378
+ assignedToRoles: [],
379
+ bareNameResolvesToRole: [{ path: 'Knowledge/Board/access.md', verb: 'read' }],
380
+ },
381
+ ...IDP_ROSTER.groups,
382
+ ],
383
+ groupsHealth: { ok: true },
384
+ });
385
+ renderPage();
386
+ const report = await screen.findByRole('status');
387
+ expect(report).toHaveTextContent(/name a group the way a role is named/i);
388
+ expect(report).toHaveTextContent('Knowledge/Board/access.md');
389
+ expect(report).toHaveTextContent('read: Admin');
390
+ expect(report).toHaveTextContent('group/Admin');
391
+ });
392
+
393
+ it('shows no bare-name report when no group shares a role name', async () => {
394
+ vi.mocked(getGroupsRoster).mockResolvedValue(MANUAL_ROSTER);
395
+ renderPage();
396
+ await screen.findByText('Product');
397
+ expect(screen.queryByText(/name a group the way a role is named/i)).not.toBeInTheDocument();
398
+ });
399
+
349
400
  it('a roster whose groupsHealth is broken banners loudly: file, reason, "not being applied"', async () => {
350
401
  // Broken IdP-synced file: the roster still answers 200 (mode stays idp,
351
402
  // groups empty) but carries the health marker — resolution is degraded
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import { useSearchParams } from 'react-router-dom';
3
3
  import { Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';
4
4
  import { PageShell } from '../../../shared/components/PageShell';
5
+ import { Banner } from '../../../shared/components/Banner';
5
6
  import { Dialog } from '../../../shared/components/Dialog';
6
7
  import { useAdmin } from '../state/admin.context';
7
8
  import { useAppRegistry } from '../../../core/registry';
@@ -60,6 +61,11 @@ export function DirectoryGroupsPage() {
60
61
  const [working, setWorking] = useState(false);
61
62
  // Group pending delete confirmation (manual mode).
62
63
  const [deleteTarget, setDeleteTarget] = useState<GroupRosterEntry | null>(null);
64
+ // Only rules in files the admin can read: the roster leaves the rest out
65
+ // entirely (Admin status does not grant read, not even a count). So the
66
+ // copy below always says "you can read" and never claims there are no
67
+ // other rules — it reads the same whether or not unreadable ones exist.
68
+ const deleteRuleCount = deleteTarget?.referencedBy.length ?? 0;
63
69
  // The overlay panel's "a directory connection exists" signal — true between
64
70
  // connecting and the first push, when the roster still reads 'manual' but
65
71
  // manual edits would go dormant. See GroupsDirectoryPanelProps.
@@ -150,6 +156,12 @@ export function DirectoryGroupsPage() {
150
156
  const health = roster?.groupsHealth;
151
157
  const broken =
152
158
  brokenGroups ?? (health && !health.ok ? { file: health.file, reason: health.reason } : null);
159
+ // Groups that share a role's name, with the rules that spell them bare —
160
+ // those rules grant the ROLE, so an Admin must rewrite them if the group
161
+ // was meant.
162
+ const bareCollisions = (roster?.groups ?? []).filter(
163
+ (g) => (g.bareNameResolvesToRole?.length ?? 0) > 0,
164
+ );
153
165
 
154
166
  return (
155
167
  <>
@@ -171,6 +183,31 @@ export function DirectoryGroupsPage() {
171
183
  </div>
172
184
  )}
173
185
 
186
+ {bareCollisions.length > 0 && (
187
+ <Banner tone="wait" role="status" className="text-xs">
188
+ <div className="font-semibold">
189
+ Some access rules name a group the way a role is named.
190
+ </div>
191
+ <div>
192
+ A bare name in an access rule means the role when one of that name exists. These
193
+ rules resolve to the role, not the group — if the group was meant, write it as{' '}
194
+ <code>group/&lt;Name&gt;</code> (a denial as <code>deny group/&lt;Name&gt;</code>):
195
+ </div>
196
+ {/* A row is a verb and a file: whether the rule there grants or denies is
197
+ not in the roster, so the spelling is given for both. */}
198
+ <ul className="mt-1 list-disc pl-4">
199
+ {bareCollisions.flatMap((g) =>
200
+ g.bareNameResolvesToRole!.map((ref, index) => (
201
+ <li key={`${g.canonical}:${ref.path}:${ref.verb}:${index}`}>
202
+ <code>{ref.path}</code> — {ref.verb}: {g.displayName} (write{' '}
203
+ <code>group/{g.displayName}</code>, or <code>deny group/{g.displayName}</code> for a denial)
204
+ </li>
205
+ )),
206
+ )}
207
+ </ul>
208
+ </Banner>
209
+ )}
210
+
174
211
  {error && (
175
212
  <div
176
213
  className="text-xs text-danger bg-danger-soft border border-danger/30 rounded-sm px-2 py-1.5"
@@ -259,12 +296,12 @@ export function DirectoryGroupsPage() {
259
296
  >
260
297
  {deleteTarget && (
261
298
  <div className="space-y-2">
262
- {deleteTarget.referencedBy.length > 0 ? (
299
+ {deleteRuleCount > 0 ? (
263
300
  <>
264
301
  <p className="text-xs text-ink leading-snug">
265
- {deleteTarget.referencedBy.length} access rule
266
- {deleteTarget.referencedBy.length === 1 ? '' : 's'} reference
267
- {deleteTarget.referencedBy.length === 1 ? 's' : ''} this group and will stop
302
+ {deleteRuleCount} access rule
303
+ {deleteRuleCount === 1 ? '' : 's'} you can read reference
304
+ {deleteRuleCount === 1 ? 's' : ''} this group and will stop
268
305
  matching anyone after deletion:
269
306
  </p>
270
307
  <ul className="max-h-40 overflow-auto text-xs text-ink-muted space-y-0.5">
@@ -277,7 +314,7 @@ export function DirectoryGroupsPage() {
277
314
  </>
278
315
  ) : (deleteTarget.assignedToRoles?.length ?? 0) === 0 ? (
279
316
  <p className="text-xs text-ink leading-snug">
280
- Nothing is shared with this group. Its members lose nothing else.
317
+ No access rule you can read references this group.
281
318
  </p>
282
319
  ) : null}
283
320
  {/* Role assignments are unassigned atomically with the delete —
@@ -18,7 +18,10 @@ export interface GroupRosterEntry {
18
18
  canonical: string;
19
19
  displayName: string;
20
20
  members: string[];
21
- /** Every access rule referencing this group — drives the delete warning. */
21
+ /**
22
+ * Every access rule referencing this group in a file the viewer can read —
23
+ * drives the delete warning.
24
+ */
22
25
  referencedBy: { path: string; verb: string }[];
23
26
  /**
24
27
  * Canonical names of roles carrying an assignment to this group — deleting
@@ -27,6 +30,13 @@ export interface GroupRosterEntry {
27
30
  * defensively: a skewed server may omit it, and rendering must not throw.
28
31
  */
29
32
  assignedToRoles?: string[];
33
+ /**
34
+ * Access rules naming this group's name BARE while a role of the same name
35
+ * exists — a bare name means the role, so these grant the role, not this
36
+ * group. Rewritten as `group/<Name>` if the group was meant. Optional
37
+ * defensively, like `assignedToRoles`.
38
+ */
39
+ bareNameResolvesToRole?: { path: string; verb: string }[];
30
40
  }
31
41
 
32
42
  /**
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { act, renderHook } from '@testing-library/react';
3
+ import { useConnectAsChoice } from '../useConnectAsChoice';
4
+
5
+ const AGENT = { path: 'Agents/release-helper.agent', name: 'release-helper', description: 'Reads; never writes.' };
6
+
7
+ describe('useConnectAsChoice', () => {
8
+ it('starts at Everything and lets nothing connect until the agents answer', () => {
9
+ const { result } = renderHook(() => useConnectAsChoice());
10
+ expect(result.current.value).toBeNull();
11
+ expect(result.current.mayConnect).toBe(false);
12
+ act(() => result.current.settle({ agents: [AGENT] }));
13
+ expect(result.current.agents).toEqual([AGENT]);
14
+ expect(result.current.mayConnect).toBe(true);
15
+ act(() => result.current.setValue(AGENT.path));
16
+ expect(result.current.value).toBe(AGENT.path);
17
+ });
18
+
19
+ it('drops a remembered choice the answer no longer offers, back to Everything', () => {
20
+ const { result } = renderHook(() => useConnectAsChoice({ initial: 'Agents/gone.agent' }));
21
+ expect(result.current.value).toBe('Agents/gone.agent');
22
+ act(() => result.current.settle({ agents: [AGENT] }));
23
+ expect(result.current.value).toBeNull();
24
+ });
25
+
26
+ it('keeps a remembered choice the answer still offers', () => {
27
+ const { result } = renderHook(() => useConnectAsChoice({ initial: AGENT.path }));
28
+ act(() => result.current.settle({ agents: [AGENT] }));
29
+ expect(result.current.value).toBe(AGENT.path);
30
+ });
31
+
32
+ it('waits for Everything to be confirmed when the agents could not be loaded', () => {
33
+ const { result } = renderHook(() => useConnectAsChoice());
34
+ act(() => result.current.settle({ agents: [], failed: true }));
35
+ expect(result.current.unavailable).toBeDefined();
36
+ expect(result.current.mayConnect).toBe(false);
37
+ act(() => result.current.unavailable!.onConfirm(true));
38
+ expect(result.current.mayConnect).toBe(true);
39
+ });
40
+
41
+ it('with an expected request, is settled only by that request’s answer', () => {
42
+ const { result, rerender } = renderHook(({ expect: key }) => useConnectAsChoice({ expect: key }), {
43
+ initialProps: { expect: 'state-1' as string | null },
44
+ });
45
+ act(() => result.current.settle({ agents: [] }, 'state-0'));
46
+ expect(result.current.mayConnect).toBe(false);
47
+ act(() => result.current.settle({ agents: [] }, 'state-1'));
48
+ expect(result.current.mayConnect).toBe(true);
49
+ // A new request arrives: its own answer is awaited again.
50
+ rerender({ expect: 'state-2' });
51
+ expect(result.current.mayConnect).toBe(false);
52
+ // And without any request there is nothing to connect.
53
+ rerender({ expect: null });
54
+ expect(result.current.mayConnect).toBe(false);
55
+ });
56
+ });
@@ -0,0 +1,81 @@
1
+ import { useId } from 'react';
2
+ import { cn } from '../../../lib/utils';
3
+ import type { AgentChoice } from '../services/agent-choices.api';
4
+ import type { UnavailableChoice } from '../connect-as';
5
+
6
+ export interface ConnectAsChoiceProps {
7
+ /** The agents the person may connect as; Everything is always offered first. */
8
+ agents: readonly AgentChoice[];
9
+ /** The chosen agent's path, or null for Everything. */
10
+ value: string | null;
11
+ onChange: (agentPath: string | null) => void;
12
+ disabled?: boolean;
13
+ /** One line under the heading, saying what the choice is for here. */
14
+ hint?: string;
15
+ /**
16
+ * Set when the agents could not be loaded: the list is not "you have
17
+ * none", so the choice says it failed and asks the person to confirm
18
+ * Everything before the connection is made (see {@link canConnectAs}).
19
+ */
20
+ unavailable?: UnavailableChoice;
21
+ }
22
+
23
+ /**
24
+ * "Connect as": Everything (selected by default) or one agent configuration, by
25
+ * name with its description. Used where a connection is made — the OAuth
26
+ * consent step and the connection-key form — so both offer the same choice
27
+ * the same way.
28
+ */
29
+ export function ConnectAsChoice({ agents, value, onChange, disabled, hint, unavailable }: ConnectAsChoiceProps) {
30
+ const name = useId();
31
+ const options: { path: string | null; title: string; detail: string }[] = [
32
+ {
33
+ path: null,
34
+ title: 'Everything',
35
+ detail: 'Every tool, skill and plugin you may read.',
36
+ },
37
+ ...agents.map((a) => ({ path: a.path, title: a.name, detail: a.description || a.path })),
38
+ ];
39
+ return (
40
+ <fieldset className="space-y-1.5" disabled={disabled}>
41
+ <legend className="text-xs font-medium text-ink">Connect as</legend>
42
+ {hint && <p className="text-meta text-ink-muted leading-snug">{hint}</p>}
43
+ <div className="divide-y divide-line border border-line rounded-md">
44
+ {options.map((o) => {
45
+ const checked = value === o.path;
46
+ return (
47
+ <label
48
+ key={o.path ?? ''}
49
+ className={cn('flex items-start gap-2 px-3 py-2 cursor-pointer', checked && 'bg-sunken')}
50
+ >
51
+ <input
52
+ type="radio"
53
+ name={name}
54
+ className="mt-0.5"
55
+ checked={checked}
56
+ onChange={() => onChange(o.path)}
57
+ />
58
+ <span className="min-w-0">
59
+ <span className="block text-sm font-medium text-ink truncate">{o.title}</span>
60
+ <span className="block text-meta text-ink-muted leading-snug">{o.detail}</span>
61
+ </span>
62
+ </label>
63
+ );
64
+ })}
65
+ </div>
66
+ {unavailable && (
67
+ <div role="alert" className="text-xs text-danger bg-danger-soft border border-danger rounded-md px-2 py-1.5 space-y-1">
68
+ <p>Your agents couldn't be loaded, so only Everything can be chosen right now.</p>
69
+ <label className="flex items-center gap-1.5 cursor-pointer">
70
+ <input
71
+ type="checkbox"
72
+ checked={unavailable.confirmed}
73
+ onChange={(e) => unavailable.onConfirm(e.target.checked)}
74
+ />
75
+ Connect as Everything anyway
76
+ </label>
77
+ </div>
78
+ )}
79
+ </fieldset>
80
+ );
81
+ }
@@ -0,0 +1,15 @@
1
+ /** The agents could not be loaded; Everything waits for the person to confirm it. */
2
+ export interface UnavailableChoice {
3
+ confirmed: boolean;
4
+ onConfirm: (confirmed: boolean) => void;
5
+ }
6
+
7
+ /**
8
+ * Whether a connection may be made with the "Connect as" choice as it
9
+ * stands: once the agents on offer have answered — before that, the default
10
+ * Everything is not yet a choice anyone made — and then always, unless they
11
+ * failed to load and Everything is not yet confirmed.
12
+ */
13
+ export function canConnectAs(choices: { settled: boolean; unavailable: UnavailableChoice | undefined }): boolean {
14
+ return choices.settled && (!choices.unavailable || choices.unavailable.confirmed);
15
+ }
@@ -0,0 +1,5 @@
1
+ export { canConnectAs, type UnavailableChoice } from './connect-as';
2
+ export { listAgentChoices, connectedAsLabel, type AgentChoice } from './services/agent-choices.api';
3
+ // The "Connect as" state both forms hold: the consent step and the key form
4
+ // settle it with the agents they loaded and read the choice back from it.
5
+ export { useConnectAsChoice, type AgentChoicesAnswer, type ConnectAsChoiceState } from './useConnectAsChoice';
@@ -0,0 +1,39 @@
1
+ import { authFetch } from '../../../lib/api';
2
+
3
+ /**
4
+ * Connecting as an agent: an MCP connection or a connection key is made as
5
+ * Everything (all the person may read) or as one agent configuration of the
6
+ * knowledge base, whose lists narrow what the connection loads. What a
7
+ * configuration is — the file kind, what it says — is the distribution's;
8
+ * this mirrors the backend's `modules/agent-scope` contract, which only
9
+ * names the configuration by its path.
10
+ */
11
+
12
+ /** One agent configuration the signed-in person may connect as. */
13
+ export interface AgentChoice {
14
+ /** Repo-relative path of the configuration — what the connection records. */
15
+ path: string;
16
+ /** Its name, as the choice shows it. */
17
+ name: string;
18
+ /** Its description, one line; empty when it has none. */
19
+ description: string;
20
+ }
21
+
22
+ /** The agents a connection key may be minted as (the OAuth consent step gets the same list with its request). */
23
+ export async function listAgentChoices(): Promise<AgentChoice[]> {
24
+ const res = await authFetch('/api/mcp/agent-choices');
25
+ if (!res.ok) throw new Error("Couldn't load the agents you can connect as.");
26
+ const body = (await res.json()) as { agents?: AgentChoice[] };
27
+ return Array.isArray(body.agents) ? body.agents : [];
28
+ }
29
+
30
+ /**
31
+ * How a connection's choice reads beside it: "Everything" for none, else the
32
+ * configuration's file name without its extension (the stored record is the
33
+ * path; the name its definition carries is the distribution's to show).
34
+ */
35
+ export function connectedAsLabel(agentPath: string | null | undefined): string {
36
+ if (!agentPath) return 'Everything';
37
+ const base = agentPath.slice(agentPath.lastIndexOf('/') + 1);
38
+ return base.replace(/\.[a-z0-9]+$/i, '') || agentPath;
39
+ }
@@ -0,0 +1,66 @@
1
+ import { useCallback, useMemo, useState } from 'react';
2
+ import { canConnectAs, type UnavailableChoice } from './connect-as';
3
+ import type { AgentChoice } from './services/agent-choices.api';
4
+
5
+ /** What the agents on offer answered: the list, or that they could not be loaded. */
6
+ export interface AgentChoicesAnswer {
7
+ agents: readonly AgentChoice[];
8
+ /** The agents could not be listed: `agents` is then empty for that reason, not because there are none. */
9
+ failed?: boolean;
10
+ }
11
+
12
+ /**
13
+ * The "Connect as" state a connection is made with — the one shape both
14
+ * forms (the OAuth consent step, the connection-key form) hold, so the
15
+ * agents module owns the consent state and each page only says when its
16
+ * agents answered and what it does with the choice.
17
+ */
18
+ export interface ConnectAsChoiceState {
19
+ /** The agents on offer; Everything is always offered first. */
20
+ agents: readonly AgentChoice[];
21
+ /** The chosen agent's path, or null for Everything. */
22
+ value: string | null;
23
+ setValue: (agentPath: string | null) => void;
24
+ /** Set when the agents could not be loaded: Everything waits for the person to confirm it. */
25
+ unavailable: UnavailableChoice | undefined;
26
+ /** Whether a connection may be made with the choice as it stands (see {@link canConnectAs}). */
27
+ mayConnect: boolean;
28
+ /**
29
+ * The agents on offer have answered. `requestKey` names the request they
30
+ * answered for, when the page waits on one in particular (the consent
31
+ * step's authorization state): until that request's own answer is in,
32
+ * Everything is not yet a choice anyone made.
33
+ */
34
+ settle: (answer: AgentChoicesAnswer, requestKey?: string) => void;
35
+ }
36
+
37
+ /**
38
+ * The "Connect as" choice: Everything (null) unless the person picks an
39
+ * agent, settled once the agents on offer answer. A remembered choice that is
40
+ * no longer on offer falls back to Everything. With `expect`, the state is
41
+ * settled only when the answer named that request; without it, by any answer.
42
+ */
43
+ export function useConnectAsChoice(opts: { initial?: string | null | (() => string | null); expect?: string | null } = {}): ConnectAsChoiceState {
44
+ const [agents, setAgents] = useState<readonly AgentChoice[]>([]);
45
+ const [value, setValue] = useState<string | null>(opts.initial ?? null);
46
+ const [failed, setFailed] = useState(false);
47
+ const [settledFor, setSettledFor] = useState<string | null>(null);
48
+ const [everythingConfirmed, setEverythingConfirmed] = useState(false);
49
+
50
+ const settle = useCallback((answer: AgentChoicesAnswer, requestKey = '') => {
51
+ setAgents(answer.agents);
52
+ setFailed(answer.failed === true);
53
+ // A remembered choice that is no longer on offer falls back to Everything.
54
+ setValue((current) => (current && answer.agents.some((a) => a.path === current) ? current : null));
55
+ setSettledFor(requestKey);
56
+ }, []);
57
+
58
+ const unavailable = useMemo<UnavailableChoice | undefined>(
59
+ () => (failed ? { confirmed: everythingConfirmed, onConfirm: setEverythingConfirmed } : undefined),
60
+ [failed, everythingConfirmed],
61
+ );
62
+ const settled = opts.expect === undefined ? settledFor !== null : opts.expect != null && settledFor === opts.expect;
63
+ const mayConnect = canConnectAs({ settled, unavailable });
64
+
65
+ return { agents, value, setValue, unavailable, mayConnect, settle };
66
+ }