The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit f1f8fc237d6aCommit detailsView latest

apps/dashboard/src/main.tsx 1412 lines · 46.3 KB · tsx
1
import React, { useCallback, useEffect, useMemo, useState } from 'react';
2
import { createRoot } from 'react-dom/client';
3
import './styles.css';
4
5
declare const __AUTH0_DOMAIN__: string;
6
declare const __AUTH0_CLIENT_ID__: string;
7
declare const __AUTH0_AUDIENCE__: string;
8
9
type Auth0User = { sub: string; name?: string; email?: string; picture?: string };
10
type AuthSession = { user: Auth0User };
11
type AuthTransaction = { state: string; nonce: string; verifier: string };
12
type Theme = 'dark' | 'light';
13
14
const authTransactionKey = 'openclasp.auth0.transaction';
15
const themeKey = 'openclasp.theme.v1';
16
17
type DashboardData = {
18
  agents: Record<string, any>[];
19
  projects: Record<string, any>[];
20
  installations: Record<string, any>[];
21
  setupRequests: Record<string, any>[];
22
  publications: Record<string, any>[];
23
  interactions: Record<string, any>[];
24
  federatedInteractions: Record<string, any>[];
25
  liveSessions: Record<string, any>[];
26
  events: Record<string, any>[];
27
  conflicts: Record<string, any>[];
28
  receipts: Record<string, any>[];
29
  profiles: Record<string, any>[];
30
  runtimes: Record<string, any>[];
31
};
32
33
type Settings = {
34
  displayName: string;
35
  contributionEnabled: boolean;
36
  retentionDays: number;
37
  evidenceSharing: 'never' | 'ask' | 'contract_only';
38
  rawConversationsStored: false;
39
};
40
41
const emptyData: DashboardData = {
42
  agents: [],
43
  projects: [],
44
  installations: [],
45
  setupRequests: [],
46
  publications: [],
47
  interactions: [],
48
  federatedInteractions: [],
49
  liveSessions: [],
50
  events: [],
51
  conflicts: [],
52
  receipts: [],
53
  profiles: [],
54
  runtimes: [],
55
};
56
const defaultSettings: Settings = {
57
  displayName: '',
58
  contributionEnabled: false,
59
  retentionDays: 30,
60
  evidenceSharing: 'ask',
61
  rawConversationsStored: false,
62
};
63
const pages = ['dashboard', 'history', 'agents', 'insights', 'connect', 'settings'] as const;
64
type Page = (typeof pages)[number];
65
66
function base64Url(bytes: Uint8Array) {
67
  let binary = '';
68
  for (const byte of bytes) binary += String.fromCharCode(byte);
69
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
70
}
71
72
function randomValue(size = 32) {
73
  return base64Url(crypto.getRandomValues(new Uint8Array(size)));
74
}
75
76
async function beginAuth(provider: 'google' | 'github') {
77
  const verifier = randomValue(48);
78
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
79
  const transaction: AuthTransaction = { state: randomValue(), nonce: randomValue(), verifier };
80
  sessionStorage.setItem(authTransactionKey, JSON.stringify(transaction));
81
  const parameters = new URLSearchParams({
82
    client_id: __AUTH0_CLIENT_ID__,
83
    redirect_uri: `${location.origin}/sso-callback`,
84
    response_type: 'code',
85
    scope: 'openid profile email',
86
    audience: __AUTH0_AUDIENCE__,
87
    state: transaction.state,
88
    nonce: transaction.nonce,
89
    code_challenge: base64Url(new Uint8Array(digest)),
90
    code_challenge_method: 'S256',
91
    connection: provider === 'google' ? 'google-oauth2' : 'github',
92
  });
93
  location.assign(`https://${__AUTH0_DOMAIN__}/authorize?${parameters}`);
94
}
95
96
async function signOut() {
97
  await fetch('/api/session', { method: 'DELETE', credentials: 'same-origin' });
98
  const parameters = new URLSearchParams({
99
    client_id: __AUTH0_CLIENT_ID__,
100
    returnTo: `${location.origin}/login`,
101
  });
102
  location.assign(`https://${__AUTH0_DOMAIN__}/v2/logout?${parameters}`);
103
}
104
105
async function api(path: string, init?: RequestInit) {
106
  const headers = new Headers(init?.headers);
107
  if (init?.body && !headers.has('content-type')) headers.set('content-type', 'application/json');
108
  return fetch(path, {
109
    ...init,
110
    credentials: 'same-origin',
111
    headers,
112
  }).then(async (response) => {
113
    if (!response.ok)
114
      throw new Error((await response.text()) || `Request failed: ${response.status}`);
115
    return response.json();
116
  });
117
}
118
119
function route(): Page {
120
  const value = location.pathname.slice(1) || 'dashboard';
121
  return pages.includes(value as Page) ? (value as Page) : 'dashboard';
122
}
123
124
function initialTheme(): Theme {
125
  const saved = localStorage.getItem(themeKey);
126
  if (saved === 'dark' || saved === 'light') return saved;
127
  return matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
128
}
129
130
function App() {
131
  const [session, setSession] = useState<AuthSession | null>();
132
  const [theme, setTheme] = useState<Theme>(initialTheme);
133
  const [page, setPage] = useState<Page>(route());
134
  const [data, setData] = useState<DashboardData>(emptyData);
135
  const [settings, setSettings] = useState<Settings>(defaultSettings);
136
  const [loading, setLoading] = useState(true);
137
  const [error, setError] = useState('');
138
  const refreshDashboard = useCallback(async () => {
139
    setData((await api('/v0.1/dashboard')) as DashboardData);
140
  }, []);
141
142
  useEffect(() => {
143
    fetch('/api/session', { credentials: 'same-origin' })
144
      .then(async (response) => {
145
        if (!response.ok) return null;
146
        return (await response.json()) as AuthSession;
147
      })
148
      .then(setSession)
149
      .catch(() => setSession(null));
150
  }, []);
151
152
  useEffect(() => {
153
    document.documentElement.dataset.theme = theme;
154
    localStorage.setItem(themeKey, theme);
155
  }, [theme]);
156
157
  useEffect(() => {
158
    const onPopState = () => setPage(route());
159
    addEventListener('popstate', onPopState);
160
    return () => removeEventListener('popstate', onPopState);
161
  }, []);
162
163
  useEffect(() => {
164
    if (session === undefined) return;
165
    if (!session && location.pathname !== '/login') history.replaceState({}, '', '/login');
166
    if (!session) return;
167
    if (location.pathname === '/login') history.replaceState({}, '', '/dashboard');
168
    setPage(route());
169
    Promise.all([api('/v0.1/dashboard'), api('/v0.1/settings')])
170
      .then(([dashboard, accountSettings]) => {
171
        setData(dashboard as DashboardData);
172
        setSettings(accountSettings as Settings);
173
      })
174
      .catch((reason: unknown) =>
175
        setError(reason instanceof Error ? reason.message : 'Load failed'),
176
      )
177
      .finally(() => setLoading(false));
178
  }, [session]);
179
180
  useEffect(() => {
181
    if (!session) return;
182
    const refresh = () => {
183
      if (document.visibilityState === 'visible') void refreshDashboard().catch(() => undefined);
184
    };
185
    const timer = window.setInterval(refresh, 10_000);
186
    document.addEventListener('visibilitychange', refresh);
187
    return () => {
188
      window.clearInterval(timer);
189
      document.removeEventListener('visibilitychange', refresh);
190
    };
191
  }, [session, refreshDashboard]);
192
193
  const navigate = (next: Page) => {
194
    history.pushState({}, '', `/${next}`);
195
    setPage(next);
196
  };
197
198
  if (session === undefined) return <Loading />;
199
  if (!session) return <Login />;
200
201
  return (
202
    <div className="appShell">
203
      <aside>
204
        <div className="brand">
205
          <div className="mark">OC</div>
206
          <div>
207
            <strong>OpenClasp</strong>
208
            <small>ASSURANCE NETWORK</small>
209
          </div>
210
        </div>
211
        <nav>
212
          <Nav page="dashboard" active={page} onClick={navigate} label="Overview" glyph="⌂" />
213
          <Nav page="history" active={page} onClick={navigate} label="History" glyph="≡" />
214
          <Nav page="agents" active={page} onClick={navigate} label="Agents" glyph="◇" />
215
          <Nav page="insights" active={page} onClick={navigate} label="Insights" glyph="⌁" />
216
          <Nav page="connect" active={page} onClick={navigate} label="Connect" glyph="+" />
217
          <Nav page="settings" active={page} onClick={navigate} label="Settings" glyph="⚙" />
218
        </nav>
219
        <button
220
          className="themeSwitch"
221
          onClick={() => setTheme((current) => (current === 'dark' ? 'light' : 'dark'))}
222
          aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
223
        >
224
          <span>{theme === 'dark' ? '☼' : '◐'}</span>
225
          {theme === 'dark' ? 'Light theme' : 'Dark theme'}
226
        </button>
227
        <div className="privacyStamp">
228
          <span className="liveDot" />
229
          <div>
230
            <strong>Privacy separated</strong>
231
            <small>Raw messages never stored</small>
232
          </div>
233
        </div>
234
        <button className="account" onClick={() => void signOut()}>
235
          <span>{initials(session.user.name || session.user.email || 'OC')}</span>
236
          <div>
237
            <strong>{session.user.name || 'OpenClasp user'}</strong>
238
            <small>{session.user.email || 'Sign out'}</small>
239
          </div>
240
          <b>↗</b>
241
        </button>
242
      </aside>
243
      <main>
244
        {error && <div className="errorBar">{error}</div>}
245
        {loading ? (
246
          <Loading compact />
247
        ) : (
248
          <PageContent
249
            page={page}
250
            data={data}
251
            settings={settings}
252
            setSettings={setSettings}
253
            navigate={navigate}
254
            refreshDashboard={refreshDashboard}
255
          />
256
        )}
257
      </main>
258
    </div>
259
  );
260
}
261
262
function Login() {
263
  const [error, setError] = useState('');
264
  const continueWith = async (provider: 'google' | 'github') => {
265
    setError('');
266
    try {
267
      await beginAuth(provider);
268
    } catch {
269
      setError(`${provider === 'google' ? 'Google' : 'GitHub'} sign-in is not configured yet.`);
270
    }
271
  };
272
  return (
273
    <div className="loginPage">
274
      <section className="loginPitch">
275
        <div className="brand">
276
          <div className="mark">OC</div>
277
          <strong>OpenClasp</strong>
278
        </div>
279
        <div>
280
          <p className="eyebrow">AGENT-TO-AGENT ASSURANCE</p>
281
          <h1>Know who your agent is dealing with.</h1>
282
          <p>
283
            Verified identities, signed outcomes, private warnings, and contextual
284
            reliability—without using message bodies for scoring.
285
          </p>
286
        </div>
287
        <div className="loginProof">
288
          <span>01</span> User-owned history<span>02</span> No universal trust score<span>03</span>{' '}
289
          Explicit network consent
290
        </div>
291
      </section>
292
      <section className="loginCard">
293
        <div>
294
          <p className="eyebrow">SECURE ACCESS</p>
295
          <h2>Sign in to OpenClasp</h2>
296
          <p>
297
            Manage connected agents, review signed history, and control what contributes to the
298
            network.
299
          </p>
300
        </div>
301
        <div className="socialButtons">
302
          <button onClick={() => void continueWith('google')}>
303
            <span className="google">G</span> Continue with Google
304
          </button>
305
          <button onClick={() => void continueWith('github')}>
306
            <span>◉</span> Continue with GitHub
307
          </button>
308
        </div>
309
        {error && <div className="loginError">{error}</div>}
310
        <small>
311
          Google and GitHub handle authentication. OpenClasp never receives your password.
312
        </small>
313
      </section>
314
    </div>
315
  );
316
}
317
318
let callbackStarted = false;
319
function AuthCallback() {
320
  const [error, setError] = useState('');
321
  useEffect(() => {
322
    if (callbackStarted) return;
323
    callbackStarted = true;
324
    const finish = async () => {
325
      const query = new URLSearchParams(location.search);
326
      const oauthError = query.get('error_description') ?? query.get('error');
327
      if (oauthError) throw new Error(oauthError);
328
      const code = query.get('code');
329
      const returnedState = query.get('state');
330
      const rawTransaction = sessionStorage.getItem(authTransactionKey);
331
      if (!code || !returnedState || !rawTransaction) throw new Error('Missing OAuth transaction');
332
      const transaction = JSON.parse(rawTransaction) as AuthTransaction;
333
      sessionStorage.removeItem(authTransactionKey);
334
      if (returnedState !== transaction.state) throw new Error('OAuth state mismatch');
335
      const response = await fetch('/api/session', {
336
        method: 'POST',
337
        credentials: 'same-origin',
338
        headers: { 'content-type': 'application/json' },
339
        body: JSON.stringify({
340
          code,
341
          codeVerifier: transaction.verifier,
342
        }),
343
      });
344
      if (!response.ok) throw new Error('Auth0 token exchange failed');
345
      location.replace('/dashboard');
346
    };
347
    void finish().catch((reason: unknown) =>
348
      setError(reason instanceof Error ? reason.message : 'Authentication failed'),
349
    );
350
  }, []);
351
  if (error)
352
    return (
353
      <div className="loading">
354
        <span className="mark">OC</span>
355
        <p>{error}</p>
356
        <a href="/login">Return to login</a>
357
      </div>
358
    );
359
  return <Loading />;
360
}
361
362
function PageContent({
363
  page,
364
  data,
365
  settings,
366
  setSettings,
367
  navigate,
368
  refreshDashboard,
369
}: {
370
  page: Page;
371
  data: DashboardData;
372
  settings: Settings;
373
  setSettings: React.Dispatch<React.SetStateAction<Settings>>;
374
  navigate: (page: Page) => void;
375
  refreshDashboard: () => Promise<void>;
376
}) {
377
  if (page === 'history') return <History data={data} />;
378
  if (page === 'agents')
379
    return <Agents data={data} navigate={navigate} refreshDashboard={refreshDashboard} />;
380
  if (page === 'insights') return <Insights data={data} />;
381
  if (page === 'connect') return <Connect data={data} refreshDashboard={refreshDashboard} />;
382
  if (page === 'settings') return <SettingsPage settings={settings} setSettings={setSettings} />;
383
  return <Overview data={data} navigate={navigate} refreshDashboard={refreshDashboard} />;
384
}
385
386
function Overview({
387
  data,
388
  navigate,
389
  refreshDashboard,
390
}: {
391
  data: DashboardData;
392
  navigate: (page: Page) => void;
393
  refreshDashboard: () => Promise<void>;
394
}) {
395
  const completed = data.receipts.filter((item) => item.outcome === 'success').length;
396
  const warnings = data.events.filter((item) =>
397
    ['policy_warning', 'policy_violation', 'objection'].includes(String(item.eventType)),
398
  ).length;
399
  const publishedIds = new Set(
400
    data.publications
401
      .filter((publication) => publication.published)
402
      .map((publication) => String(publication.agentId)),
403
  );
404
  const readyAgents = data.agents.filter((agent) => publishedIds.has(String(agent.agentId))).length;
405
  const onlineAgents = data.agents.filter((agent) => agent.presence?.status === 'online').length;
406
  const pendingInvitations = data.federatedInteractions.filter(
407
    (interaction) => interaction.status === 'pending',
408
  ).length;
409
  return (
410
    <>
411
      <PageHead
412
        eyebrow="NETWORK OVERVIEW"
413
        title="Assurance, at a glance."
414
        action="Connect agent"
415
        onAction={() => navigate('connect')}
416
      />
417
      <section
418
        className={`readiness ${readyAgents === data.agents.length && readyAgents ? 'ready' : ''}`}
419
      >
420
        <div>
421
          <span className="statusOrb">{readyAgents ? '✓' : '!'}</span>
422
          <div>
423
            <strong>
424
              {readyAgents === data.agents.length && readyAgents
425
                ? 'Your agent network is ready'
426
                : `${readyAgents} of ${data.agents.length} agents can receive A2A work`}
427
            </strong>
428
            <small>
429
              Safe matching requests activate automatically. Everything else waits for approval.
430
            </small>
431
          </div>
432
        </div>
433
        <button className="secondary" onClick={() => navigate('agents')}>
434
          Manage automation
435
        </button>
436
      </section>
437
      <section className="metrics">
438
        <Metric
439
          label="Online agents"
440
          value={onlineAgents}
441
          note={`${data.agents.length - onlineAgents} offline · 2 min window`}
442
        />
443
        <Metric
444
          label="Interactions"
445
          value={data.interactions.length + data.federatedInteractions.length}
446
          note="local and shared"
447
        />
448
        <Metric label="Successful outcomes" value={completed} note="receipt-backed" />
449
        <Metric
450
          label="Needs review"
451
          value={warnings + pendingInvitations}
452
          note="warnings or approvals"
453
          warn={warnings + pendingInvitations > 0}
454
        />
455
      </section>
456
      <Invitations data={data} refreshDashboard={refreshDashboard} />
457
      <section className="contentGrid">
458
        <Panel title="Recent activity" subtitle="Structured events and signed outcomes">
459
          <Timeline events={data.events.slice(-6).reverse()} />
460
          <TextButton onClick={() => navigate('history')}>View complete history →</TextButton>
461
        </Panel>
462
        <Panel
463
          title="Reliability context"
464
          subtitle="Task-specific profiles, never a universal score"
465
        >
466
          {data.profiles.length ? (
467
            data.profiles
468
              .slice(0, 4)
469
              .map((profile) => (
470
                <Profile key={`${profile.agentId}-${profile.taskCategory}`} profile={profile} />
471
              ))
472
          ) : (
473
            <Empty
474
              title="No reliability profile yet"
475
              text="Profiles appear after signed receipts and eligible bilateral feedback."
476
            />
477
          )}
478
        </Panel>
479
      </section>
480
    </>
481
  );
482
}
483
484
function History({ data }: { data: DashboardData }) {
485
  const records = useMemo(
486
    () =>
487
      [
488
        ...data.interactions.map((value) => ({ ...value, _kind: 'interaction' })),
489
        ...data.federatedInteractions.map((value) => ({
490
          ...value,
491
          _kind: 'federated interaction',
492
        })),
493
        ...data.events.map((value) => ({ ...value, _kind: 'event' })),
494
        ...data.receipts.map((value) => ({ ...value, _kind: 'receipt' })),
495
        ...data.conflicts.map((value) => ({ ...value, _kind: 'dispute' })),
496
      ].sort((a, b) => Date.parse(timestamp(b)) - Date.parse(timestamp(a))),
497
    [data],
498
  );
499
  return (
500
    <>
501
      <PageHead eyebrow="AUDIT HISTORY" title="What happened, and what proves it." />
502
      <Panel
503
        title="Account history"
504
        subtitle="Only structured metadata, signatures, hashes, and permitted evidence are hosted"
505
      >
506
        {records.length ? (
507
          records.map((item, index) => (
508
            <HistoryRow
509
              key={String(
510
                (item as Record<string, any>).eventId ??
511
                  (item as Record<string, any>).receiptId ??
512
                  (item as Record<string, any>).interactionId ??
513
                  index,
514
              )}
515
              item={item}
516
            />
517
          ))
518
        ) : (
519
          <Empty
520
            title="No interactions recorded"
521
            text="Connect an agent and start an assured interaction. Raw message bodies will not appear here."
522
          />
523
        )}
524
      </Panel>
525
    </>
526
  );
527
}
528
529
function Agents({
530
  data,
531
  navigate,
532
  refreshDashboard,
533
}: {
534
  data: DashboardData;
535
  navigate: (page: Page) => void;
536
  refreshDashboard: () => Promise<void>;
537
}) {
538
  const [working, setWorking] = useState('');
539
  const [error, setError] = useState('');
540
  const saveAutomation = async (
541
    agentId: string,
542
    value: {
543
      autoPublish: boolean;
544
      autoAcceptPolicy: 'off' | 'safe_matching';
545
      autoAcceptTaskCategories: string[];
546
    },
547
  ) => {
548
    setWorking(agentId);
549
    setError('');
550
    try {
551
      await api(`/v0.1/agents/${encodeURIComponent(agentId)}/automation`, {
552
        method: 'PUT',
553
        body: JSON.stringify(value),
554
      });
555
      await refreshDashboard();
556
    } catch (reason) {
557
      setError(reason instanceof Error ? reason.message : 'Directory update failed');
558
    } finally {
559
      setWorking('');
560
    }
561
  };
562
  const saveRuntime = async (agentId: string, endpoint: string) => {
563
    setWorking(`runtime:${agentId}`);
564
    setError('');
565
    try {
566
      await api(`/v0.1/agents/${encodeURIComponent(agentId)}/runtime`, {
567
        method: 'PUT',
568
        body: JSON.stringify({ endpoint }),
569
      });
570
      await refreshDashboard();
571
    } catch (reason) {
572
      setError(reason instanceof Error ? reason.message : 'Runtime verification failed');
573
    } finally {
574
      setWorking('');
575
    }
576
  };
577
  const disableRuntime = async (agentId: string) => {
578
    setWorking(`runtime:${agentId}`);
579
    setError('');
580
    try {
581
      await api(`/v0.1/agents/${encodeURIComponent(agentId)}/runtime`, { method: 'DELETE' });
582
      await refreshDashboard();
583
    } catch (reason) {
584
      setError(reason instanceof Error ? reason.message : 'Runtime update failed');
585
    } finally {
586
      setWorking('');
587
    }
588
  };
589
  return (
590
    <>
591
      <PageHead
592
        eyebrow="IDENTITY REGISTRY"
593
        title="Your connected agents."
594
        action="Connect agent"
595
        onAction={() => navigate('connect')}
596
      />
597
      <div className="notice">
598
        <strong>Direct live sessions.</strong> OpenClasp verifies both runtimes, brokers scoped
599
        credentials, then gets out of the message path. Safe matching tasks can be accepted
600
        automatically; sensitive or mismatched requests still require review.
601
      </div>
602
      {error && <div className="errorBar">{error}</div>}
603
      <section className="agentGrid">
604
        {data.agents.length ? (
605
          data.agents.map((agent) => (
606
            <AgentCard
607
              key={agent.agentId}
608
              agent={agent}
609
              projectName={
610
                data.projects.find((project) => project.projectId === agent.projectId)?.name
611
              }
612
              published={data.publications.some(
613
                (publication) => publication.agentId === agent.agentId && publication.published,
614
              )}
615
              working={working === agent.agentId}
616
              onSave={(value) => saveAutomation(agent.agentId, value)}
617
              runtime={data.runtimes.find((runtime) => runtime.agentId === agent.agentId)}
618
              runtimeWorking={working === `runtime:${agent.agentId}`}
619
              onRuntime={(endpoint) => saveRuntime(agent.agentId, endpoint)}
620
              onDisableRuntime={() => disableRuntime(agent.agentId)}
621
            />
622
          ))
623
        ) : (
624
          <Empty
625
            title="No agents connected"
626
            text="Install the remote MCP endpoint in an agent, sign in, then create and register its identity."
627
            action="Open connection guide"
628
            onAction={() => navigate('connect')}
629
          />
630
        )}
631
      </section>
632
    </>
633
  );
634
}
635
636
function Invitations({
637
  data,
638
  refreshDashboard,
639
}: {
640
  data: DashboardData;
641
  refreshDashboard: () => Promise<void>;
642
}) {
643
  const [working, setWorking] = useState('');
644
  const [error, setError] = useState('');
645
  const ownedAgentIds = useMemo(
646
    () => new Set(data.agents.map((agent) => String(agent.agentId))),
647
    [data.agents],
648
  );
649
  const incoming = data.federatedInteractions.filter(
650
    (interaction) =>
651
      interaction.status === 'pending' && ownedAgentIds.has(String(interaction.responderAgentId)),
652
  );
653
  const respond = async (interactionId: string, agentId: string, decision: 'accept' | 'reject') => {
654
    setWorking(interactionId);
655
    setError('');
656
    try {
657
      await api(`/v0.1/federated-interactions/${encodeURIComponent(interactionId)}/respond`, {
658
        method: 'POST',
659
        body: JSON.stringify({ agentId, decision }),
660
      });
661
      await refreshDashboard();
662
    } catch (reason) {
663
      setError(reason instanceof Error ? reason.message : 'Could not respond to invitation');
664
    } finally {
665
      setWorking('');
666
    }
667
  };
668
  if (!incoming.length && !data.federatedInteractions.length) return null;
669
  return (
670
    <Panel
671
      title={incoming.length ? `Agent invitations (${incoming.length})` : 'Shared interactions'}
672
      subtitle="Both accounts see the same immutable contract and acceptance state"
673
    >
674
      {error ? <div className="errorBar">{error}</div> : null}
675
      {(incoming.length ? incoming : data.federatedInteractions.slice(0, 5)).map((interaction) => (
676
        <article className="setupRequest" key={interaction.interactionId}>
677
          <div>
678
            <strong>{interaction.contract?.purpose ?? interaction.interactionId}</strong>
679
            <small>
680
              {interaction.initiatorAgentId} → {interaction.responderAgentId} · {interaction.status}
681
            </small>
682
            <small>Contract: {String(interaction.termsHash).slice(0, 16)}…</small>
683
            {data.liveSessions.find(
684
              (session) => session.interactionId === interaction.interactionId,
685
            ) ? (
686
              <small className="autoAccepted">
687
                Live session:{' '}
688
                {
689
                  data.liveSessions.find(
690
                    (session) => session.interactionId === interaction.interactionId,
691
                  )?.status
692
                }
693
              </small>
694
            ) : null}
695
            {interaction.status === 'active' &&
696
            interaction.acceptances?.[interaction.responderAgentId]?.method ===
697
              'policy_auto_accept' ? (
698
              <small className="autoAccepted">✓ Auto-approved by the responder's safe policy</small>
699
            ) : null}
700
          </div>
701
          {interaction.status === 'pending' &&
702
          ownedAgentIds.has(String(interaction.responderAgentId)) ? (
703
            <div className="decisionButtons">
704
              <button
705
                className="secondary"
706
                disabled={working === interaction.interactionId}
707
                onClick={() =>
708
                  void respond(interaction.interactionId, interaction.responderAgentId, 'reject')
709
                }
710
              >
711
                Reject
712
              </button>
713
              <button
714
                className="primary"
715
                disabled={working === interaction.interactionId}
716
                onClick={() =>
717
                  void respond(interaction.interactionId, interaction.responderAgentId, 'accept')
718
                }
719
              >
720
                {working === interaction.interactionId ? 'Working…' : 'Accept contract'}
721
              </button>
722
            </div>
723
          ) : null}
724
        </article>
725
      ))}
726
    </Panel>
727
  );
728
}
729
730
function Insights({ data }: { data: DashboardData }) {
731
  return (
732
    <>
733
      <PageHead eyebrow="BEHAVIOURAL CONTEXT" title="Evidence, not reputation theatre." />
734
      <div className="notice">
735
        <strong>Context matters.</strong> OpenClasp profiles an agent by task category and version.
736
        It does not produce a single universal trust score.
737
      </div>
738
      <section className="agentGrid">
739
        {data.profiles.length ? (
740
          data.profiles.map((profile) => (
741
            <Panel
742
              key={`${profile.agentId}-${profile.taskCategory}`}
743
              title={profile.agentId}
744
              subtitle={`${profile.taskCategory} · v${profile.agentVersion}`}
745
            >
746
              <Profile profile={profile} expanded />
747
            </Panel>
748
          ))
749
        ) : (
750
          <Empty
751
            title="Not enough verified evidence"
752
            text="Insights grow only from signed outcomes, eligible feedback, corrections, disputes, and version-aware history."
753
          />
754
        )}
755
      </section>
756
    </>
757
  );
758
}
759
760
function Connect({
761
  data,
762
  refreshDashboard,
763
}: {
764
  data: DashboardData;
765
  refreshDashboard: () => Promise<void>;
766
}) {
767
  const endpoint = 'https://openclasp.vercel.app/mcp';
768
  const [copied, setCopied] = useState(false);
769
  const [working, setWorking] = useState('');
770
  const [decisionError, setDecisionError] = useState('');
771
  const pending = data.setupRequests.filter((request) => request.status === 'pending');
772
  useEffect(() => {
773
    const poll = () => void refreshDashboard().catch(() => undefined);
774
    poll();
775
    const timer = window.setInterval(poll, 5000);
776
    return () => window.clearInterval(timer);
777
  }, [refreshDashboard]);
778
  const decide = async (requestId: string, decision: 'approve' | 'reject') => {
779
    setWorking(requestId);
780
    setDecisionError('');
781
    try {
782
      await api(`/v0.1/onboarding/${encodeURIComponent(requestId)}/${decision}`, {
783
        method: 'POST',
784
      });
785
      await refreshDashboard();
786
    } catch (reason) {
787
      setDecisionError(reason instanceof Error ? reason.message : 'Could not update setup request');
788
    } finally {
789
      setWorking('');
790
    }
791
  };
792
  return (
793
    <>
794
      <PageHead eyebrow="AGENT CONNECTION" title="Add OpenClasp to an agent." />
795
      {pending.length > 0 && (
796
        <section className="setupRequests">
797
          <div>
798
            <p className="eyebrow">CONFIRMATION REQUIRED</p>
799
            <h2>Approve agent setup</h2>
800
            <p>
801
              An agent proposed this identity. Confirm it before OpenClasp binds the installation.
802
            </p>
803
          </div>
804
          {pending.map((request) => (
805
            <article className="setupRequest" key={request.requestId}>
806
              <div>
807
                <strong>{request.agentName ?? 'Switch installation'}</strong>
808
                <small>
809
                  {request.projectName ?? request.existingAgentId} · {request.framework}
810
                </small>
811
                {!!request.capabilities?.length && (
812
                  <div className="tags">
813
                    {request.capabilities.slice(0, 5).map((capability: string) => (
814
                      <span key={capability}>{capability}</span>
815
                    ))}
816
                  </div>
817
                )}
818
                {!!request.limitations?.length && (
819
                  <small>Limitations: {request.limitations.join(' · ')}</small>
820
                )}
821
                <div className="automationPreview">
822
                  <span>{request.autoPublish ? 'Public after approval' : 'Private'}</span>
823
                  <span>
824
                    {request.autoAcceptPolicy === 'safe_matching'
825
                      ? 'Auto-accept safe matches'
826
                      : 'Review every request'}
827
                  </span>
828
                </div>
829
              </div>
830
              <div className="decisionButtons">
831
                <button
832
                  className="secondary"
833
                  disabled={working === request.requestId}
834
                  onClick={() => void decide(request.requestId, 'reject')}
835
                >
836
                  Reject
837
                </button>
838
                <button
839
                  className="primary"
840
                  disabled={working === request.requestId}
841
                  onClick={() => void decide(request.requestId, 'approve')}
842
                >
843
                  {working === request.requestId ? 'Working…' : 'Approve & automate'}
844
                </button>
845
              </div>
846
            </article>
847
          ))}
848
          {decisionError && <div className="loginError">{decisionError}</div>}
849
        </section>
850
      )}
851
      <section className="connectLayout">
852
        <Panel title="Connect once" subtitle="OpenClasp handles the routine steps afterward">
853
          <div className="endpoint">
854
            <code>{endpoint}</code>
855
            <button
856
              onClick={() => {
857
                void navigator.clipboard.writeText(endpoint);
858
                setCopied(true);
859
              }}
860
            >
861
              {copied ? 'Copied' : 'Copy'}
862
            </button>
863
          </div>
864
          <ol>
865
            <li>Add this MCP URL and complete the OAuth sign-in.</li>
866
            <li>
867
              Tell the agent: <code>Set yourself up on OpenClasp</code>.
868
            </li>
869
            <li>
870
              Approve its identity and automation policy here once. That is the last routine manual
871
              step.
872
            </li>
873
          </ol>
874
        </Panel>
875
        <Panel
876
          title="What becomes automatic"
877
          subtitle="Safe defaults with deterministic approval boundaries"
878
        >
879
          <ul className="checkList">
880
            <li>Agent Card publication and discovery</li>
881
            <li>Contract defaults inferred from the task</li>
882
            <li>Safe matching invitations accepted immediately</li>
883
            <li>Ready-to-send A2A endpoint, headers, and metadata</li>
884
            <li>Risky requests routed to human review</li>
885
          </ul>
886
        </Panel>
887
      </section>
888
    </>
889
  );
890
}
891
892
function SettingsPage({
893
  settings,
894
  setSettings,
895
}: {
896
  settings: Settings;
897
  setSettings: React.Dispatch<React.SetStateAction<Settings>>;
898
}) {
899
  const [saving, setSaving] = useState(false);
900
  const [saved, setSaved] = useState(false);
901
  const save = useCallback(async () => {
902
    setSaving(true);
903
    setSaved(false);
904
    const updated = (await api('/v0.1/settings', {
905
      method: 'PUT',
906
      body: JSON.stringify(settings),
907
    })) as Settings;
908
    setSettings(updated);
909
    setSaving(false);
910
    setSaved(true);
911
  }, [settings, setSettings]);
912
  return (
913
    <>
914
      <PageHead eyebrow="ACCOUNT CONTROLS" title="Privacy and network settings." />
915
      <section className="settingsCard">
916
        <Setting label="Display name" description="Shown only inside your OpenClasp account.">
917
          <input
918
            value={settings.displayName}
919
            onChange={(event) =>
920
              setSettings((value) => ({ ...value, displayName: event.target.value }))
921
            }
922
            placeholder="Team or operator name"
923
          />
924
        </Setting>
925
        <Setting
926
          label="Network contribution"
927
          description="Allow eligible structured aggregates to improve contextual intelligence. Raw conversations are never included."
928
        >
929
          <Toggle
930
            checked={settings.contributionEnabled}
931
            onChange={(checked) =>
932
              setSettings((value) => ({ ...value, contributionEnabled: checked }))
933
            }
934
          />
935
        </Setting>
936
        <Setting
937
          label="Evidence sharing"
938
          description="Controls when permitted evidence references may be shared with interaction participants."
939
        >
940
          <select
941
            value={settings.evidenceSharing}
942
            onChange={(event) =>
943
              setSettings((value) => ({
944
                ...value,
945
                evidenceSharing: event.target.value as Settings['evidenceSharing'],
946
              }))
947
            }
948
          >
949
            <option value="never">Never</option>
950
            <option value="ask">Ask every time</option>
951
            <option value="contract_only">When contract permits</option>
952
          </select>
953
        </Setting>
954
        <Setting
955
          label="Structured record retention"
956
          description="Retention for hosted account records. Signed protocol records may require separate revocation markers."
957
        >
958
          <select
959
            value={settings.retentionDays}
960
            onChange={(event) =>
961
              setSettings((value) => ({ ...value, retentionDays: Number(event.target.value) }))
962
            }
963
          >
964
            <option value={7}>7 days</option>
965
            <option value={30}>30 days</option>
966
            <option value={90}>90 days</option>
967
            <option value={365}>1 year</option>
968
            <option value={0}>No automatic deletion</option>
969
          </select>
970
        </Setting>
971
        <Setting
972
          label="Raw agent messages"
973
          description="Travel directly between agent-owned runtimes. OpenClasp stores structured events and hashes only."
974
        >
975
          <span className="locked">NOT STORED</span>
976
        </Setting>
977
        <div className="saveRow">
978
          <button className="primary" onClick={() => void save()} disabled={saving}>
979
            {saving ? 'Saving…' : 'Save settings'}
980
          </button>
981
          {saved && <span>Saved</span>}
982
        </div>
983
      </section>
984
    </>
985
  );
986
}
987
988
function PageHead({
989
  eyebrow,
990
  title,
991
  action,
992
  onAction,
993
}: {
994
  eyebrow: string;
995
  title: string;
996
  action?: string;
997
  onAction?: () => void;
998
}) {
999
  return (
1000
    <header className="pageHead">
1001
      <div>
1002
        <p className="eyebrow">{eyebrow}</p>
1003
        <h1>{title}</h1>
1004
      </div>
1005
      {action && (
1006
        <button className="primary" onClick={onAction}>
1007
          {action}
1008
        </button>
1009
      )}
1010
    </header>
1011
  );
1012
}
1013
function Nav({
1014
  page,
1015
  active,
1016
  onClick,
1017
  label,
1018
  glyph,
1019
}: {
1020
  page: Page;
1021
  active: Page;
1022
  onClick: (page: Page) => void;
1023
  label: string;
1024
  glyph: string;
1025
}) {
1026
  return (
1027
    <button className={active === page ? 'active' : ''} onClick={() => onClick(page)}>
1028
      <span>{glyph}</span>
1029
      {label}
1030
    </button>
1031
  );
1032
}
1033
function Metric({
1034
  label,
1035
  value,
1036
  note,
1037
  warn,
1038
}: {
1039
  label: string;
1040
  value: number;
1041
  note: string;
1042
  warn?: boolean;
1043
}) {
1044
  return (
1045
    <article className={warn ? 'metric warn' : 'metric'}>
1046
      <span>{label}</span>
1047
      <strong>{String(value).padStart(2, '0')}</strong>
1048
      <small>{note}</small>
1049
    </article>
1050
  );
1051
}
1052
function Panel({
1053
  title,
1054
  subtitle,
1055
  children,
1056
}: React.PropsWithChildren<{ title: string; subtitle: string }>) {
1057
  return (
1058
    <section className="panel">
1059
      <div className="panelHead">
1060
        <div>
1061
          <h2>{title}</h2>
1062
          <p>{subtitle}</p>
1063
        </div>
1064
      </div>
1065
      {children}
1066
    </section>
1067
  );
1068
}
1069
function Timeline({ events }: { events: Record<string, any>[] }) {
1070
  return events.length ? (
1071
    <div className="timeline">
1072
      {events.map((event) => (
1073
        <HistoryRow key={event.eventId} item={{ ...event, _kind: 'event' }} />
1074
      ))}
1075
    </div>
1076
  ) : (
1077
    <Empty
1078
      title="Nothing recorded yet"
1079
      text="Activity appears after your connected agents submit signed structured events."
1080
    />
1081
  );
1082
}
1083
function HistoryRow({ item }: { item: Record<string, any> }) {
1084
  const kind = String(item.eventType ?? item._kind ?? 'record').replaceAll('_', ' ');
1085
  const id = String(item.agentId ?? item.interactionId ?? item.receiptId ?? 'OpenClasp');
1086
  return (
1087
    <article className="historyRow">
1088
      <span className={`eventDot ${item.eventType ?? item._kind}`} />
1089
      <div>
1090
        <strong>{kind}</strong>
1091
        <small>
1092
          {id} · {new Date(timestamp(item)).toLocaleString()}
1093
        </small>
1094
      </div>
1095
      <b>{item.visibility ?? item.outcome ?? item.status ?? 'SIGNED'}</b>
1096
    </article>
1097
  );
1098
}
1099
function AgentCard({
1100
  agent,
1101
  projectName,
1102
  published,
1103
  working,
1104
  onSave,
1105
  runtime,
1106
  runtimeWorking,
1107
  onRuntime,
1108
  onDisableRuntime,
1109
}: {
1110
  agent: Record<string, any>;
1111
  projectName?: string;
1112
  published: boolean;
1113
  working: boolean;
1114
  onSave: (value: {
1115
    autoPublish: boolean;
1116
    autoAcceptPolicy: 'off' | 'safe_matching';
1117
    autoAcceptTaskCategories: string[];
1118
  }) => void;
1119
  runtime: Record<string, any> | undefined;
1120
  runtimeWorking: boolean;
1121
  onRuntime: (endpoint: string) => void;
1122
  onDisableRuntime: () => void;
1123
}) {
1124
  const [editing, setEditing] = useState(false);
1125
  const [autoPublish, setAutoPublish] = useState(Boolean(agent.autoPublish ?? published));
1126
  const [autoAcceptPolicy, setAutoAcceptPolicy] = useState<'off' | 'safe_matching'>(
1127
    agent.autoAcceptPolicy === 'safe_matching' ? 'safe_matching' : 'off',
1128
  );
1129
  const [categories, setCategories] = useState<string>(
1130
    (agent.autoAcceptTaskCategories?.length
1131
      ? agent.autoAcceptTaskCategories
1132
      : (agent.capabilities ?? [])
1133
    ).join(', '),
1134
  );
1135
  const [runtimeEndpoint, setRuntimeEndpoint] = useState(String(runtime?.endpoint ?? ''));
1136
  const ready = published;
1137
  const online = agent.presence?.status === 'online';
1138
  const endpoint = String(runtime?.a2aEndpoint ?? agent.a2aEndpoint ?? 'Connect a runtime first');
1139
  const identityLabel = agent.revoked
1140
    ? 'REVOKED'
1141
    : agent.identityMode === 'oauth_installation'
1142
      ? 'AUTHENTICATED'
1143
      : 'VERIFIED';
1144
  return (
1145
    <article className="agentCard">
1146
      <div className="agentTop">
1147
        <span className="agentGlyph">◇</span>
1148
        <div className="agentBadges">
1149
          <b className={online ? 'onlineBadge' : 'offlineBadge'}>
1150
            ● {online ? 'ONLINE' : 'OFFLINE'}
1151
          </b>
1152
          <b className={agent.revoked ? 'bad' : ''}>{identityLabel}</b>
1153
          <b className={ready ? 'readyBadge' : 'needsBadge'}>{ready ? 'READY' : 'SETUP NEEDED'}</b>
1154
        </div>
1155
      </div>
1156
      <h2>{agent.name ?? agent.agentId}</h2>
1157
      <p>{projectName ?? `Version ${agent.agentVersion ?? '1.0.0'}`}</p>
1158
      <div className="tags">
1159
        {(agent.capabilities ?? []).slice(0, 4).map((capability: string) => (
1160
          <span key={capability}>{capability}</span>
1161
        ))}
1162
      </div>
1163
      <small>
1164
        {agent.framework ? `${agent.framework} · ` : ''}
1165
        {agent.identityMode === 'oauth_installation' ? 'OAuth-bound · ' : 'Ed25519 · '}Created{' '}
1166
        {new Date(agent.createdAt).toLocaleDateString()}
1167
      </small>
1168
      <small>
1169
        {agent.presence?.lastSeenAt
1170
          ? `Last agent activity ${new Date(agent.presence.lastSeenAt).toLocaleString()}`
1171
          : 'No agent activity recorded yet'}
1172
      </small>
1173
      {published ? (
1174
        <a
1175
          href={`/agents/${encodeURIComponent(agent.agentId)}/card.json`}
1176
          target="_blank"
1177
          rel="noreferrer"
1178
        >
1179
          Public Agent Card ↗
1180
        </a>
1181
      ) : null}
1182
      <div className="automationSummary">
1183
        <span>{published ? '● Public discovery' : '○ Private'}</span>
1184
        <span>↗ Direct agent-owned A2A</span>
1185
        <span>
1186
          {agent.autoAcceptPolicy === 'safe_matching'
1187
            ? '⚡ Safe tasks automatic'
1188
            : '◷ Manual approval'}
1189
        </span>
1190
      </div>
1191
      <div className="runtimeBox">
1192
        <div>
1193
          <strong>Autonomous runtime</strong>
1194
          <span className={runtime?.status === 'verified' ? 'runtimeLive' : 'runtimeMissing'}>
1195
            {runtime?.status === 'verified' ? 'VERIFIED' : 'NOT CONNECTED'}
1196
          </span>
1197
        </div>
1198
        <p>
1199
          Connect the worker running on your cloud. OpenClasp uses this callback only to prepare a
1200
          live session; messages then travel directly between agents.
1201
        </p>
1202
        <input
1203
          type="url"
1204
          value={runtimeEndpoint}
1205
          onChange={(event) => setRuntimeEndpoint(event.target.value)}
1206
          placeholder="https://agent.example.com/openclasp"
1207
        />
1208
        <div className="agentActions">
1209
          {runtime?.status === 'verified' ? (
1210
            <button className="secondary" disabled={runtimeWorking} onClick={onDisableRuntime}>
1211
              Disable runtime
1212
            </button>
1213
          ) : null}
1214
          <button
1215
            className="primary"
1216
            disabled={runtimeWorking || !runtimeEndpoint.trim()}
1217
            onClick={() => onRuntime(runtimeEndpoint.trim())}
1218
          >
1219
            {runtimeWorking ? 'Verifying…' : runtime ? 'Rotate connection' : 'Verify & connect'}
1220
          </button>
1221
        </div>
1222
        {runtime?.lastError ? <small>Last session error: {runtime.lastError}</small> : null}
1223
      </div>
1224
      {editing ? (
1225
        <div className="automationForm">
1226
          <label>
1227
            <span>Agent-owned A2A endpoint</span>
1228
            <input type="url" value={endpoint} readOnly />
1229
          </label>
1230
          <label>
1231
            <span>Invitation policy</span>
1232
            <select
1233
              value={autoAcceptPolicy}
1234
              onChange={(event) =>
1235
                setAutoAcceptPolicy(event.target.value as 'off' | 'safe_matching')
1236
              }
1237
            >
1238
              <option value="safe_matching">Auto-accept safe matches</option>
1239
              <option value="off">Review every request</option>
1240
            </select>
1241
          </label>
1242
          <label>
1243
            <span>Safe task categories</span>
1244
            <input
1245
              value={categories}
1246
              onChange={(event) => setCategories(event.target.value)}
1247
              placeholder="research, planning, coding"
1248
            />
1249
          </label>
1250
          <label className="checkControl">
1251
            <input
1252
              type="checkbox"
1253
              checked={autoPublish}
1254
              onChange={(event) => setAutoPublish(event.target.checked)}
1255
            />
1256
            <span>Publish and keep Agent Card updated</span>
1257
          </label>
1258
          <div className="agentActions">
1259
            <button className="secondary" onClick={() => setEditing(false)}>
1260
              Cancel
1261
            </button>
1262
            <button
1263
              className="primary"
1264
              disabled={working || agent.status === 'revoked'}
1265
              onClick={() =>
1266
                onSave({
1267
                  autoPublish,
1268
                  autoAcceptPolicy,
1269
                  autoAcceptTaskCategories: categories
1270
                    .split(',')
1271
                    .map((value) => value.trim())
1272
                    .filter(Boolean),
1273
                })
1274
              }
1275
            >
1276
              {working ? 'Saving…' : 'Save automation'}
1277
            </button>
1278
          </div>
1279
        </div>
1280
      ) : (
1281
        <button
1282
          className="secondary"
1283
          disabled={working || agent.status === 'revoked'}
1284
          onClick={() => setEditing(true)}
1285
        >
1286
          Configure automation
1287
        </button>
1288
      )}
1289
    </article>
1290
  );
1291
}
1292
function Profile({ profile, expanded }: { profile: Record<string, any>; expanded?: boolean }) {
1293
  const dimensions = [
1294
    ['Completion', profile.completion],
1295
    ['Scope', profile.scope],
1296
    ['Evidence', profile.evidence],
1297
    ...(expanded
1298
      ? [
1299
          ['Communication', profile.communication],
1300
          ['Deadline', profile.deadline],
1301
        ]
1302
      : []),
1303
  ] as [string, number][];
1304
  return (
1305
    <article className="profile">
1306
      <div>
1307
        <strong>{profile.agentId}</strong>
1308
        <small>
1309
          {profile.taskCategory} · {profile.sampleSize} outcome(s)
1310
        </small>
1311
      </div>
1312
      {dimensions.map(([label, value]) => (
1313
        <Meter key={label} label={label} value={value ?? 0} />
1314
      ))}
1315
    </article>
1316
  );
1317
}
1318
function Meter({ label, value }: { label: string; value: number }) {
1319
  return (
1320
    <div className="meter">
1321
      <span>{label}</span>
1322
      <i>
1323
        <b style={{ width: `${Math.round(value * 100)}%` }} />
1324
      </i>
1325
      <strong>{Math.round(value * 100)}%</strong>
1326
    </div>
1327
  );
1328
}
1329
function Empty({
1330
  title,
1331
  text,
1332
  action,
1333
  onAction,
1334
}: {
1335
  title: string;
1336
  text: string;
1337
  action?: string;
1338
  onAction?: () => void;
1339
}) {
1340
  return (
1341
    <div className="empty">
1342
      <span>◇</span>
1343
      <strong>{title}</strong>
1344
      <p>{text}</p>
1345
      {action && (
1346
        <button className="secondary" onClick={onAction}>
1347
          {action}
1348
        </button>
1349
      )}
1350
    </div>
1351
  );
1352
}
1353
function TextButton({ children, onClick }: React.PropsWithChildren<{ onClick: () => void }>) {
1354
  return (
1355
    <button className="textButton" onClick={onClick}>
1356
      {children}
1357
    </button>
1358
  );
1359
}
1360
function Setting({
1361
  label,
1362
  description,
1363
  children,
1364
}: React.PropsWithChildren<{ label: string; description: string }>) {
1365
  return (
1366
    <div className="setting">
1367
      <div>
1368
        <strong>{label}</strong>
1369
        <p>{description}</p>
1370
      </div>
1371
      <div>{children}</div>
1372
    </div>
1373
  );
1374
}
1375
function Toggle({ checked, onChange }: { checked: boolean; onChange: (checked: boolean) => void }) {
1376
  return (
1377
    <button
1378
      className={checked ? 'toggle on' : 'toggle'}
1379
      role="switch"
1380
      aria-checked={checked}
1381
      onClick={() => onChange(!checked)}
1382
    >
1383
      <span />
1384
    </button>
1385
  );
1386
}
1387
function Loading({ compact }: { compact?: boolean }) {
1388
  return (
1389
    <div className={compact ? 'loading compact' : 'loading'}>
1390
      <span className="mark">OC</span>
1391
      <p>Verifying session…</p>
1392
    </div>
1393
  );
1394
}
1395
function initials(value: string) {
1396
  return value
1397
    .split(/\s+|@/)
1398
    .slice(0, 2)
1399
    .map((part) => part[0]?.toUpperCase())
1400
    .join('');
1401
}
1402
function timestamp(item: Record<string, any>) {
1403
  return String(item.timestamp ?? item.completedAt ?? item.createdAt ?? new Date(0).toISOString());
1404
}
1405
1406
if (!__AUTH0_DOMAIN__ || !__AUTH0_CLIENT_ID__ || !__AUTH0_AUDIENCE__)
1407
  throw new Error('Auth0 public configuration is incomplete');
1408
createRoot(document.getElementById('root')!).render(
1409
  <React.StrictMode>
1410
    {location.pathname === '/sso-callback' ? <AuthCallback /> : <App />}
1411
  </React.StrictMode>,
1412
);