@bevel-software/platform-core-frontend 0.19.0 → 0.21.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 (52) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +6 -2
  3. package/src/modules/access/hooks/useFileAccess.ts +2 -2
  4. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +312 -0
  5. package/src/modules/audit/components/AuditEventsPanel.tsx +319 -0
  6. package/src/modules/audit/components/AuditLogPage.tsx +373 -0
  7. package/src/modules/audit/components/principal-grouping.ts +49 -0
  8. package/src/modules/audit/services/audit.api.ts +98 -0
  9. package/src/modules/auth/components/LoginScreen.tsx +1 -0
  10. package/src/modules/git/components/BranchSwitcher.tsx +9 -3
  11. package/src/modules/git/components/FileComparisonPanel.tsx +10 -4
  12. package/src/modules/git/components/PullNeededBanner.tsx +2 -2
  13. package/src/modules/git/services/error-messages.ts +2 -2
  14. package/src/modules/layout/__tests__/HeaderAlignment.test.tsx +110 -9
  15. package/src/modules/layout/components/SidebarFrame.tsx +26 -9
  16. package/src/modules/library/__tests__/DeleteToolDialog.test.tsx +11 -0
  17. package/src/modules/library/__tests__/LibraryRoutes.test.tsx +3 -0
  18. package/src/modules/library/__tests__/PluginIndexRow.test.tsx +146 -0
  19. package/src/modules/library/__tests__/PluginPage.test.tsx +110 -3
  20. package/src/modules/library/__tests__/ToolPage.test.tsx +20 -0
  21. package/src/modules/library/__tests__/name-with-badges.test.tsx +16 -3
  22. package/src/modules/library/__tests__/title-row-actions.ts +43 -0
  23. package/src/modules/library/components/PluginIndexRow.tsx +37 -20
  24. package/src/modules/library/components/PluginPage.tsx +115 -3
  25. package/src/modules/library/components/tool-page/ToolPage.tsx +25 -17
  26. package/src/modules/library/routes/library-paths.ts +9 -2
  27. package/src/modules/library/services/plugins.api.ts +45 -0
  28. package/src/modules/library/utils/plugin-summary.ts +7 -2
  29. package/src/modules/onboarding/__tests__/onboarding.test.tsx +43 -0
  30. package/src/modules/onboarding/components/ConnectAgentPill.tsx +13 -2
  31. package/src/modules/pr/components/OpenChangeRequestDialog.tsx +3 -2
  32. package/src/modules/review/components/ReviewPanel.tsx +2 -2
  33. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +2 -1
  34. package/src/modules/settings/settings-nav-items.tsx +11 -9
  35. package/src/modules/setup/components/SetupScreen.tsx +11 -0
  36. package/src/modules/setup/services/setup.api.ts +1 -1
  37. package/src/modules/toolbar/services/external-api-keys.api.ts +2 -0
  38. package/src/modules/workspace/components/FileExplorer.tsx +4 -2
  39. package/src/modules/workspace/components/FileViewer.tsx +14 -4
  40. package/src/modules/workspace/components/KbDocumentShell.tsx +50 -8
  41. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +60 -0
  42. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +99 -0
  43. package/src/modules/workspace/components/__tests__/KbDocumentShell.test.tsx +49 -1
  44. package/src/modules/workspace/hooks/useWorkspaceState.ts +7 -2
  45. package/src/modules/workspace/services/__tests__/workspace.api.test.ts +78 -1
  46. package/src/modules/workspace/utils/fileTree.ts +2 -1
  47. package/src/modules/workspace/utils/treeConfirm.ts +7 -3
  48. package/src/shared/theme/measure.ts +23 -2
  49. package/src/modules/admin/__tests__/ConnectionKeysPage.test.tsx +0 -266
  50. package/src/modules/admin/components/ConnectionKeysPage.tsx +0 -269
  51. package/src/modules/admin/components/connection-keys-grouping.ts +0 -43
  52. package/src/modules/admin/services/connection-keys.api.ts +0 -47
