@bevel-software/platform-core-frontend 0.4.0 → 0.4.1

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 (30) hide show
  1. package/package.json +2 -2
  2. package/src/core/__tests__/ShellRoutes.test.tsx +95 -95
  3. package/src/lib/utils.ts +138 -138
  4. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +156 -156
  5. package/src/modules/admin/components/UserAccountsPage.tsx +353 -353
  6. package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -104
  7. package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -200
  8. package/src/modules/library/__tests__/loadout.test.tsx +72 -72
  9. package/src/modules/library/__tests__/status.test.ts +117 -117
  10. package/src/modules/library/components/ChangeRequestDock.tsx +47 -47
  11. package/src/modules/library/components/CompareView.tsx +357 -357
  12. package/src/modules/library/components/DetailDialog.tsx +566 -566
  13. package/src/modules/library/components/GearIcon.tsx +12 -12
  14. package/src/modules/library/components/LibraryCard.tsx +132 -132
  15. package/src/modules/library/components/LibraryPage.tsx +254 -254
  16. package/src/modules/library/components/LoadoutSidebar.tsx +156 -156
  17. package/src/modules/library/components/StatusGem.tsx +21 -21
  18. package/src/modules/library/components/SuggestChange.tsx +171 -171
  19. package/src/modules/library/components/particles.ts +50 -50
  20. package/src/modules/library/library.css +320 -320
  21. package/src/modules/library/state/loadout.tsx +129 -129
  22. package/src/modules/library/utils/status.ts +116 -116
  23. package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -276
  24. package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -51
  25. package/src/modules/toolbar/components/AppSwitcher.tsx +108 -108
  26. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -548
  27. package/src/modules/workspace/components/FileExplorer.tsx +1068 -1068
  28. package/src/modules/workspace/components/FileViewer.tsx +906 -906
  29. package/src/modules/workspace/utils/fileTree.ts +179 -179
  30. package/src/shared/components/PageShell.tsx +51 -51
