patchwise-agent-studio / web /src /account /AccessTokensCard.tsx
EnergyVenom's picture
Tidy the web app: pages by area, CSS in load order, web/README.md (b2a039d)
fb43301 verified
Raw History Blame Contribute Delete
7.36 kB
import { Button, CopyButton, Group, Radio, Stack, Text, TextInput } from '@mantine/core';
import { IconCheck, IconCopy, IconKey } from '@/components/icons';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState, type FormEvent } from 'react';
import { useLocation } from 'react-router-dom';
import { sendJson } from '../api/client';
import { ErrorAlert, fmtTs } from '../components/common';
import { shortWhen } from '../domain/runName';
import { isActive, scopeWords, TOKENS_KEY, useAccessTokens, type AccessToken, type CreatedToken } from './useAccessTokens';
import './account-tokens.css';
/** One of your tokens: what it allows, when it was last used, when it expires, and Revoke (asked twice). */
function TokenRow({ t }: { t: AccessToken }) {
const qc = useQueryClient();
const [sure, setSure] = useState(false);
const revoke = useMutation({
mutationFn: () => sendJson<null>('DELETE', `/api/tokens/${t.id}`),
onSuccess: () => { setSure(false); void qc.invalidateQueries({ queryKey: TOKENS_KEY }); },
});
const active = isActive(t);
return (
<li className="tok-row" data-testid={`token-${t.id}`} data-active={active || undefined}>
<div className="tok-main">
<b className="tok-name">{t.name}</b>
<span className="tok-meta">
{scopeWords(t)} · ends in <span className="tok-last4">…{t.last4}</span>
</span>
<span className="tok-meta">
{t.revoked_at ? `Revoked ${shortWhen(t.revoked_at)}` : active ? `Expires ${shortWhen(t.expires_at)}` : `Expired ${shortWhen(t.expires_at)}`}
{' · '}{t.last_used_at ? <span title={fmtTs(t.last_used_at)}>Last used {shortWhen(t.last_used_at)}</span> : 'Never used'}
</span>
</div>
{active && (!sure ? (
<Button variant="subtle" color="red" size="xs" onClick={() => setSure(true)} aria-label={`Revoke the token ${t.name}`}>Revoke</Button>
) : (
<Group gap="xs" role="group" aria-label={`Revoke the token ${t.name}?`}>
<Text size="sm">Assistants using it lose access.</Text>
<Button color="red" variant="filled" size="xs" onClick={() => revoke.mutate()} loading={revoke.isPending}>Yes, revoke</Button>
<Button variant="default" size="xs" onClick={() => setSure(false)}>Keep it</Button>
</Group>
))}
{revoke.error ? <div className="tok-err"><ErrorAlert error={revoke.error} title="The token was not revoked" /></div> : null}
</li>
);
}
/** The new token, once: a labelled, copyable field and a clear warning. It lives only in this component's memory. */
function ShownOnce({ created, onDone }: { created: CreatedToken; onDone: () => void }) {
return (
<div className="tok-once" role="region" aria-label="Your new token" data-testid="token-once">
<Text size="sm" fw={600}>Copy it now: it won't be shown again.</Text>
<Group gap="xs" align="flex-end" wrap="nowrap">
<TextInput label="Your new token" readOnly value={created.token} className="tok-value" onFocus={(e) => e.currentTarget.select()}
spellCheck={false} autoComplete="off" />
<CopyButton value={created.token} timeout={2000}>
{({ copied, copy }) => (
<Button onClick={copy} leftSection={copied ? <IconCheck size={15} aria-hidden /> : <IconCopy size={15} aria-hidden />} aria-label="Copy the token">
{copied ? 'Copied' : 'Copy'}
</Button>
)}
</CopyButton>
</Group>
<Text size="xs" c="dimmed">Expires {fmtTs(created.expires_at)}. Paste it into your assistant's settings, then close this.</Text>
<Group><Button variant="default" onClick={onDone}>Done, I've copied it</Button></Group>
</div>
);
}
/** Account → Access tokens for AI assistants: create a token (shown once), see and revoke your own. */
export function AccessTokensCard() {
const qc = useQueryClient();
const tokens = useAccessTokens();
const [name, setName] = useState('');
const [scopes, setScopes] = useState<'read' | 'read,act'>('read');
const [days, setDays] = useState('90');
const [created, setCreated] = useState<CreatedToken | null>(null);
const create = useMutation({
mutationFn: () => sendJson<CreatedToken>('POST', '/api/tokens', { name: name.trim(), scopes, days: Number(days) }),
onSuccess: (r) => { setCreated(r); setName(''); void qc.invalidateQueries({ queryKey: TOKENS_KEY }); },
});
const onSubmit = (e: FormEvent) => { e.preventDefault(); if (name.trim()) create.mutate(); };
const items = tokens.data?.items ?? [];
const loc = useLocation();
const ref = useRef<HTMLElement>(null);
// arriving from Integrations ("/account#tokens"): bring the card into view
useEffect(() => { if (loc.hash === '#tokens') ref.current?.scrollIntoView?.({ block: 'start' }); }, [loc.hash]);
return (
<section ref={ref} id="tokens" className="fpt-card tok-card" style={{ padding: 20 }} aria-labelledby="acc-tokens">
<h2 id="acc-tokens" className="trio-card-h"><IconKey size={18} aria-hidden /> Access tokens for AI assistants</h2>
<Text size="sm" mt={4}>
A token lets Microsoft Copilot, Claude, ChatGPT or another assistant use Astra as you, with your permissions.
Anything that changes something, such as starting a run, still asks you to confirm. Sign-off stays in Astra.
</Text>
{created && <ShownOnce created={created} onDone={() => setCreated(null)} />}
<h3 className="tok-subh">Your tokens</h3>
<ErrorAlert error={tokens.error} title="Your tokens could not be loaded" />
{tokens.isLoading ? <Text size="sm" c="dimmed">Loading your tokens…</Text>
: items.length === 0 ? <Text size="sm" c="dimmed" data-testid="tokens-empty">You have no tokens yet.</Text>
: <ul className="tok-list" aria-label="Your tokens">{items.map((t) => <TokenRow key={t.id} t={t} />)}</ul>}
<h3 className="tok-subh">Create a token</h3>
<form onSubmit={onSubmit} aria-label="Create a token">
<Stack gap="sm" maw={520}>
<TextInput label="Name" description="Where you will use it, for example Claude on my laptop." required value={name}
onChange={(e) => setName(e.currentTarget.value)} maxLength={60} />
<Radio.Group label="What it allows" value={scopes} onChange={(v) => setScopes(v as 'read' | 'read,act')}>
<Stack gap={6} mt={4}>
<Radio value="read" label="Read only: readiness, what's waiting, runs and reports" />
<Radio value="read,act" label="Read and start runs or approve scenarios (you confirm each)" />
</Stack>
</Radio.Group>
<Radio.Group label="Expires after" value={days} onChange={setDays}>
<Group gap="md" mt={4}>
<Radio value="30" label="30 days" /><Radio value="90" label="90 days" /><Radio value="365" label="1 year" />
</Group>
</Radio.Group>
<Group><Button type="submit" variant="filled" disabled={!name.trim()} loading={create.isPending}>Create token</Button></Group>
<ErrorAlert error={create.error} title="The token was not created" />
</Stack>
</form>
</section>
);
}