@@ -0,0 +1,373 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { Bot, ChevronRight, KeyRound } from 'lucide-react';
3
+ import { PageShell } from '../../../shared/components/PageShell';
4
+ import { Dialog } from '../../../shared/components/Dialog';
5
+ import { Badge, Banner, Button } from '../../../shared/components';
6
+ import { cn, formatRelativeTime } from '../../../lib/utils';
7
+ import { GITHUB_LINK_KIND } from '../../../shared/marketplace-url';
8
+ import { useAdmin } from '../../admin/state/admin.context';
9
+ import { useAuth } from '../../auth/state/auth.context';
10
+ import { listPrincipals, revokeAgent, revokeKey, type AuditPrincipal } from '../services/audit.api';
11
+ import { groupByAccount, principalKey } from './principal-grouping';
12
+ import { AuditEventsPanel } from './AuditEventsPanel';
13
+
14
+ /**
15
+ * The shared formatter, plus the one word it deliberately leaves to the caller:
16
+ * a key that has never been used has no instant to describe.
17
+ */
18
+ function formatRelative(ts: number | null): string {
19
+ return formatRelativeTime(ts) || 'never';
20
+ }
21
+
22
+ /** The exact instant, for a hover — the row shows the relative form. */
23
+ function formatAbsolute(ts: number | null): string | undefined {
24
+ return ts === null ? undefined : new Date(ts).toLocaleString();
25
+ }
26
+
27
+ /** What a row is, in the words the page uses: an OAuth agent, a Claude link, or a hand-made key. */
28
+ function kindLabel(p: AuditPrincipal): string {
29
+ if (p.kind === 'agent') return 'Agent · OAuth';
30
+ return p.keyKind === GITHUB_LINK_KIND ? 'Claude link' : 'Connection key';
31
+ }
32
+
33
+ function eventsLabel(n: number): string {
34
+ if (n === 0) return 'No events yet';
35
+ return `${n.toLocaleString()} ${n === 1 ? 'event' : 'events'}`;
36
+ }
37
+
38
+ /**
39
+ * The Audit log (`/audit-log`): every agent and connection key connected to
40
+ * your account — or, for admins, to every account — with when it connected,
41
+ * when it was last used and how much it has called; a revoke for each; and,
42
+ * under each row when opened, the list of what it called, newest first.
43
+ *
44
+ * It replaced the admin-only Connection keys overview. Keys are still minted
45
+ * and deleted for good on External agent access; here they are listed,
46
+ * watched and revoked beside the OAuth agents, which had no page at all.
47
+ *
48
+ * Revoking keeps the row (dimmed, marked with who revoked it) so its history
49
+ * stays readable. Revoked rows are hidden by default — on a busy deployment
50
+ * they outnumber the live ones — and a toggle brings them back.
51
+ */
52
+ export function AuditLogPage() {
53
+ const { user } = useAuth();
54
+ const { isAdmin, isAdminLoading } = useAdmin();
55
+ // The admin verdict decides which scope to ask for; asking before it has
56
+ // settled would fetch a member's list and then an admin's a moment later.
57
+ const settled = isAdminLoading !== true;
58
+
59
+ const [principals, setPrincipals] = useState<AuditPrincipal[] | null>(null);
60
+ const [error, setError] = useState<string | null>(null);
61
+ const [showRevoked, setShowRevoked] = useState(false);
62
+ const [query, setQuery] = useState('');
63
+ // Which rows are open, and which have EVER been opened: a panel stays
64
+ // mounted after its first open (hidden when collapsed), so re-expanding
65
+ // costs no request and keeps its filters and loaded pages.
66
+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});
67
+ const [opened, setOpened] = useState<Record<string, boolean>>({});
68
+ // The row awaiting revoke confirmation; non-null drives the confirm
69
+ // Dialog. `revoking` keeps the confirm open while the request is in flight.
70
+ const [pendingRevoke, setPendingRevoke] = useState<AuditPrincipal | null>(null);
71
+ const [revoking, setRevoking] = useState(false);
72
+
73
+ // Generation of the newest load. Two revokes in quick succession start two
74
+ // reloads, and the older one can land last — carrying a row the newer one
75
+ // already saw revoked. Only the latest load may write `principals`.
76
+ const loadGen = useRef(0);
77
+ const refresh = useCallback(() => {
78
+ const gen = ++loadGen.current;
79
+ listPrincipals(isAdmin ? 'all' : 'me')
80
+ .then((rows) => {
81
+ if (gen !== loadGen.current) return;
82
+ setPrincipals(rows);
83
+ setError(null);
84
+ })
85
+ .catch((err) => {
86
+ if (gen !== loadGen.current) return;
87
+ setError(err instanceof Error ? err.message : "Couldn't load the audit log.");
88
+ // `principals` is deliberately left alone: a reload that fails keeps
89
+ // the rows it had, and a first load that fails stays `null` rather
90
+ // than rendering "nothing connected" for a deployment we cannot reach.
91
+ });
92
+ }, [isAdmin]);
93
+
94
+ useEffect(() => {
95
+ if (settled) refresh();
96
+ }, [settled, refresh]);
97
+
98
+ const groups = useMemo(
99
+ () => (principals ? groupByAccount(principals, { includeRevoked: showRevoked, query: isAdmin ? query : '' }) : []),
100
+ [principals, showRevoked, query, isAdmin],
101
+ );
102
+ const liveCount = principals?.filter((p) => p.revokedAt === null).length ?? 0;
103
+ const revokedCount = (principals?.length ?? 0) - liveCount;
104
+ const accountCount = useMemo(() => new Set(principals?.map((p) => p.user.id)).size, [principals]);
105
+
106
+ const toggle = (key: string) => {
107
+ setExpanded((prev) => ({ ...prev, [key]: !prev[key] }));
108
+ setOpened((prev) => (prev[key] ? prev : { ...prev, [key]: true }));
109
+ };
110
+
111
+ async function confirmRevoke() {
112
+ if (!pendingRevoke || revoking) return;
113
+ setRevoking(true);
114
+ setError(null);
115
+ try {
116
+ const target = pendingRevoke;
117
+ if (target.kind === 'agent') await revokeAgent(target.id);
118
+ else await revokeKey(target.id);
119
+ // The server has revoked it; say so at once rather than waiting on the
120
+ // reload. If that reload fails, the row must not sit there looking live
121
+ // with a Revoke button — the agent holding it is already cut off.
122
+ const by: AuditPrincipal['revokedBy'] = user && target.user.id === user.id ? 'owner' : 'admin';
123
+ setPrincipals((prev) =>
124
+ prev
125
+ ? prev.map((p) =>
126
+ p.kind === target.kind && p.id === target.id && p.revokedAt === null
127
+ ? { ...p, revokedAt: Date.now(), revokedBy: by }
128
+ : p,
129
+ )
130
+ : prev,
131
+ );
132
+ setPendingRevoke(null);
133
+ refresh();
134
+ } catch (err) {
135
+ setPendingRevoke(null);
136
+ setError(err instanceof Error ? err.message : "Couldn't revoke this.");
137
+ } finally {
138
+ setRevoking(false);
139
+ }
140
+ }
141
+
142
+ const revokeVerb = (p: AuditPrincipal) => (p.kind === 'agent' ? 'Revoke access' : 'Revoke key');
143
+
144
+ return (
145
+ <>
146
+ <PageShell title="Audit log" width="4xl" card={false}>
147
+ <div className="space-y-4">
148
+ <p className="text-xs text-ink-muted leading-snug max-w-[65ch]">
149
+ {isAdmin
150
+ ? 'Every agent and connection key on this deployment, per account. Open one to see what it called and when. Revoking cuts the agent off immediately; the row stays so its history remains visible.'
151
+ : 'The agents and connection keys connected to your account. Open one to see what it called and when. Revoking cuts the agent off immediately; it can reconnect by signing in again.'}
152
+ </p>
153
+
154
+ {error && (
155
+ <Banner tone="danger" role="alert" className="text-detail">
156
+ {error}
157
+ </Banner>
158
+ )}
159
+
160
+ {principals !== null && (
161
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 text-xs text-ink-muted">
162
+ <span>
163
+ {isAdmin && `${accountCount} ${accountCount === 1 ? 'account' : 'accounts'} · `}
164
+ {liveCount} live
165
+ {revokedCount > 0 && ` · ${revokedCount} revoked`}
166
+ </span>
167
+ <div className="flex flex-wrap items-center gap-3">
168
+ {isAdmin && (
169
+ <input
170
+ value={query}
171
+ onChange={(e) => setQuery(e.target.value)}
172
+ placeholder="Filter by person or agent"
173
+ aria-label="Filter by person or agent"
174
+ className="bg-white border border-line rounded-sm px-2 py-1 text-detail text-ink focus:outline-none focus:border-accent min-w-[200px]"
175
+ />
176
+ )}
177
+ {revokedCount > 0 && (
178
+ <label className="flex items-center gap-1.5 cursor-pointer select-none">
179
+ <input
180
+ type="checkbox"
181
+ checked={showRevoked}
182
+ onChange={(e) => setShowRevoked(e.target.checked)}
183
+ />
184
+ Show revoked
185
+ </label>
186
+ )}
187
+ </div>
188
+ </div>
189
+ )}
190
+
191
+ {principals === null ? (
192
+ error ? null : <div className="text-xs text-ink-muted">Loading…</div>
193
+ ) : groups.length === 0 ? (
194
+ <div className="text-xs text-ink-muted">
195
+ {principals.length === 0
196
+ ? isAdmin
197
+ ? 'No agents or connection keys on this deployment.'
198
+ : 'Nothing connected to your account yet. Connect an agent from External agent access.'
199
+ : query.trim()
200
+ ? 'Nothing matches that filter.'
201
+ : 'No live agents or connection keys.'}
202
+ </div>
203
+ ) : (
204
+ <div className="space-y-5">
205
+ {groups.map((group) => {
206
+ const live = group.principals.filter((p) => p.revokedAt === null).length;
207
+ return (
208
+ <section key={group.user.id} aria-label={`Agents and keys for ${group.user.email}`}>
209
+ {isAdmin && (
210
+ <div className="flex items-baseline gap-2 px-1 pb-1.5">
211
+ <span className="text-sm font-medium truncate">{group.user.name}</span>
212
+ <span className="text-meta text-ink-muted truncate">{group.user.email}</span>
213
+ <span className="ml-auto text-meta text-ink-muted whitespace-nowrap">{live} live</span>
214
+ </div>
215
+ )}
216
+ <ul className="divide-y divide-line border border-line rounded-md bg-white shadow-card overflow-hidden">
217
+ {group.principals.map((p) => {
218
+ const key = principalKey(p);
219
+ const revoked = p.revokedAt !== null;
220
+ const open = !!expanded[key];
221
+ const panelId = `audit-events-${p.kind}-${p.id}`;
222
+ const Icon = p.kind === 'agent' ? Bot : KeyRound;
223
+ return (
224
+ <li key={key}>
225
+ {/* The WHOLE row opens the events, chevron at its far edge, the
226
+ way a disclosure row reads. A button cannot nest the Revoke
227
+ button, so the expand button is stretched over the row by
228
+ its ::after pseudo-element instead (padding, chevron and all)
229
+ and Revoke is raised above that overlay. `relative` stays on
230
+ THIS row div, not the <li>: the overlay must never cover the
231
+ events panel below. */}
232
+ <div
233
+ className={cn(
234
+ 'relative flex items-center gap-3 px-3 py-2 text-sm hover:bg-surface-hover',
235
+ open && 'bg-surface-hover',
236
+ )}
237
+ >
238
+ <button
239
+ type="button"
240
+ onClick={() => toggle(key)}
241
+ aria-expanded={open}
242
+ // Only once the panel exists: a reference to an id that is
243
+ // not in the document is an invalid one, and the panel is
244
+ // mounted on the row's first open.
245
+ aria-controls={opened[key] ? panelId : undefined}
246
+ className={cn(
247
+ 'flex flex-1 min-w-0 items-center gap-3 text-left',
248
+ "after:absolute after:inset-0 after:content-['']",
249
+ 'focus-visible:outline-none focus-visible:after:outline-2 focus-visible:after:-outline-offset-2 focus-visible:after:outline-accent',
250
+ revoked && 'opacity-60',
251
+ )}
252
+ >
253
+ <span
254
+ aria-hidden
255
+ className="flex-none size-7 rounded-sm bg-sunken inline-flex items-center justify-center text-ink-muted"
256
+ >
257
+ <Icon size={15} />
258
+ </span>
259
+ <span className="flex-1 min-w-0">
260
+ <span className="flex items-center gap-2 font-medium">
261
+ <span className="truncate">{p.label}</span>
262
+ <Badge tone="outline">{kindLabel(p)}</Badge>
263
+ {revoked && (
264
+ <Badge tone={p.revokedBy === 'admin' ? 'danger' : 'neutral'}>
265
+ {p.revokedBy === 'admin' ? 'Revoked by an admin' : 'Disconnected by owner'}
266
+ </Badge>
267
+ )}
268
+ {/* The owner deleted it from their own pages; the row and its
269
+ events stay here, for admins, until retention prunes them. */}
270
+ {p.deletedAt != null && <Badge tone="outline">Deleted by owner</Badge>}
271
+ </span>
272
+ <span className="block text-meta text-ink-muted">
273
+ <span title={formatAbsolute(p.createdAt)}>
274
+ {p.kind === 'agent' ? 'Connected' : 'Created'} {formatRelative(p.createdAt)}
275
+ </span>
276
+ {' · '}
277
+ <span title={formatAbsolute(p.lastUsedAt)}>Last used {formatRelative(p.lastUsedAt)}</span>
278
+ {revoked && (
279
+ <>
280
+ {' · '}
281
+ <span title={formatAbsolute(p.revokedAt)}>Revoked {formatRelative(p.revokedAt)}</span>
282
+ </>
283
+ )}
284
+ {' · '}
285
+ {eventsLabel(p.eventCount)}
286
+ </span>
287
+ </span>
288
+ </button>
289
+ {!revoked && (
290
+ <Button
291
+ variant="danger"
292
+ size="sm"
293
+ className="relative z-10"
294
+ onClick={() => setPendingRevoke(p)}
295
+ title={
296
+ p.kind === 'agent'
297
+ ? 'Revoke this agent’s access. It will have to sign in again to reconnect.'
298
+ : 'Revoke this key. The external agent using it will lose access.'
299
+ }
300
+ aria-label={`${revokeVerb(p)} for ${p.label} (${group.user.email})`}
301
+ >
302
+ {revokeVerb(p)}
303
+ </Button>
304
+ )}
305
+ <ChevronRight
306
+ aria-hidden
307
+ size={14}
308
+ className={cn('flex-none text-ink-faint transition-transform', open && 'rotate-90')}
309
+ />
310
+ </div>
311
+ {opened[key] && (
312
+ <div
313
+ id={panelId}
314
+ hidden={!open}
315
+ className="border-t border-line bg-sunken px-3 py-3"
316
+ >
317
+ <AuditEventsPanel kind={p.kind} id={p.id} label={p.label} />
318
+ </div>
319
+ )}
320
+ </li>
321
+ );
322
+ })}
323
+ </ul>
324
+ </section>
325
+ );
326
+ })}
327
+ </div>
328
+ )}
329
+ </div>
330
+ </PageShell>
331
+
332
+ <Dialog
333
+ open={pendingRevoke !== null}
334
+ onClose={() => setPendingRevoke(null)}
335
+ title={pendingRevoke?.kind === 'agent' ? 'Revoke agent access' : 'Revoke connection key'}
336
+ size="sm"
337
+ busy={revoking}
338
+ footer={
339
+ <>
340
+ <Button variant="outline" onClick={() => setPendingRevoke(null)} disabled={revoking}>
341
+ Cancel
342
+ </Button>
343
+ <Button variant="danger" onClick={confirmRevoke} disabled={revoking}>
344
+ {revoking ? 'Revoking…' : pendingRevoke ? revokeVerb(pendingRevoke) : 'Revoke'}
345
+ </Button>
346
+ </>
347
+ }
348
+ >
349
+ <p className="text-xs text-ink leading-snug">
350
+ {pendingRevoke?.kind === 'agent' ? (
351
+ <>
352
+ Revoke <span className="font-medium">{pendingRevoke.label}</span>&rsquo;s access for{' '}
353
+ <span className="font-medium">
354
+ {pendingRevoke.user.name} ({pendingRevoke.user.email})
355
+ </span>
356
+ ? Every token it holds stops working now. It can reconnect only by signing in again through the
357
+ browser. Its history stays visible here.
358
+ </>
359
+ ) : (
360
+ <>
361
+ Revoke <span className="font-medium">{pendingRevoke?.label}</span> belonging to{' '}
362
+ <span className="font-medium">
363
+ {pendingRevoke?.user.name} ({pendingRevoke?.user.email})
364
+ </span>
365
+ ? Whatever is using it loses access immediately. The key stays listed so its history remains
366
+ visible; its owner can delete it for good from External agent access.
367
+ </>
368
+ )}
369
+ </p>
370
+ </Dialog>
371
+ </>
372
+ );
373
+ }
@@ -0,0 +1,49 @@
1
+ import type { AuditPrincipal } from '../services/audit.api';
2
+
3
+ export interface AccountGroup {
4
+ user: AuditPrincipal['user'];
5
+ principals: AuditPrincipal[];
6
+ }
7
+
8
+ /** The React key / disclosure id for one row — kinds share no id space, so both go in. */
9
+ export function principalKey(p: Pick<AuditPrincipal, 'kind' | 'id'>): string {
10
+ return `${p.kind}:${p.id}`;
11
+ }
12
+
13
+ /**
14
+ * One list from the server, grouped per account in the order the server
15
+ * returned it (owner email; live before revoked, most recently used first).
16
+ * Revoked rows are dropped unless asked for, and an account left with no
17
+ * rows disappears with them.
18
+ *
19
+ * `query` narrows to accounts or rows whose name, email or label contains it
20
+ * (case-insensitive) — the admin's "find that agent" box. A match on the
21
+ * account keeps every row of it; a match on a row keeps just that row.
22
+ *
23
+ * Lives beside {@link AuditLogPage} rather than in it: a component file that
24
+ * also exports a plain function breaks fast refresh.
25
+ */
26
+ export function groupByAccount(
27
+ principals: AuditPrincipal[],
28
+ opts: { includeRevoked: boolean; query?: string },
29
+ ): AccountGroup[] {
30
+ const q = (opts.query ?? '').trim().toLowerCase();
31
+ const groups: AccountGroup[] = [];
32
+ const byUser = new Map<string, AccountGroup>();
33
+ for (const p of principals) {
34
+ if (!opts.includeRevoked && p.revokedAt !== null) continue;
35
+ if (q) {
36
+ const accountHit = p.user.name.toLowerCase().includes(q) || p.user.email.toLowerCase().includes(q);
37
+ const rowHit = p.label.toLowerCase().includes(q);
38
+ if (!accountHit && !rowHit) continue;
39
+ }
40
+ let group = byUser.get(p.user.id);
41
+ if (!group) {
42
+ group = { user: p.user, principals: [] };
43
+ byUser.set(p.user.id, group);
44
+ groups.push(group);
45
+ }
46
+ group.principals.push(p);
47
+ }
48
+ return groups;
49
+ }
@@ -0,0 +1,98 @@
1
+ import { authFetch } from '../../../lib/api';
2
+
3
+ /**
4
+ * The Audit log's client: the agents and keys a person (or, for admins, the
5
+ * deployment) has connected, what each of them called, and the revoke of
6
+ * either. Types mirror the backend's `audit.contract.ts`; re-declared here
7
+ * rather than shared, like the admin inbox's, because the feature is small.
8
+ */
9
+
10
+ export type AuditPrincipalKind = 'key' | 'agent';
11
+
12
+ /** One row of the Audit log: an agent connection or a connection key, with its owner. */
13
+ export interface AuditPrincipal {
14
+ kind: AuditPrincipalKind;
15
+ id: string;
16
+ /** The key's label, or the agent's registered name ("Claude"). */
17
+ label: string;
18
+ /** For a key: `key` by hand, `github-link` for a Claude link. Absent for an agent. */
19
+ keyKind?: string;
20
+ /** When the key was created / the agent connected. Epoch ms. */
21
+ createdAt: number;
22
+ lastUsedAt: number | null;
23
+ revokedAt: number | null;
24
+ /** Who ended it once revoked: the owner, or an admin. Null while live. */
25
+ revokedBy: 'owner' | 'admin' | null;
26
+ /** For a key: when its owner deleted it for good. Only admins see such rows. */
27
+ deletedAt?: number | null;
28
+ /** Events on record for it. */
29
+ eventCount: number;
30
+ user: { id: string; email: string; name: string };
31
+ }
32
+
33
+ export type AgentEventKind = 'capability' | 'tool' | 'skill';
34
+ export type AgentEventOutcome = 'ok' | 'error' | 'denied';
35
+
36
+ export interface AgentEvent {
37
+ id: string;
38
+ kind: AgentEventKind;
39
+ /** The MCP server / `.tool` manual for a tool, the skill folder for a skill; null for a capability. */
40
+ manual: string | null;
41
+ name: string;
42
+ outcome: AgentEventOutcome;
43
+ /** Epoch ms. */
44
+ at: number;
45
+ }
46
+
47
+ export interface AgentEventPage {
48
+ events: AgentEvent[];
49
+ /** Every event on record for the principal — on the first page only; null on a page reached through a cursor. */
50
+ total: number | null;
51
+ /** Pass back as `before` for the next (older) page; null on the last. */
52
+ nextCursor: string | null;
53
+ }
54
+
55
+ async function readError(res: Response, fallback: string): Promise<string> {
56
+ const body = await res.json().catch(() => ({}));
57
+ return (body as { error?: string }).error || fallback;
58
+ }
59
+
60
+ /** Your own agents and keys, or (admins) everyone's. Ordered by owner, live first, most recently used first. */
61
+ export async function listPrincipals(scope: 'me' | 'all'): Promise<AuditPrincipal[]> {
62
+ const res = await authFetch(`/api/audit/principals?scope=${scope}`);
63
+ if (!res.ok) throw new Error(await readError(res, 'Could not load the audit log'));
64
+ const body = (await res.json()) as { principals: AuditPrincipal[] };
65
+ return body.principals;
66
+ }
67
+
68
+ /** One principal's events, newest first; `before` continues from a previous page's cursor. */
69
+ export async function listEvents(
70
+ kind: AuditPrincipalKind,
71
+ id: string,
72
+ opts: { before?: string; limit?: number } = {},
73
+ ): Promise<AgentEventPage> {
74
+ const qs = new URLSearchParams();
75
+ if (opts.before) qs.set('before', opts.before);
76
+ if (opts.limit) qs.set('limit', String(opts.limit));
77
+ const query = qs.toString();
78
+ const res = await authFetch(
79
+ `/api/audit/principals/${kind}/${encodeURIComponent(id)}/events${query ? `?${query}` : ''}`,
80
+ );
81
+ if (!res.ok) throw new Error(await readError(res, 'Could not load events'));
82
+ return (await res.json()) as AgentEventPage;
83
+ }
84
+
85
+ /**
86
+ * Cut an agent off: every token it holds stops working, and it can only
87
+ * come back by signing in again through the browser. Its row and events stay.
88
+ */
89
+ export async function revokeAgent(id: string): Promise<void> {
90
+ const res = await authFetch(`/api/audit/agents/${encodeURIComponent(id)}`, { method: 'DELETE' });
91
+ if (!res.ok) throw new Error(await readError(res, 'Could not revoke this agent'));
92
+ }
93
+
94
+ /** Revoke a connection key (own, or as an admin anyone's). The row stays so its history remains visible. */
95
+ export async function revokeKey(id: string): Promise<void> {
96
+ const res = await authFetch(`/api/audit/keys/${encodeURIComponent(id)}`, { method: 'DELETE' });
97
+ if (!res.ok) throw new Error(await readError(res, 'Could not revoke this key'));
98
+ }
@@ -12,6 +12,7 @@ const OAUTH_ERROR_MESSAGES: Record<string, string> = {
12
12
  auth: 'Sign-in failed. Please try again.',
13
13
  start: 'Could not start sign-in. Please try again.',
14
14
  not_configured: 'Single sign-on is not configured on this deployment.',
15
+ admission: 'This workspace has no seat available for your account. Ask its admin.',
15
16
  };