@@ -1,548 +1,548 @@
1
- import { useCallback, useEffect, useId, useState } from 'react';
2
- import { Link } from 'react-router-dom';
3
- import { Check, Copy, Wrench, ExternalLink } from 'lucide-react';
4
- import { Dialog } from '../../../shared/components/Dialog';
5
- import { PageShell } from '../../../shared/components/PageShell';
6
- import {
7
- type ExternalApiKeySummary,
8
- type MintedExternalApiKey,
9
- createExternalApiKey,
10
- deleteExternalApiKey,
11
- disconnectExternalApiKey,
12
- listExternalApiKeys,
13
- } from '../services/external-api-keys.api';
14
-
15
- /**
16
- * "Copied" affordance with a 1500ms auto-reset. Owns the timer + its teardown
17
- * (so an unmounting page can't fire a stale setState), shared by the reveal
18
- * modal and every CopyBlock. `copy(text)` writes to the clipboard and flags
19
- * copied; a rejected write (insecure context / denied permission) leaves the
20
- * textarea selectable for manual copy and shows no false "Copied".
21
- */
22
- function useCopyFeedback(): { copied: boolean; copy: (text: string) => void } {
23
- const [copied, setCopied] = useState(false);
24
- useEffect(() => {
25
- if (!copied) return;
26
- const timerId = window.setTimeout(() => setCopied(false), 1500);
27
- return () => window.clearTimeout(timerId);
28
- }, [copied]);
29
- const copy = useCallback((text: string) => {
30
- void navigator.clipboard
31
- .writeText(text)
32
- .then(() => setCopied(true))
33
- .catch(() => {});
34
- }, []);
35
- return { copied, copy };
36
- }
37
-
38
- const MAX_LABEL_LEN = 200;
39
-
40
- function formatRelative(ts: number | null): string {
41
- if (ts === null) return 'never';
42
- const diff = Date.now() - ts;
43
- const minutes = Math.round(diff / 60_000);
44
- if (minutes < 1) return 'just now';
45
- if (minutes < 60) return `${minutes} min ago`;
46
- const hours = Math.round(minutes / 60);
47
- if (hours < 24) return `${hours} hr ago`;
48
- const days = Math.round(hours / 24);
49
- if (days < 30) return `${days} day${days === 1 ? '' : 's'} ago`;
50
- return new Date(ts).toLocaleDateString();
51
- }
52
-
53
- /**
54
- * The External agent access page, routed standalone at
55
- * `/external-agent-access` (below the persistent toolbar), in two tabs:
56
- *
57
- * - "Your agent" (default) — connecting the user's own interactive agent
58
- * (Claude Code, Claude Desktop, Cursor…). No key: the agent gets only the
59
- * server URL, and on first connect the browser opens our authorization
60
- * flow (sign in + choose tools on /connect). Copy-paste configs only.
61
- * - "Autonomous agents" — the external-API-key surface for pipelines/CI
62
- * that can't open a browser: lists existing keys, mints new ones,
63
- * disconnects revoked ones, permanently deletes disconnected ones. The
64
- * plaintext of a minted key is only shown once — there is no read-it-back
65
- * endpoint.
66
- *
67
- * Glossary terms used in copy: "External API key", "Disconnect" (= revoke),
68
- * "External agent" (= MCP client). See docs/glossary.md.
69
- */
70
- export function ExternalAgentAccessPage() {
71
- const labelInputId = useId();
72
-
73
- const [tab, setTab] = useState<'agent' | 'autonomous'>('agent');
74
- const [keys, setKeys] = useState<ExternalApiKeySummary[]>([]);
75
- const [loading, setLoading] = useState(false);
76
- const [loadError, setLoadError] = useState<string | null>(null);
77
-
78
- const [label, setLabel] = useState('');
79
- const [creating, setCreating] = useState(false);
80
- const [createError, setCreateError] = useState<string | null>(null);
81
-
82
- // The plaintext of a freshly minted key. Held in state for the lifetime
83
- // of the reveal modal — never persisted, and cleared when the user
84
- // dismisses the reveal step.
85
- const [reveal, setReveal] = useState<MintedExternalApiKey | null>(null);
86
- const { copied, copy } = useCopyFeedback();
87
-
88
- // The disconnected key awaiting a permanent-delete confirmation. Non-null
89
- // drives the themed confirm Dialog below; `deleting` keeps the request in
90
- // flight so the confirm can't be dismissed mid-delete.
91
- const [pendingDelete, setPendingDelete] = useState<{ id: string; label: string } | null>(null);
92
- const [deleting, setDeleting] = useState(false);
93
-
94
- const refresh = useCallback(async () => {
95
- setLoading(true);
96
- setLoadError(null);
97
- try {
98
- setKeys(await listExternalApiKeys());
99
- } catch (err) {
100
- setLoadError(err instanceof Error ? err.message : "Couldn't load external API keys.");
101
- } finally {
102
- setLoading(false);
103
- }
104
- }, []);
105
-
106
- useEffect(() => {
107
- void refresh();
108
- }, [refresh]);
109
-
110
- async function handleCreate() {
111
- const trimmed = label.trim();
112
- if (trimmed.length === 0 || trimmed.length > MAX_LABEL_LEN || creating) return;
113
- setCreating(true);
114
- setCreateError(null);
115
- try {
116
- const minted = await createExternalApiKey(trimmed);
117
- setReveal(minted);
118
- setLabel('');
119
- // Optimistic-ish: refresh the list so the new row shows up underneath
120
- // the reveal modal.
121
- void refresh();
122
- } catch (err) {
123
- setCreateError(err instanceof Error ? err.message : "Couldn't create external API key.");
124
- } finally {
125
- setCreating(false);
126
- }
127
- }
128
-
129
- async function handleDisconnect(id: string) {
130
- try {
131
- await disconnectExternalApiKey(id);
132
- await refresh();
133
- } catch (err) {
134
- setLoadError(err instanceof Error ? err.message : "Couldn't disconnect this key.");
135
- }
136
- }
137
-
138
- async function confirmDelete() {
139
- if (!pendingDelete || deleting) return;
140
- setDeleting(true);
141
- try {
142
- await deleteExternalApiKey(pendingDelete.id);
143
- setPendingDelete(null);
144
- await refresh();
145
- } catch (err) {
146
- setLoadError(err instanceof Error ? err.message : "Couldn't delete this key.");
147
- setPendingDelete(null);
148
- } finally {
149
- setDeleting(false);
150
- }
151
- }
152
-
153
- const trimmed = label.trim();
154
- const canSubmit = trimmed.length > 0 && trimmed.length <= MAX_LABEL_LEN && !creating;
155
-
156
- // Surface the keys that matter: active keys first (most-recently-used at the
157
- // top, never-used ones last within that group), with disconnected keys sunk
158
- // to the bottom. Non-destructive — nothing is hidden or deleted, just ordered
159
- // so a long list of stale/test keys doesn't bury the ones in use.
160
- const sortedKeys = [...keys].sort((a, b) => {
161
- const aRevoked = a.revokedAt !== null;
162
- const bRevoked = b.revokedAt !== null;
163
- if (aRevoked !== bRevoked) return aRevoked ? 1 : -1;
164
- return (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0);
165
- });
166
-
167
- return (
168
- <>
169
- <PageShell title="External agent access" padded={false}>
170
- <div className="flex border-b border-slate-200 px-4 shrink-0" role="tablist">
171
- {(
172
- [
173
- ['agent', 'Your agent'],
174
- ['autonomous', 'Autonomous agents'],
175
- ] as const
176
- ).map(([id, name]) => (
177
- <button
178
- key={id}
179
- role="tab"
180
- aria-selected={tab === id}
181
- onClick={() => setTab(id)}
182
- className={`px-3 py-2 text-xs font-medium border-b-2 -mb-px ${
183
- tab === id
184
- ? 'border-bevel text-slate-900'
185
- : 'border-transparent text-slate-500 hover:text-slate-800'
186
- }`}
187
- >
188
- {name}
189
- </button>
190
- ))}
191
- </div>
192
-
193
- {tab === 'agent' && (
194
- <div className="px-4 py-3 space-y-4">
195
- <p className="text-xs text-slate-600 leading-snug">
196
- Connect your own agent — Claude Code, Claude Desktop, Cursor and similar. No key
197
- needed: the first time the agent connects, your browser opens so you can sign in and
198
- choose which tools to share with it. Everything it saves appears under your name.
199
- </p>
200
- <Link
201
- to="/connect"
202
- target="_blank"
203
- rel="noopener noreferrer"
204
- className="flex items-center justify-center gap-1.5 rounded border border-slate-200 px-2 py-1.5 text-xs text-slate-700 hover:bg-slate-100"
205
- >
206
- <Wrench size={12} />
207
- Configure your tools
208
- <ExternalLink size={11} className="opacity-60" />
209
- </Link>
210
- <CopyBlock
211
- label="Connect Claude Code"
212
- value={`claude mcp add --transport http knowledge-base ${window.location.origin}/api/mcp`}
213
- rows={2}
214
- />
215
- <div>
216
- <div className="text-xs font-medium text-slate-700 mb-1">claude.ai / Claude Desktop</div>
217
- <p className="text-[11px] text-slate-600 mb-1 leading-snug">
218
- Settings → Connectors → Add custom connector, then paste this URL. When asked to
219
- authorize, your browser opens this app to finish connecting.
220
- </p>
221
- <CopyBlock label={null} value={`${window.location.origin}/api/mcp`} rows={1} />
222
- </div>
223
- <div>
224
- <div className="text-xs font-medium text-slate-700 mb-1">Other agents (JSON config)</div>
225
- <p className="text-[11px] text-slate-600 mb-1 leading-snug">
226
- Works with Cursor, Windsurf, Cline, and most clients that load servers from a JSON
227
- config and support signing in.
228
- </p>
229
- <CopyBlock
230
- label={null}
231
- value={JSON.stringify(
232
- {
233
- mcpServers: {
234
- 'knowledge-base': {
235
- type: 'http',
236
- url: `${window.location.origin}/api/mcp`,
237
- },
238
- },
239
- },
240
- null,
241
- 2,
242
- )}
243
- rows={9}
244
- />
245
- </div>
246
- <p className="text-[11px] text-slate-500 leading-snug">
247
- Running an unattended pipeline or CI agent that can't open a browser? Use the{' '}
248
- <button
249
- type="button"
250
- onClick={() => setTab('autonomous')}
251
- className="underline text-slate-600 hover:text-slate-900"
252
- >
253
- Autonomous agents
254
- </button>{' '}
255
- tab instead.
256
- </p>
257
- </div>
258
- )}
259
-
260
- {tab === 'autonomous' && (
261
- <div className="px-4 py-3 space-y-4">
262
- <p className="text-xs text-slate-600 leading-snug">
263
- For autonomous agents and pipelines (CI, scheduled jobs) that can't open a browser to
264
- sign in. Create an external API key and give it to the agent. Each key carries your
265
- identity, so any saves the agent makes appear under your name — and it only gets the
266
- tools you've already connected on the Connect your tools page.
267
- </p>
268
-
269
- <div className="border border-slate-200 rounded p-3 space-y-2">
270
- <label htmlFor={labelInputId} className="block text-xs font-medium text-slate-700">
271
- Create an external API key
272
- </label>
273
- <div className="flex gap-2">
274
- <input
275
- id={labelInputId}
276
- value={label}
277
- onChange={(e) => setLabel(e.target.value)}
278
- placeholder="e.g. Claude Code on my laptop"
279
- maxLength={MAX_LABEL_LEN}
280
- className="flex-1 bg-white border border-slate-200 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-slate-300"
281
- onKeyDown={(e) => {
282
- if (e.key === 'Enter' && canSubmit) handleCreate();
283
- }}
284
- />
285
- <button
286
- onClick={handleCreate}
287
- disabled={!canSubmit}
288
- className="px-3 py-1.5 text-sm rounded bg-bevel hover:bg-bevel-deep text-white disabled:opacity-50 disabled:hover:bg-bevel"
289
- >
290
- {creating ? 'Creating…' : 'Create key'}
291
- </button>
292
- </div>
293
- {createError && (
294
- <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
295
- {createError}
296
- </div>
297
- )}
298
- </div>
299
-
300
- <div className="space-y-2">
301
- <div className="text-xs font-medium text-slate-700">Your external API keys</div>
302
- {loadError && (
303
- <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
304
- {loadError}
305
- </div>
306
- )}
307
- {loading ? (
308
- <div className="text-xs text-slate-600">Loading…</div>
309
- ) : keys.length === 0 ? (
310
- <div className="text-xs text-slate-600">No external API keys yet.</div>
311
- ) : (
312
- <ul className="divide-y divide-slate-200 border border-slate-200 rounded">
313
- {sortedKeys.map((k) => {
314
- const revoked = k.revokedAt !== null;
315
- const usage = !revoked ? k.llmUsage : undefined;
316
- const cap = usage?.dailyTokenCap ?? 0;
317
- const used = usage?.usedTodayTokens ?? 0;
318
- const pct = cap > 0 ? Math.min(100, Math.round((used / cap) * 100)) : 0;
319
- const overCap = cap > 0 && used >= cap;
320
- return (
321
- <li
322
- key={k.id}
323
- className={`flex items-center gap-3 px-3 py-2 text-sm ${
324
- revoked ? 'opacity-60' : ''
325
- }`}
326
- >
327
- <div className="flex-1 min-w-0">
328
- <div className="font-medium truncate">{k.label}</div>
329
- <div className="text-[11px] text-slate-600">
330
- Created {formatRelative(k.createdAt)} · Last used {formatRelative(k.lastUsedAt)}
331
- {revoked && ' · Disconnected'}
332
- </div>
333
- {usage && (
334
- <div className="mt-1 max-w-xs">
335
- <div
336
- className={`flex items-center justify-between text-[11px] ${
337
- overCap ? 'text-red-600' : 'text-slate-600'
338
- }`}
339
- >
340
- <span>Model usage today</span>
341
- <span>
342
- {used.toLocaleString()} / {cap.toLocaleString()} tokens
343
- </span>
344
- </div>
345
- <div className="mt-0.5 h-1 rounded bg-slate-100 overflow-hidden">
346
- <div
347
- className={`h-full ${overCap ? 'bg-red-500' : 'bg-bevel'}`}
348
- style={{ width: `${pct}%` }}
349
- />
350
- </div>
351
- </div>
352
- )}
353
- </div>
354
- {revoked ? (
355
- <button
356
- onClick={() => setPendingDelete({ id: k.id, label: k.label })}
357
- className="text-xs px-2 py-1 rounded text-red-600 hover:bg-red-50 border border-slate-200"
358
- title="Permanently delete this disconnected key and its usage history."
359
- >
360
- Delete
361
- </button>
362
- ) : (
363
- <button
364
- onClick={() => handleDisconnect(k.id)}
365
- className="text-xs px-2 py-1 rounded text-slate-700 hover:bg-slate-100 border border-slate-200"
366
- title="Disconnect this external API key. The external agent using it will lose access."
367
- >
368
- Disconnect
369
- </button>
370
- )}
371
- </li>
372
- );
373
- })}
374
- </ul>
375
- )}
376
- </div>
377
- </div>
378
- )}
379
- </PageShell>
380
-
381
- <Dialog
382
- open={pendingDelete !== null}
383
- onClose={() => setPendingDelete(null)}
384
- title="Delete external API key"
385
- size="sm"
386
- busy={deleting}
387
- footer={
388
- <>
389
- <button
390
- onClick={() => setPendingDelete(null)}
391
- disabled={deleting}
392
- className="px-3 py-1.5 text-sm rounded text-slate-700 hover:bg-slate-100 border border-slate-200 disabled:opacity-50"
393
- >
394
- Cancel
395
- </button>
396
- <button
397
- onClick={confirmDelete}
398
- disabled={deleting}
399
- className="px-3 py-1.5 text-sm rounded bg-red-600 hover:bg-red-700 text-white disabled:opacity-50 disabled:hover:bg-red-600"
400
- >
401
- {deleting ? 'Deleting…' : 'Delete'}
402
- </button>
403
- </>
404
- }
405
- >
406
- <p className="text-xs text-slate-700 leading-snug">
407
- Permanently delete{' '}
408
- <span className="font-medium">&ldquo;{pendingDelete?.label}&rdquo;</span>? This removes it
409
- and its usage history for good.
410
- </p>
411
- </Dialog>
412
-
413
- {reveal && (
414
- <div
415
- className="fixed inset-0 z-[60] bg-slate-900/40 flex items-center justify-center p-4"
416
- onClick={(e) => e.stopPropagation()}
417
- >
418
- <div
419
- role="alertdialog"
420
- aria-modal="true"
421
- className="bg-white border border-slate-200 rounded-lg shadow-xl w-full max-w-xl max-h-[90vh] overflow-y-auto"
422
- >
423
- <div className="px-4 py-3 border-b border-slate-200">
424
- <h3 className="text-sm font-semibold">Save this external API key now</h3>
425
- </div>
426
- <div className="px-4 py-3 space-y-3">
427
- <p className="text-xs text-slate-700 leading-snug">
428
- This is the only time you'll see the full key. If you lose it, disconnect it and create a new one.
429
- </p>
430
- <div className="relative">
431
- <textarea
432
- readOnly
433
- value={reveal.plaintext}
434
- rows={2}
435
- className="w-full font-mono text-xs bg-slate-50 border border-slate-200 rounded px-2 py-1.5 pr-10 resize-none"
436
- onFocus={(e) => e.currentTarget.select()}
437
- />
438
- <button
439
- onClick={() => copy(reveal.plaintext)}
440
- className="absolute top-1.5 right-1.5 p-1 rounded hover:bg-slate-100 text-slate-600"
441
- aria-label="Copy external API key"
442
- title="Copy to clipboard"
443
- >
444
- {copied ? <Check size={14} /> : <Copy size={14} />}
445
- </button>
446
- </div>
447
- <div>
448
- <div className="text-xs font-medium text-slate-700 mb-1">
449
- Connect Claude Code
450
- </div>
451
- <textarea
452
- readOnly
453
- value={`claude mcp add --transport http knowledge-base ${window.location.origin}/api/mcp --header "Authorization: Bearer ${reveal.plaintext}"`}
454
- rows={3}
455
- className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
456
- onFocus={(e) => e.currentTarget.select()}
457
- />
458
- </div>
459
- <div>
460
- <div className="text-xs font-medium text-slate-700 mb-1">
461
- Connect Langdock
462
- </div>
463
- <ol className="text-[11px] text-slate-600 mb-1 leading-snug list-decimal pl-4 space-y-0.5">
464
- <li>In Langdock, open your workspace settings and go to MCP servers → Add server.</li>
465
- <li>Choose <span className="font-medium">HTTP</span> (Streamable HTTP) as the transport.</li>
466
- <li>Give it a name (e.g. <span className="font-medium">Bevel</span>), paste the URL below into the server URL field, and add the Authorization header under custom headers.</li>
467
- <li>Save, then enable the server in any assistant you want it available in.</li>
468
- </ol>
469
- <textarea
470
- readOnly
471
- value={`URL: ${window.location.origin}/api/mcp\nHeader name: Authorization\nHeader value: Bearer ${reveal.plaintext}`}
472
- rows={3}
473
- className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
474
- onFocus={(e) => e.currentTarget.select()}
475
- />
476
- </div>
477
- <div>
478
- <div className="text-xs font-medium text-slate-700 mb-1">
479
- Other agents (JSON config)
480
- </div>
481
- <p className="text-[11px] text-slate-600 mb-1 leading-snug">
482
- Works with Claude Desktop, Cursor, Windsurf, Cline, and most clients that load servers from a JSON config.
483
- </p>
484
- <textarea
485
- readOnly
486
- value={JSON.stringify(
487
- {
488
- mcpServers: {
489
- 'knowledge-base': {
490
- type: 'http',
491
- url: `${window.location.origin}/api/mcp`,
492
- headers: {
493
- Authorization: `Bearer ${reveal.plaintext}`,
494
- },
495
- },
496
- },
497
- },
498
- null,
499
- 2,
500
- )}
501
- rows={11}
502
- className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
503
- onFocus={(e) => e.currentTarget.select()}
504
- />
505
- </div>
506
- </div>
507
- <div className="flex justify-end px-4 py-3 border-t border-slate-200">
508
- <button
509
- onClick={() => setReveal(null)}
510
- className="px-3 py-1.5 text-sm rounded bg-bevel hover:bg-bevel-deep text-white"
511
- >
512
- Done — I've saved it
513
- </button>
514
- </div>
515
- </div>
516
- </div>
517
- )}
518
- </>
519
- );
520
- }
521
-
522
- /** Read-only snippet with a copy button, for the no-key connection configs. */
523
- function CopyBlock({ label, value, rows }: { label: string | null; value: string; rows: number }) {
524
- const { copied, copy } = useCopyFeedback();
525
-
526
- return (
527
- <div>
528
- <div className="flex items-center justify-between mb-1">
529
- {label !== null && <div className="text-xs font-medium text-slate-700">{label}</div>}
530
- <button
531
- onClick={() => copy(value)}
532
- className="ml-auto p-1 rounded hover:bg-slate-100 text-slate-600"
533
- aria-label={label ? `Copy: ${label}` : 'Copy to clipboard'}
534
- title="Copy to clipboard"
535
- >
536
- {copied ? <Check size={14} /> : <Copy size={14} />}
537
- </button>
538
- </div>
539
- <textarea
540
- readOnly
541
- value={value}
542
- rows={rows}
543
- className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
544
- onFocus={(e) => e.currentTarget.select()}
545
- />
546
- </div>
547
- );
548
- }
1
+ import { useCallback, useEffect, useId, useState } from 'react';
2
+ import { Link } from 'react-router-dom';
3
+ import { Check, Copy, Wrench, ExternalLink } from 'lucide-react';
4
+ import { Dialog } from '../../../shared/components/Dialog';
5
+ import { PageShell } from '../../../shared/components/PageShell';
6
+ import {
7
+ type ExternalApiKeySummary,
8
+ type MintedExternalApiKey,
9
+ createExternalApiKey,
10
+ deleteExternalApiKey,
11
+ disconnectExternalApiKey,
12
+ listExternalApiKeys,
13
+ } from '../services/external-api-keys.api';
14
+
15
+ /**
16
+ * "Copied" affordance with a 1500ms auto-reset. Owns the timer + its teardown
17
+ * (so an unmounting page can't fire a stale setState), shared by the reveal
18
+ * modal and every CopyBlock. `copy(text)` writes to the clipboard and flags
19
+ * copied; a rejected write (insecure context / denied permission) leaves the
20
+ * textarea selectable for manual copy and shows no false "Copied".
21
+ */
22
+ function useCopyFeedback(): { copied: boolean; copy: (text: string) => void } {
23
+ const [copied, setCopied] = useState(false);
24
+ useEffect(() => {
25
+ if (!copied) return;
26
+ const timerId = window.setTimeout(() => setCopied(false), 1500);
27
+ return () => window.clearTimeout(timerId);
28
+ }, [copied]);
29
+ const copy = useCallback((text: string) => {
30
+ void navigator.clipboard
31
+ .writeText(text)
32
+ .then(() => setCopied(true))
33
+ .catch(() => {});
34
+ }, []);
35
+ return { copied, copy };
36
+ }
37
+
38
+ const MAX_LABEL_LEN = 200;
39
+
40
+ function formatRelative(ts: number | null): string {
41
+ if (ts === null) return 'never';
42
+ const diff = Date.now() - ts;
43
+ const minutes = Math.round(diff / 60_000);
44
+ if (minutes < 1) return 'just now';
45
+ if (minutes < 60) return `${minutes} min ago`;
46
+ const hours = Math.round(minutes / 60);
47
+ if (hours < 24) return `${hours} hr ago`;
48
+ const days = Math.round(hours / 24);
49
+ if (days < 30) return `${days} day${days === 1 ? '' : 's'} ago`;
50
+ return new Date(ts).toLocaleDateString();
51
+ }
52
+
53
+ /**
54
+ * The External agent access page, routed standalone at
55
+ * `/external-agent-access` (below the persistent toolbar), in two tabs:
56
+ *
57
+ * - "Your agent" (default) — connecting the user's own interactive agent
58
+ * (Claude Code, Claude Desktop, Cursor…). No key: the agent gets only the
59
+ * server URL, and on first connect the browser opens our authorization
60
+ * flow (sign in + choose tools on /connect). Copy-paste configs only.
61
+ * - "Autonomous agents" — the external-API-key surface for pipelines/CI
62
+ * that can't open a browser: lists existing keys, mints new ones,
63
+ * disconnects revoked ones, permanently deletes disconnected ones. The
64
+ * plaintext of a minted key is only shown once — there is no read-it-back
65
+ * endpoint.
66
+ *
67
+ * Glossary terms used in copy: "External API key", "Disconnect" (= revoke),
68
+ * "External agent" (= MCP client). See docs/glossary.md.
69
+ */
70
+ export function ExternalAgentAccessPage() {
71
+ const labelInputId = useId();
72
+
73
+ const [tab, setTab] = useState<'agent' | 'autonomous'>('agent');
74
+ const [keys, setKeys] = useState<ExternalApiKeySummary[]>([]);
75
+ const [loading, setLoading] = useState(false);
76
+ const [loadError, setLoadError] = useState<string | null>(null);
77
+
78
+ const [label, setLabel] = useState('');
79
+ const [creating, setCreating] = useState(false);
80
+ const [createError, setCreateError] = useState<string | null>(null);
81
+
82
+ // The plaintext of a freshly minted key. Held in state for the lifetime
83
+ // of the reveal modal — never persisted, and cleared when the user
84
+ // dismisses the reveal step.
85
+ const [reveal, setReveal] = useState<MintedExternalApiKey | null>(null);
86
+ const { copied, copy } = useCopyFeedback();
87
+
88
+ // The disconnected key awaiting a permanent-delete confirmation. Non-null
89
+ // drives the themed confirm Dialog below; `deleting` keeps the request in
90
+ // flight so the confirm can't be dismissed mid-delete.
91
+ const [pendingDelete, setPendingDelete] = useState<{ id: string; label: string } | null>(null);
92
+ const [deleting, setDeleting] = useState(false);
93
+
94
+ const refresh = useCallback(async () => {
95
+ setLoading(true);
96
+ setLoadError(null);
97
+ try {
98
+ setKeys(await listExternalApiKeys());
99
+ } catch (err) {
100
+ setLoadError(err instanceof Error ? err.message : "Couldn't load external API keys.");
101
+ } finally {
102
+ setLoading(false);
103
+ }
104
+ }, []);
105
+
106
+ useEffect(() => {
107
+ void refresh();
108
+ }, [refresh]);
109
+
110
+ async function handleCreate() {
111
+ const trimmed = label.trim();
112
+ if (trimmed.length === 0 || trimmed.length > MAX_LABEL_LEN || creating) return;
113
+ setCreating(true);
114
+ setCreateError(null);
115
+ try {
116
+ const minted = await createExternalApiKey(trimmed);
117
+ setReveal(minted);
118
+ setLabel('');
119
+ // Optimistic-ish: refresh the list so the new row shows up underneath
120
+ // the reveal modal.
121
+ void refresh();
122
+ } catch (err) {
123
+ setCreateError(err instanceof Error ? err.message : "Couldn't create external API key.");
124
+ } finally {
125
+ setCreating(false);
126
+ }
127
+ }
128
+
129
+ async function handleDisconnect(id: string) {
130
+ try {
131
+ await disconnectExternalApiKey(id);
132
+ await refresh();
133
+ } catch (err) {
134
+ setLoadError(err instanceof Error ? err.message : "Couldn't disconnect this key.");
135
+ }
136
+ }
137
+
138
+ async function confirmDelete() {
139
+ if (!pendingDelete || deleting) return;
140
+ setDeleting(true);
141
+ try {
142
+ await deleteExternalApiKey(pendingDelete.id);
143
+ setPendingDelete(null);
144
+ await refresh();
145
+ } catch (err) {
146
+ setLoadError(err instanceof Error ? err.message : "Couldn't delete this key.");
147
+ setPendingDelete(null);
148
+ } finally {
149
+ setDeleting(false);
150
+ }
151
+ }
152
+
153
+ const trimmed = label.trim();
154
+ const canSubmit = trimmed.length > 0 && trimmed.length <= MAX_LABEL_LEN && !creating;
155
+
156
+ // Surface the keys that matter: active keys first (most-recently-used at the
157
+ // top, never-used ones last within that group), with disconnected keys sunk
158
+ // to the bottom. Non-destructive — nothing is hidden or deleted, just ordered
159
+ // so a long list of stale/test keys doesn't bury the ones in use.
160
+ const sortedKeys = [...keys].sort((a, b) => {
161
+ const aRevoked = a.revokedAt !== null;
162
+ const bRevoked = b.revokedAt !== null;
163
+ if (aRevoked !== bRevoked) return aRevoked ? 1 : -1;
164
+ return (b.lastUsedAt ?? 0) - (a.lastUsedAt ?? 0);
165
+ });
166
+
167
+ return (
168
+ <>
169
+ <PageShell title="External agent access" padded={false}>
170
+ <div className="flex border-b border-slate-200 px-4 shrink-0" role="tablist">
171
+ {(
172
+ [
173
+ ['agent', 'Your agent'],
174
+ ['autonomous', 'Autonomous agents'],
175
+ ] as const
176
+ ).map(([id, name]) => (
177
+ <button
178
+ key={id}
179
+ role="tab"
180
+ aria-selected={tab === id}
181
+ onClick={() => setTab(id)}
182
+ className={`px-3 py-2 text-xs font-medium border-b-2 -mb-px ${
183
+ tab === id
184
+ ? 'border-bevel text-slate-900'
185
+ : 'border-transparent text-slate-500 hover:text-slate-800'
186
+ }`}
187
+ >
188
+ {name}
189
+ </button>
190
+ ))}
191
+ </div>
192
+
193
+ {tab === 'agent' && (
194
+ <div className="px-4 py-3 space-y-4">
195
+ <p className="text-xs text-slate-600 leading-snug">
196
+ Connect your own agent — Claude Code, Claude Desktop, Cursor and similar. No key
197
+ needed: the first time the agent connects, your browser opens so you can sign in and
198
+ choose which tools to share with it. Everything it saves appears under your name.
199
+ </p>
200
+ <Link
201
+ to="/connect"
202
+ target="_blank"
203
+ rel="noopener noreferrer"
204
+ className="flex items-center justify-center gap-1.5 rounded border border-slate-200 px-2 py-1.5 text-xs text-slate-700 hover:bg-slate-100"
205
+ >
206
+ <Wrench size={12} />
207
+ Configure your tools
208
+ <ExternalLink size={11} className="opacity-60" />
209
+ </Link>
210
+ <CopyBlock
211
+ label="Connect Claude Code"
212
+ value={`claude mcp add --transport http knowledge-base ${window.location.origin}/api/mcp`}
213
+ rows={2}
214
+ />
215
+ <div>
216
+ <div className="text-xs font-medium text-slate-700 mb-1">claude.ai / Claude Desktop</div>
217
+ <p className="text-[11px] text-slate-600 mb-1 leading-snug">
218
+ Settings → Connectors → Add custom connector, then paste this URL. When asked to
219
+ authorize, your browser opens this app to finish connecting.
220
+ </p>
221
+ <CopyBlock label={null} value={`${window.location.origin}/api/mcp`} rows={1} />
222
+ </div>
223
+ <div>
224
+ <div className="text-xs font-medium text-slate-700 mb-1">Other agents (JSON config)</div>
225
+ <p className="text-[11px] text-slate-600 mb-1 leading-snug">
226
+ Works with Cursor, Windsurf, Cline, and most clients that load servers from a JSON
227
+ config and support signing in.
228
+ </p>
229
+ <CopyBlock
230
+ label={null}
231
+ value={JSON.stringify(
232
+ {
233
+ mcpServers: {
234
+ 'knowledge-base': {
235
+ type: 'http',
236
+ url: `${window.location.origin}/api/mcp`,
237
+ },
238
+ },
239
+ },
240
+ null,
241
+ 2,
242
+ )}
243
+ rows={9}
244
+ />
245
+ </div>
246
+ <p className="text-[11px] text-slate-500 leading-snug">
247
+ Running an unattended pipeline or CI agent that can't open a browser? Use the{' '}
248
+ <button
249
+ type="button"
250
+ onClick={() => setTab('autonomous')}
251
+ className="underline text-slate-600 hover:text-slate-900"
252
+ >
253
+ Autonomous agents
254
+ </button>{' '}
255
+ tab instead.
256
+ </p>
257
+ </div>
258
+ )}
259
+
260
+ {tab === 'autonomous' && (
261
+ <div className="px-4 py-3 space-y-4">
262
+ <p className="text-xs text-slate-600 leading-snug">
263
+ For autonomous agents and pipelines (CI, scheduled jobs) that can't open a browser to
264
+ sign in. Create an external API key and give it to the agent. Each key carries your
265
+ identity, so any saves the agent makes appear under your name — and it only gets the
266
+ tools you've already connected on the Connect your tools page.
267
+ </p>
268
+
269
+ <div className="border border-slate-200 rounded p-3 space-y-2">
270
+ <label htmlFor={labelInputId} className="block text-xs font-medium text-slate-700">
271
+ Create an external API key
272
+ </label>
273
+ <div className="flex gap-2">
274
+ <input
275
+ id={labelInputId}
276
+ value={label}
277
+ onChange={(e) => setLabel(e.target.value)}
278
+ placeholder="e.g. Claude Code on my laptop"
279
+ maxLength={MAX_LABEL_LEN}
280
+ className="flex-1 bg-white border border-slate-200 rounded px-2 py-1.5 text-sm focus:outline-none focus:border-slate-300"
281
+ onKeyDown={(e) => {
282
+ if (e.key === 'Enter' && canSubmit) handleCreate();
283
+ }}
284
+ />
285
+ <button
286
+ onClick={handleCreate}
287
+ disabled={!canSubmit}
288
+ className="px-3 py-1.5 text-sm rounded bg-bevel hover:bg-bevel-deep text-white disabled:opacity-50 disabled:hover:bg-bevel"
289
+ >
290
+ {creating ? 'Creating…' : 'Create key'}
291
+ </button>
292
+ </div>
293
+ {createError && (
294
+ <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
295
+ {createError}
296
+ </div>
297
+ )}
298
+ </div>
299
+
300
+ <div className="space-y-2">
301
+ <div className="text-xs font-medium text-slate-700">Your external API keys</div>
302
+ {loadError && (
303
+ <div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1.5">
304
+ {loadError}
305
+ </div>
306
+ )}
307
+ {loading ? (
308
+ <div className="text-xs text-slate-600">Loading…</div>
309
+ ) : keys.length === 0 ? (
310
+ <div className="text-xs text-slate-600">No external API keys yet.</div>
311
+ ) : (
312
+ <ul className="divide-y divide-slate-200 border border-slate-200 rounded">
313
+ {sortedKeys.map((k) => {
314
+ const revoked = k.revokedAt !== null;
315
+ const usage = !revoked ? k.llmUsage : undefined;
316
+ const cap = usage?.dailyTokenCap ?? 0;
317
+ const used = usage?.usedTodayTokens ?? 0;
318
+ const pct = cap > 0 ? Math.min(100, Math.round((used / cap) * 100)) : 0;
319
+ const overCap = cap > 0 && used >= cap;
320
+ return (
321
+ <li
322
+ key={k.id}
323
+ className={`flex items-center gap-3 px-3 py-2 text-sm ${
324
+ revoked ? 'opacity-60' : ''
325
+ }`}
326
+ >
327
+ <div className="flex-1 min-w-0">
328
+ <div className="font-medium truncate">{k.label}</div>
329
+ <div className="text-[11px] text-slate-600">
330
+ Created {formatRelative(k.createdAt)} · Last used {formatRelative(k.lastUsedAt)}
331
+ {revoked && ' · Disconnected'}
332
+ </div>
333
+ {usage && (
334
+ <div className="mt-1 max-w-xs">
335
+ <div
336
+ className={`flex items-center justify-between text-[11px] ${
337
+ overCap ? 'text-red-600' : 'text-slate-600'
338
+ }`}
339
+ >
340
+ <span>Model usage today</span>
341
+ <span>
342
+ {used.toLocaleString()} / {cap.toLocaleString()} tokens
343
+ </span>
344
+ </div>
345
+ <div className="mt-0.5 h-1 rounded bg-slate-100 overflow-hidden">
346
+ <div
347
+ className={`h-full ${overCap ? 'bg-red-500' : 'bg-bevel'}`}
348
+ style={{ width: `${pct}%` }}
349
+ />
350
+ </div>
351
+ </div>
352
+ )}
353
+ </div>
354
+ {revoked ? (
355
+ <button
356
+ onClick={() => setPendingDelete({ id: k.id, label: k.label })}
357
+ className="text-xs px-2 py-1 rounded text-red-600 hover:bg-red-50 border border-slate-200"
358
+ title="Permanently delete this disconnected key and its usage history."
359
+ >
360
+ Delete
361
+ </button>
362
+ ) : (
363
+ <button
364
+ onClick={() => handleDisconnect(k.id)}
365
+ className="text-xs px-2 py-1 rounded text-slate-700 hover:bg-slate-100 border border-slate-200"
366
+ title="Disconnect this external API key. The external agent using it will lose access."
367
+ >
368
+ Disconnect
369
+ </button>
370
+ )}
371
+ </li>
372
+ );
373
+ })}
374
+ </ul>
375
+ )}
376
+ </div>
377
+ </div>
378
+ )}
379
+ </PageShell>
380
+
381
+ <Dialog
382
+ open={pendingDelete !== null}
383
+ onClose={() => setPendingDelete(null)}
384
+ title="Delete external API key"
385
+ size="sm"
386
+ busy={deleting}
387
+ footer={
388
+ <>
389
+ <button
390
+ onClick={() => setPendingDelete(null)}
391
+ disabled={deleting}
392
+ className="px-3 py-1.5 text-sm rounded text-slate-700 hover:bg-slate-100 border border-slate-200 disabled:opacity-50"
393
+ >
394
+ Cancel
395
+ </button>
396
+ <button
397
+ onClick={confirmDelete}
398
+ disabled={deleting}
399
+ className="px-3 py-1.5 text-sm rounded bg-red-600 hover:bg-red-700 text-white disabled:opacity-50 disabled:hover:bg-red-600"
400
+ >
401
+ {deleting ? 'Deleting…' : 'Delete'}
402
+ </button>
403
+ </>
404
+ }
405
+ >
406
+ <p className="text-xs text-slate-700 leading-snug">
407
+ Permanently delete{' '}
408
+ <span className="font-medium">&ldquo;{pendingDelete?.label}&rdquo;</span>? This removes it
409
+ and its usage history for good.
410
+ </p>
411
+ </Dialog>
412
+
413
+ {reveal && (
414
+ <div
415
+ className="fixed inset-0 z-[60] bg-slate-900/40 flex items-center justify-center p-4"
416
+ onClick={(e) => e.stopPropagation()}
417
+ >
418
+ <div
419
+ role="alertdialog"
420
+ aria-modal="true"
421
+ className="bg-white border border-slate-200 rounded-lg shadow-xl w-full max-w-xl max-h-[90vh] overflow-y-auto"
422
+ >
423
+ <div className="px-4 py-3 border-b border-slate-200">
424
+ <h3 className="text-sm font-semibold">Save this external API key now</h3>
425
+ </div>
426
+ <div className="px-4 py-3 space-y-3">
427
+ <p className="text-xs text-slate-700 leading-snug">
428
+ This is the only time you'll see the full key. If you lose it, disconnect it and create a new one.
429
+ </p>
430
+ <div className="relative">
431
+ <textarea
432
+ readOnly
433
+ value={reveal.plaintext}
434
+ rows={2}
435
+ className="w-full font-mono text-xs bg-slate-50 border border-slate-200 rounded px-2 py-1.5 pr-10 resize-none"
436
+ onFocus={(e) => e.currentTarget.select()}
437
+ />
438
+ <button
439
+ onClick={() => copy(reveal.plaintext)}
440
+ className="absolute top-1.5 right-1.5 p-1 rounded hover:bg-slate-100 text-slate-600"
441
+ aria-label="Copy external API key"
442
+ title="Copy to clipboard"
443
+ >
444
+ {copied ? <Check size={14} /> : <Copy size={14} />}
445
+ </button>
446
+ </div>
447
+ <div>
448
+ <div className="text-xs font-medium text-slate-700 mb-1">
449
+ Connect Claude Code
450
+ </div>
451
+ <textarea
452
+ readOnly
453
+ value={`claude mcp add --transport http knowledge-base ${window.location.origin}/api/mcp --header "Authorization: Bearer ${reveal.plaintext}"`}
454
+ rows={3}
455
+ className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
456
+ onFocus={(e) => e.currentTarget.select()}
457
+ />
458
+ </div>
459
+ <div>
460
+ <div className="text-xs font-medium text-slate-700 mb-1">
461
+ Connect Langdock
462
+ </div>
463
+ <ol className="text-[11px] text-slate-600 mb-1 leading-snug list-decimal pl-4 space-y-0.5">
464
+ <li>In Langdock, open your workspace settings and go to MCP servers → Add server.</li>
465
+ <li>Choose <span className="font-medium">HTTP</span> (Streamable HTTP) as the transport.</li>
466
+ <li>Give it a name (e.g. <span className="font-medium">Bevel</span>), paste the URL below into the server URL field, and add the Authorization header under custom headers.</li>
467
+ <li>Save, then enable the server in any assistant you want it available in.</li>
468
+ </ol>
469
+ <textarea
470
+ readOnly
471
+ value={`URL: ${window.location.origin}/api/mcp\nHeader name: Authorization\nHeader value: Bearer ${reveal.plaintext}`}
472
+ rows={3}
473
+ className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
474
+ onFocus={(e) => e.currentTarget.select()}
475
+ />
476
+ </div>
477
+ <div>
478
+ <div className="text-xs font-medium text-slate-700 mb-1">
479
+ Other agents (JSON config)
480
+ </div>
481
+ <p className="text-[11px] text-slate-600 mb-1 leading-snug">
482
+ Works with Claude Desktop, Cursor, Windsurf, Cline, and most clients that load servers from a JSON config.
483
+ </p>
484
+ <textarea
485
+ readOnly
486
+ value={JSON.stringify(
487
+ {
488
+ mcpServers: {
489
+ 'knowledge-base': {
490
+ type: 'http',
491
+ url: `${window.location.origin}/api/mcp`,
492
+ headers: {
493
+ Authorization: `Bearer ${reveal.plaintext}`,
494
+ },
495
+ },
496
+ },
497
+ },
498
+ null,
499
+ 2,
500
+ )}
501
+ rows={11}
502
+ className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
503
+ onFocus={(e) => e.currentTarget.select()}
504
+ />
505
+ </div>
506
+ </div>
507
+ <div className="flex justify-end px-4 py-3 border-t border-slate-200">
508
+ <button
509
+ onClick={() => setReveal(null)}
510
+ className="px-3 py-1.5 text-sm rounded bg-bevel hover:bg-bevel-deep text-white"
511
+ >
512
+ Done — I've saved it
513
+ </button>
514
+ </div>
515
+ </div>
516
+ </div>
517
+ )}
518
+ </>
519
+ );
520
+ }
521
+
522
+ /** Read-only snippet with a copy button, for the no-key connection configs. */
523
+ function CopyBlock({ label, value, rows }: { label: string | null; value: string; rows: number }) {
524
+ const { copied, copy } = useCopyFeedback();
525
+
526
+ return (
527
+ <div>
528
+ <div className="flex items-center justify-between mb-1">
529
+ {label !== null && <div className="text-xs font-medium text-slate-700">{label}</div>}
530
+ <button
531
+ onClick={() => copy(value)}
532
+ className="ml-auto p-1 rounded hover:bg-slate-100 text-slate-600"
533
+ aria-label={label ? `Copy: ${label}` : 'Copy to clipboard'}
534
+ title="Copy to clipboard"
535
+ >
536
+ {copied ? <Check size={14} /> : <Copy size={14} />}
537
+ </button>
538
+ </div>
539
+ <textarea
540
+ readOnly
541
+ value={value}
542
+ rows={rows}
543
+ className="w-full font-mono text-[11px] bg-slate-50 border border-slate-200 rounded px-2 py-1.5 resize-none"
544
+ onFocus={(e) => e.currentTarget.select()}
545
+ />
546
+ </div>
547
+ );
548
+ }