16
17
 
17
18
  export function LoginScreen() {
@@ -2,7 +2,13 @@ import { useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { createPortal } from 'react-dom';
3
3
  import { useLocation, useNavigate } from 'react-router-dom';
4
4
  import { ChevronDown, GitBranch, Plus, Lock, Check, GitPullRequest, Trash2, Loader2 } from 'lucide-react';
5
- import { protectedBranchDisplayName, branchAuthorLocalpart, isBranchAuthoredBy, DEFAULT_BRANCH } from '@bevel-software/platform-shared';
5
+ import {
6
+ protectedBranchDisplayName,
7
+ currentBranchModel,
8
+ branchAuthorLocalpart,
9
+ isBranchAuthoredBy,
10
+ DEFAULT_BRANCH,
11
+ } from '@bevel-software/platform-shared';
6
12
  import { useGit } from '../state/git.context';
7
13
  import { parseGitError, type GitErrorInfo } from '../services/error-messages';
8
14
  import { useAuth } from '../../auth/state/auth.context';
@@ -192,7 +198,7 @@ export function BranchSwitcher() {
192
198
  // shared draft" is wrong, it's the official version everyone sees.
193
199
  const branchLabel = (() => {
194
200
  if (switchingTo) return `Switching to ${switchingTo}…`;
195
- const protectedName = protectedBranchDisplayName(git.status?.branch);
201
+ const protectedName = protectedBranchDisplayName(currentBranchModel(), git.status?.branch);
196
202
  if (protectedName) return `${protectedName} (official version)`;
197
203
  return 'Your active shared draft';
198
204
  })();
@@ -403,7 +409,7 @@ export function BranchSwitcher() {
403
409
  </div>
404
410
  )}
405
411
  {targetBranches.map((b) => {
406
- const displayName = protectedBranchDisplayName(b.name);
412
+ const displayName = protectedBranchDisplayName(currentBranchModel(), b.name);
407
413
  // Default destination for shared drafts: visually distinguish
408
414
  // the default branch so users see the recommended path without
409
415
  // having to read the slug. Others stay available, just quieter.
@@ -8,7 +8,13 @@ import {
8
8
  AlertTriangle,
9
9
  RefreshCw,
10
10
  } from 'lucide-react';
11
- import { protectedBranchDisplayName, isProtectedBranch, DEFAULT_BRANCH, type BranchInfo } from '@bevel-software/platform-shared';
11
+ import {
12
+ protectedBranchDisplayName,
13
+ isProtectedBranch,
14
+ currentBranchModel,
15
+ DEFAULT_BRANCH,
16
+ type BranchInfo,
17
+ } from '@bevel-software/platform-shared';
12
18
  import { useGit } from '../state/git.context';
13
19
  import { UnifiedDiffView } from './UnifiedDiffView';
14
20
  import { friendlyGitError } from '../services/error-messages';
@@ -84,7 +90,7 @@ function defaultFromForCurrent(
84
90
  // On a protected branch, prefer the default branch as the comparison base so
85
91
  // the picker opens on the canonical "official vs official" diff; if we're
86
92
  // already on the default branch, any other protected branch works.
87
- if (isProtectedBranch(currentBranch)) {
93
+ if (isProtectedBranch(currentBranchModel(), currentBranch)) {
88
94
  if (currentBranch !== DEFAULT_BRANCH && others.some((b) => b.name === DEFAULT_BRANCH)) {
89
95
  return DEFAULT_BRANCH;
90
96
  }
@@ -313,7 +319,7 @@ function BranchPicker({ label, value, branches, onChange }: BranchPickerProps) {
313
319
  const valueIsProtected = !!value && (
314
320
  branches.find((b) => b.name === value)?.isProtected ?? false
315
321
  );
316
- const valueDisplay = value ? protectedBranchDisplayName(value) ?? value : 'Select…';
322
+ const valueDisplay = value ? protectedBranchDisplayName(currentBranchModel(), value) ?? value : 'Select…';
317
323
 
318
324
  return (
319
325
  <div ref={ref} className="relative flex-1 min-w-0">
@@ -341,7 +347,7 @@ function BranchPicker({ label, value, branches, onChange }: BranchPickerProps) {
341
347
  <div className="px-3 py-2 text-xs text-ink-muted">No branches.</div>
342
348
  )}
343
349
  {branches.map((b) => {
344
- const display = protectedBranchDisplayName(b.name);
350
+ const display = protectedBranchDisplayName(currentBranchModel(), b.name);
345
351
  const isSelected = b.name === value;
346
352
  return (
347
353
  <button
@@ -1,6 +1,6 @@
1
1
  import { useState } from 'react';
2
2
  import { GitMerge } from 'lucide-react';
3
- import { isProtectedBranch } from '@bevel-software/platform-shared';
3
+ import { currentBranchModel, isProtectedBranch } from '@bevel-software/platform-shared';
4
4
  import { useGit } from '../state/git.context';
5
5
  import { useAutoUpdate } from '../state/auto-update.context';
6
6
  import { useCrCreationPort } from '../../../core/registry';
@@ -63,7 +63,7 @@ export function PullNeededBanner() {
63
63
  // Captured for the handlers below — TS control-flow narrowing on `status`
64
64
  // doesn't survive into nested function declarations.
65
65
  const branchName = status.branch;
66
- const onProtectedBranch = isProtectedBranch(status.branch);
66
+ const onProtectedBranch = isProtectedBranch(currentBranchModel(), status.branch);
67
67
  const hasUnsavedEditorChanges = !!workspace.hasUnsavedFileChanges;
68
68
  // Under save=share the working tree is never dirty and there are no
69
69
  // mid-merge conflicts to gate on — the only thing that can still block
@@ -1,4 +1,4 @@
1
- import { protectedBranchDisplayName } from '@bevel-software/platform-shared';
1
+ import { currentBranchModel, protectedBranchDisplayName } from '@bevel-software/platform-shared';
2
2
  import { GitApiError } from './git.api';
3
3
 
4
4
  /**
@@ -74,7 +74,7 @@ export function parseGitError(err: unknown): GitErrorInfo {
74
74
  * "Target company state" instead of `target-company-state`.
75
75
  */
76
76
  function friendlyNoSharedHistoryMessage(base: string): string {
77
- const baseName = protectedBranchDisplayName(base) ?? base;
77
+ const baseName = protectedBranchDisplayName(currentBranchModel(), base) ?? base;
78
78
  return (
79
79
  `This draft doesn't share history with the ${baseName}. It was likely started ` +
80
80
  `from an unrelated point or outside the app. The assistant can investigate and ` +