Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(settings): add the Claude section for tokens and approved apps
spacesdrivec392e219c365
diff --git a/frontend/src/features/settings/ClaudeClientList.tsx b/frontend/src/features/settings/ClaudeClientList.tsxnew file mode 100644index 0000000..5bd120b--- /dev/null+++ b/frontend/src/features/settings/ClaudeClientList.tsx@@ -0,0 +1,74 @@+import React, { useState } from 'react';+import { AppWindow, Trash2 } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import ConfirmDialog from '@/components/ConfirmDialog';+import RelativeTime from '@/components/RelativeTime';+import RowAction from '@/components/RowAction';+import { EmptyState } from '@/components/StateViews';+import { permissionLabel } from './claudeAccessData';+import type { McpClientGrantSummary } from '@shared/types/mcp.ts';++export interface ClaudeClientListProps {+ clients: McpClientGrantSummary[];+ oauthEnabled: boolean;+ revokingId: string | null;+ onRemove: (id: string, name: string) => Promise<boolean>;+}++function ClientRow({ client, onAskRemove }: { client: McpClientGrantSummary; onAskRemove: () => void }) {+ return (+ <li className="flex items-start justify-between gap-4 px-4 py-3">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <p className="truncate text-sm font-medium text-ink">{client.clientName}</p>+ <Badge variant={client.permission === 'write' ? 'warning' : 'secondary'}>{permissionLabel(client.permission)}</Badge>+ </div>+ <p className="text-caption text-ink-muted">+ <RelativeTime date={client.createdAt} prefix="Approved " />+ <span aria-hidden="true"> · </span><span className="sr-only">, </span>+ {client.lastUsedAt ? <RelativeTime date={client.lastUsedAt} prefix="Used " /> : 'Never used'}+ </p>+ </div>+ <RowAction label="Remove" target={client.clientName} onClick={onAskRemove} danger>+ <Trash2 />+ </RowAction>+ </li>+ );+}++export default function ClaudeClientList({ clients, oauthEnabled, revokingId, onRemove }: ClaudeClientListProps) {+ const [pending, setPending] = useState<McpClientGrantSummary | null>(null);++ if (clients.length === 0) {+ return (+ <EmptyState+ compact+ icon={<AppWindow />}+ title="No apps approved yet"+ description={oauthEnabled+ ? 'Add Twiligent as a custom connector in Claude. You approve it here when Claude asks.'+ : 'Claude on the web, desktop and mobile can connect once the instance owner turns on connector sign-in.'}+ />+ );+ }++ return (+ <>+ <ul className="divide-y divide-divider">+ {clients.map(client => <ClientRow key={client.id} client={client} onAskRemove={() => setPending(client)} />)}+ </ul>+ <ConfirmDialog+ open={pending !== null}+ onOpenChange={open => { if (!open) setPending(null); }}+ title={`Remove ${pending?.clientName ?? 'this app'}?`}+ description="It loses access to your account at its next request. To use it again, connect it in Claude and approve it here."+ confirmLabel="Remove app"+ busyLabel="Removing"+ busy={pending !== null && revokingId === pending.id}+ onConfirm={() => {+ if (pending) void onRemove(pending.id, pending.clientName).then(done => { if (done) setPending(null); });+ }}+ />+ </>+ );+}diff --git a/frontend/src/features/settings/ClaudeSection.tsx b/frontend/src/features/settings/ClaudeSection.tsxnew file mode 100644index 0000000..2acfbfb--- /dev/null+++ b/frontend/src/features/settings/ClaudeSection.tsx@@ -0,0 +1,109 @@+import React, { useEffect } from 'react';+import { CheckCircle2 } from 'lucide-react';+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import SurfaceBox from '@/components/SurfaceBox';+import { FieldRow } from '@/components/DetailPanel';+import { ErrorState } from '@/components/StateViews';+import { docsUrl } from '@/lib/docs';+import { useAppContext } from '../../context/AppContext';+import SettingsSection from './SettingsSection';+import CopyField from './CopyField';+import ClaudeTokenForm from './ClaudeTokenForm';+import ClaudeTokenList from './ClaudeTokenList';+import ClaudeClientList from './ClaudeClientList';+import { claudeCodeCommand } from './claudeAccessData';+import { useClaudeAccess } from './useClaudeAccess';+import type { CreatedToken } from './useClaudeAccess';++function CreatedTokenNotice({ created, serverUrl, onDone }: { created: CreatedToken; serverUrl: string; onDone: () => void }) {+ // the token is shown once, so focus goes to it for keyboard and screen reader users+ useEffect(() => {+ document.getElementById('mcp-new-token')?.focus();+ }, [created.token]);++ return (+ <Alert>+ <CheckCircle2 />+ <AlertTitle>Copy {created.summary.label} now</AlertTitle>+ <AlertDescription className="flex flex-col gap-3">+ <p>This is the only time the token is shown. Store it like a password; anyone who has it can act as you.</p>+ <FieldRow label="Access token" htmlFor="mcp-new-token">+ <CopyField id="mcp-new-token" label="access token" value={created.token} />+ </FieldRow>+ <FieldRow label="Claude Code command with this token" htmlFor="mcp-new-command">+ <CopyField id="mcp-new-command" label="Claude Code command" value={claudeCodeCommand(serverUrl, created.token)} />+ </FieldRow>+ <Button variant="outline" size="sm" className="self-start" onClick={onDone}>I copied it</Button>+ </AlertDescription>+ </Alert>+ );+}++export default function ClaudeSection() {+ const { showToast } = useAppContext();+ const state = useClaudeAccess(showToast);+ const { access, error, loading } = state;++ return (+ <SettingsSection+ id="claude"+ title="Claude"+ description="Let Claude read your analytics and manage your scheduled posts. Each connection acts as you and can do only what you allow."+ >+ {loading && !access && (+ <div role="status" className="flex flex-col gap-4">+ <span className="sr-only">Loading Claude connection settings</span>+ <Skeleton className="h-40 rounded-card" />+ <Skeleton className="h-40 rounded-card" />+ </div>+ )}++ {error && !access && (+ <SurfaceBox>+ <ErrorState title="Claude connection settings could not load" description={error} onRetry={() => { void state.reload(); }} />+ </SurfaceBox>+ )}++ {access && (+ <>+ <SurfaceBox title="Connect Claude" headingLevel="h3">+ <div className="flex flex-col gap-4">+ <FieldRow label="Server address" htmlFor="mcp-server-url">+ <CopyField id="mcp-server-url" label="server address" value={access.serverUrl} />+ </FieldRow>+ <FieldRow label="Claude Code" htmlFor="mcp-command" hint="Run this in a terminal, with twl_your_token replaced by a token you create below.">+ <CopyField id="mcp-command" label="Claude Code command" value={claudeCodeCommand(access.serverUrl)} />+ </FieldRow>+ <p className="max-w-prose text-body text-ink-muted">+ {access.oauthEnabled+ ? 'Claude on the web, desktop and mobile: add a custom connector with the server address, then approve it when Twiligent asks.'+ : 'Claude on the web, desktop and mobile needs connector sign-in, which the instance owner has not turned on yet. Claude Code works now with a token.'}+ {' '}+ <a href={docsUrl('/use/claude')} target="_blank" rel="noopener noreferrer" className="font-semibold text-ink underline underline-offset-4">+ How to connect Claude<span className="sr-only"> (opens in a new tab)</span>+ </a>+ </p>+ </div>+ </SurfaceBox>++ <SurfaceBox title="Access tokens" headingLevel="h3" subheader="For Claude Code and other clients that send a token. Each one signs in as you.">+ <div className="flex flex-col gap-6">+ {state.created && <CreatedTokenNotice created={state.created} serverUrl={access.serverUrl} onDone={state.dismissCreated} />}+ <ClaudeTokenForm creating={state.creating} onCreate={state.createToken} />+ </div>+ </SurfaceBox>++ <SurfaceBox title="Your tokens" headingLevel="h3" content={false}>+ <ClaudeTokenList tokens={access.tokens} revokingId={state.revokingId} onRevoke={state.revokeToken} />+ </SurfaceBox>++ <SurfaceBox title="Approved apps" headingLevel="h3" subheader="Claude apps you approved through connector sign-in." content={false}>+ <ClaudeClientList clients={access.clients} oauthEnabled={access.oauthEnabled} revokingId={state.revokingId} onRemove={state.revokeClient} />+ </SurfaceBox>+ </>+ )}+ </SettingsSection>+ );+}diff --git a/frontend/src/features/settings/ClaudeTokenForm.tsx b/frontend/src/features/settings/ClaudeTokenForm.tsxnew file mode 100644index 0000000..9c30a66--- /dev/null+++ b/frontend/src/features/settings/ClaudeTokenForm.tsx@@ -0,0 +1,81 @@+import React, { useState } from 'react';+import { Plus } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';+import { Spinner } from '@/components/ui/spinner';+import SegmentedChoice from '@/components/SegmentedChoice';+import { FieldRow } from '@/components/DetailPanel';+import {+ DEFAULT_EXPIRY, EXPIRY_OPTIONS, PERMISSION_OPTIONS, TOKEN_LABEL_MAX_LENGTH, expiryDays, tokenLabelError,+} from './claudeAccessData';+import type { ExpiryChoice } from './claudeAccessData';+import type { McpAccessTokenCreateRequest, McpPermission } from '@shared/types/mcp.ts';++export interface ClaudeTokenFormProps {+ creating: boolean;+ onCreate: (input: McpAccessTokenCreateRequest) => Promise<boolean>;+}++export default function ClaudeTokenForm({ creating, onCreate }: ClaudeTokenFormProps) {+ const [label, setLabel] = useState('');+ // read only is the default, so a token that only needs to look cannot change anything+ const [permission, setPermission] = useState<McpPermission>('read');+ const [expiry, setExpiry] = useState<ExpiryChoice>(DEFAULT_EXPIRY);+ const [tried, setTried] = useState(false);+ const labelError = tried ? tokenLabelError(label) : null;++ async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {+ e.preventDefault();+ if (creating) return;+ setTried(true);+ if (tokenLabelError(label)) {+ document.getElementById('mcp-token-label')?.focus();+ return;+ }+ const done = await onCreate({ label: label.trim(), permission, expiresInDays: expiryDays(expiry) });+ if (done) {+ setLabel('');+ setTried(false);+ }+ }++ return (+ <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-4">+ <FieldRow label="Name" htmlFor="mcp-token-label" hint="Where you will use it, such as Work laptop." error={labelError ?? undefined}>+ <Input+ id="mcp-token-label"+ value={label}+ onChange={e => setLabel(e.target.value)}+ maxLength={TOKEN_LABEL_MAX_LENGTH}+ autoComplete="off"+ required+ className="max-w-sm"+ />+ </FieldRow>+ <FieldRow label="What Claude may do" htmlFor="mcp-token-permission" group hint="Making changes covers scheduling, editing and cancelling posts and saving settings. Claude asks you to confirm before it schedules or cancels a post.">+ <SegmentedChoice<McpPermission>+ name="mcp-token-permission"+ id="mcp-token-permission"+ options={PERMISSION_OPTIONS}+ value={permission}+ onChange={setPermission}+ />+ </FieldRow>+ <FieldRow label="Expires" htmlFor="mcp-token-expiry">+ <Select value={expiry} onValueChange={value => setExpiry(value as ExpiryChoice)} items={EXPIRY_OPTIONS}>+ <SelectTrigger id="mcp-token-expiry" className="w-full max-w-sm"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {EXPIRY_OPTIONS.map(option => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FieldRow>+ <Button type="submit" variant="outline" className="self-start" disabled={creating}>+ {creating ? <Spinner className="size-4" /> : <Plus data-icon="inline-start" />}+ {creating ? 'Creating token' : 'Create token'}+ </Button>+ </form>+ );+}diff --git a/frontend/src/features/settings/ClaudeTokenList.tsx b/frontend/src/features/settings/ClaudeTokenList.tsxnew file mode 100644index 0000000..16b41b9--- /dev/null+++ b/frontend/src/features/settings/ClaudeTokenList.tsx@@ -0,0 +1,76 @@+import React, { useState } from 'react';+import { KeyRound, Trash2 } from 'lucide-react';+import { Badge } from '@/components/ui/badge';+import ConfirmDialog from '@/components/ConfirmDialog';+import RelativeTime from '@/components/RelativeTime';+import RowAction from '@/components/RowAction';+import { EmptyState } from '@/components/StateViews';+import { fmtDateTime } from '@/utils/formatters';+import { isExpired, permissionLabel } from './claudeAccessData';+import type { McpAccessTokenSummary } from '@shared/types/mcp.ts';++export interface ClaudeTokenListProps {+ tokens: McpAccessTokenSummary[];+ revokingId: string | null;+ onRevoke: (token: McpAccessTokenSummary) => Promise<boolean>;+}++function TokenRow({ token, onAskRevoke }: { token: McpAccessTokenSummary; onAskRevoke: () => void }) {+ const expired = isExpired(token);+ return (+ <li className="flex items-start justify-between gap-4 px-4 py-3">+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2">+ <p className="truncate text-sm font-medium text-ink">{token.label}</p>+ <Badge variant={token.permission === 'write' ? 'warning' : 'secondary'}>{permissionLabel(token.permission)}</Badge>+ {expired && <Badge variant="outline">Expired</Badge>}+ </div>+ <p className="text-caption text-ink-muted">+ <span className="font-mono">twl_...{token.hint}</span>+ <span aria-hidden="true"> · </span><span className="sr-only">, </span>+ {token.lastUsedAt ? <RelativeTime date={token.lastUsedAt} prefix="Used " /> : 'Never used'}+ <span aria-hidden="true"> · </span><span className="sr-only">, </span>+ {token.expiresAt ? `${expired ? 'Expired' : 'Expires'} ${fmtDateTime(token.expiresAt)}` : 'Does not expire'}+ </p>+ </div>+ <RowAction label="Revoke" target={token.label} onClick={onAskRevoke} danger>+ <Trash2 />+ </RowAction>+ </li>+ );+}++export default function ClaudeTokenList({ tokens, revokingId, onRevoke }: ClaudeTokenListProps) {+ const [pending, setPending] = useState<McpAccessTokenSummary | null>(null);++ if (tokens.length === 0) {+ return (+ <EmptyState+ compact+ icon={<KeyRound />}+ title="No access tokens yet"+ description="Create one above to connect Claude Code, or any client that sends a token."+ />+ );+ }++ return (+ <>+ <ul className="divide-y divide-divider">+ {tokens.map(token => <TokenRow key={token.id} token={token} onAskRevoke={() => setPending(token)} />)}+ </ul>+ <ConfirmDialog+ open={pending !== null}+ onOpenChange={open => { if (!open) setPending(null); }}+ title={`Revoke ${pending?.label ?? 'this token'}?`}+ description="Every Claude client that uses this token loses access at once. Revoking can't be undone; create a new token to connect again."+ confirmLabel="Revoke token"+ busyLabel="Revoking"+ busy={pending !== null && revokingId === pending.id}+ onConfirm={() => {+ if (pending) void onRevoke(pending).then(done => { if (done) setPending(null); });+ }}+ />+ </>+ );+}diff --git a/frontend/src/features/settings/CopyField.tsx b/frontend/src/features/settings/CopyField.tsxnew file mode 100644index 0000000..6e61a40--- /dev/null+++ b/frontend/src/features/settings/CopyField.tsx@@ -0,0 +1,45 @@+import React, { useState } from 'react';+import { Check, Copy } from 'lucide-react';+import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from '@/components/ui/input-group';++export interface CopyFieldProps {+ id: string;+ // what the value is, for the copy button's name ("Copy access token")+ label: string;+ value: string;+}++// a value too long for CopyChip (a token, a command): the whole text stays selectable, and one button copies it+export default function CopyField({ id, label, value }: CopyFieldProps) {+ const [copied, setCopied] = useState(false);++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(value);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ // without clipboard access the text is still selectable, so select it for a manual copy+ (document.getElementById(id) as HTMLInputElement | null)?.select();+ }+ };++ return (+ <InputGroup>+ <InputGroupInput+ id={id}+ value={value}+ readOnly+ spellCheck={false}+ onFocus={e => e.currentTarget.select()}+ className="font-mono text-sm"+ />+ <InputGroupAddon align="inline-end">+ <InputGroupButton onClick={handleCopy} aria-label={copied ? `${label} copied` : `Copy ${label}`}>+ {copied ? <Check className="text-success" /> : <Copy />}+ {copied ? 'Copied' : 'Copy'}+ </InputGroupButton>+ </InputGroupAddon>+ </InputGroup>+ );+}diff --git a/frontend/src/features/settings/Settings.tsx b/frontend/src/features/settings/Settings.tsxindex 4e4ea1b..8378278 100644--- a/frontend/src/features/settings/Settings.tsx+++ b/frontend/src/features/settings/Settings.tsx@@ -8,6 +8,7 @@ import SettingsSection from './SettingsSection';import AppearanceSection from './AppearanceSection';import PasswordSection from './PasswordSection';import ServerKeysSection from './ServerKeysSection';+import ClaudeSection from './ClaudeSection';import SchedulingSection from './SchedulingSection';import PlatformRequirementsSection from './PlatformRequirementsSection';import UsefulLinksSection from './UsefulLinksSection';@@ -41,6 +42,7 @@ export default function Settings() {<AppearanceSection /><PasswordSection /><ServerKeysSection serverStatus={serverStatus} refreshAll={refreshAll} refreshingAll={refreshingAll} />+ <ClaudeSection /><SchedulingSection github={github} /><PlatformRequirementsSection /><UsefulLinksSection />diff --git a/frontend/src/features/settings/claudeAccessData.ts b/frontend/src/features/settings/claudeAccessData.tsnew file mode 100644index 0000000..2c77cd1--- /dev/null+++ b/frontend/src/features/settings/claudeAccessData.ts@@ -0,0 +1,68 @@+import type {+ McpAccessTokenListResponse, McpAccessTokenSummary, McpClientGrantListResponse, McpClientGrantSummary, McpPermission,+ McpServerInfoResponse,+} from '@shared/types/mcp.ts';++export const TOKEN_LABEL_MAX_LENGTH = 80;++export const PERMISSION_OPTIONS: { value: McpPermission; label: string }[] = [+ { value: 'read', label: 'Read only' },+ { value: 'write', label: 'Read and make changes' },+];++export type ExpiryChoice = '30' | '90' | '365' | 'never';++// a token that never expires is allowed, but the default makes a forgotten one stop on its own+export const DEFAULT_EXPIRY: ExpiryChoice = '90';++export const EXPIRY_OPTIONS: { value: ExpiryChoice; label: string }[] = [+ { value: '30', label: 'In 30 days' },+ { value: '90', label: 'In 90 days' },+ { value: '365', label: 'In a year' },+ { value: 'never', label: 'Never' },+];++// what Claude Code needs until a token exists; the placeholder shows where the token goes+export const TOKEN_PLACEHOLDER = 'twl_your_token';++export interface ClaudeAccess {+ serverUrl: string;+ oauthEnabled: boolean;+ tokens: McpAccessTokenSummary[];+ clients: McpClientGrantSummary[];+}++export interface ClaudeAccessClient {+ getMcpInfo: () => Promise<McpServerInfoResponse>;+ getMcpTokens: () => Promise<McpAccessTokenListResponse>;+ getMcpClients: () => Promise<McpClientGrantListResponse>;+}++export function permissionLabel(permission: McpPermission): string {+ return permission === 'write' ? 'Read and make changes' : 'Read only';+}++export function expiryDays(choice: ExpiryChoice): number | null {+ return choice === 'never' ? null : Number(choice);+}++export function tokenLabelError(label: string): string | null {+ const name = label.trim();+ if (!name) return 'Give the token a name, such as the computer it is for.';+ if (name.length > TOKEN_LABEL_MAX_LENGTH) return `Keep the name to ${TOKEN_LABEL_MAX_LENGTH} characters or fewer.`;+ return null;+}++export function claudeCodeCommand(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {+ return `claude mcp add --transport http twiligent ${serverUrl} --header "Authorization: Bearer ${token}"`;+}++export function isExpired(token: Pick<McpAccessTokenSummary, 'expiresAt'>, now: number = Date.now()): boolean {+ return token.expiresAt !== null && new Date(token.expiresAt).getTime() <= now;+}++// the three reads share one loading and one error state, so the section shows all of it or says it could not load+export async function loadClaudeAccess(client: ClaudeAccessClient): Promise<ClaudeAccess> {+ const [info, tokens, clients] = await Promise.all([client.getMcpInfo(), client.getMcpTokens(), client.getMcpClients()]);+ return { serverUrl: info.serverUrl, oauthEnabled: info.oauthEnabled, tokens: tokens.tokens, clients: clients.clients };+}diff --git a/frontend/src/features/settings/useClaudeAccess.ts b/frontend/src/features/settings/useClaudeAccess.tsnew file mode 100644index 0000000..d7e80ff--- /dev/null+++ b/frontend/src/features/settings/useClaudeAccess.ts@@ -0,0 +1,93 @@+import { useCallback, useEffect, useState } from 'react';+import { api } from '../../services/api';+import { loadClaudeAccess } from './claudeAccessData';+import type { ClaudeAccess } from './claudeAccessData';+import type { AppContextValue } from '../../context/AppContext';+import type { McpAccessTokenCreateRequest, McpAccessTokenSummary } from '@shared/types/mcp.ts';++type ShowToast = AppContextValue['showToast'];++export interface CreatedToken {+ token: string;+ summary: McpAccessTokenSummary;+}++export function useClaudeAccess(showToast: ShowToast) {+ const [access, setAccess] = useState<ClaudeAccess | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);+ // the new token lives only in memory and only until the person dismisses it+ const [created, setCreated] = useState<CreatedToken | null>(null);+ const [creating, setCreating] = useState(false);+ const [revokingId, setRevokingId] = useState<string | null>(null);++ const load = useCallback(async () => {+ setLoading(true);+ setError(null);+ try {+ setAccess(await loadClaudeAccess(api));+ } catch (err) {+ setError((err as Error).message);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => { void load(); }, [load]);++ const createToken = async (input: McpAccessTokenCreateRequest): Promise<boolean> => {+ if (creating) return false;+ setCreating(true);+ try {+ const { token, summary } = await api.createMcpToken(input);+ setCreated({ token, summary });+ setAccess(current => current && { ...current, tokens: [summary, ...current.tokens] });+ showToast('Access token created. Copy it now, it is shown only once.');+ return true;+ } catch (err) {+ showToast(`Couldn't create the access token. ${(err as Error).message}`, 'error');+ return false;+ } finally {+ setCreating(false);+ }+ };++ const revokeToken = async (token: McpAccessTokenSummary): Promise<boolean> => {+ setRevokingId(token.id);+ try {+ await api.revokeMcpToken(token.id);+ setAccess(current => current && { ...current, tokens: current.tokens.filter(item => item.id !== token.id) });+ if (created?.summary.id === token.id) setCreated(null);+ showToast(`Access token ${token.label} revoked`);+ return true;+ } catch (err) {+ showToast(`Couldn't revoke the access token. ${(err as Error).message}`, 'error');+ return false;+ } finally {+ setRevokingId(null);+ }+ };++ const revokeClient = async (id: string, name: string): Promise<boolean> => {+ setRevokingId(id);+ try {+ await api.revokeMcpClient(id);+ setAccess(current => current && { ...current, clients: current.clients.filter(item => item.id !== id) });+ showToast(`${name} removed`);+ return true;+ } catch (err) {+ showToast(`Couldn't remove ${name}. ${(err as Error).message}`, 'error');+ return false;+ } finally {+ setRevokingId(null);+ }+ };++ return {+ access, error, loading, reload: load,+ created, dismissCreated: () => setCreated(null),+ creating, createToken, revokingId, revokeToken, revokeClient,+ };+}++export type ClaudeAccessState = ReturnType<typeof useClaudeAccess>;diff --git a/frontend/tests/features/settings/claudeAccessData.test.ts b/frontend/tests/features/settings/claudeAccessData.test.tsnew file mode 100644index 0000000..44e8c21--- /dev/null+++ b/frontend/tests/features/settings/claudeAccessData.test.ts@@ -0,0 +1,78 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ claudeCodeCommand, expiryDays, isExpired, loadClaudeAccess, permissionLabel, tokenLabelError, TOKEN_LABEL_MAX_LENGTH,+} from '../../../src/features/settings/claudeAccessData.ts';+import type { ClaudeAccessClient } from '../../../src/features/settings/claudeAccessData.ts';+import type { McpAccessTokenSummary, McpClientGrantSummary } from '../../../../shared/types/mcp.ts';++const TOKEN: McpAccessTokenSummary = {+ id: 't1', label: 'Laptop', hint: 'abcd', permission: 'read', lastUsedAt: null, expiresAt: null, createdAt: '2026-11-01T00:00:00.000Z',+};+const CLIENT: McpClientGrantSummary = {+ id: 'g1', clientId: 'c1', clientName: 'Claude', permission: 'write', lastUsedAt: null, createdAt: '2026-11-01T00:00:00.000Z',+};++function fakeClient(failing?: keyof ClaudeAccessClient): ClaudeAccessClient {+ const fail = (name: keyof ClaudeAccessClient) => {+ if (failing === name) throw new Error('Server error');+ };+ return {+ getMcpInfo: async () => {+ fail('getMcpInfo');+ return { success: true, serverUrl: 'https://api.example.com/mcp', oauthEnabled: false };+ },+ getMcpTokens: async () => {+ fail('getMcpTokens');+ return { success: true, tokens: [TOKEN] };+ },+ getMcpClients: async () => {+ fail('getMcpClients');+ return { success: true, clients: [CLIENT] };+ },+ };+}++test('loading Claude access combines the server address, tokens and approved apps', async () => {+ const access = await loadClaudeAccess(fakeClient());+ assert.deepEqual(access, { serverUrl: 'https://api.example.com/mcp', oauthEnabled: false, tokens: [TOKEN], clients: [CLIENT] });+});++test('loading Claude access fails as a whole when any part fails', async () => {+ await assert.rejects(loadClaudeAccess(fakeClient('getMcpClients')), /Server error/);+});++test('the Claude Code command carries the server address and the token', () => {+ assert.equal(+ claudeCodeCommand('https://api.example.com/mcp', 'twl_abc'),+ 'claude mcp add --transport http twiligent https://api.example.com/mcp --header "Authorization: Bearer twl_abc"',+ );+});++test('the Claude Code command shows a placeholder until a token exists', () => {+ assert.match(claudeCodeCommand('https://api.example.com/mcp'), /Bearer twl_your_token"$/);+});++test('a token name must be present and short enough', () => {+ assert.match(tokenLabelError(' ') ?? '', /Give the token a name/);+ assert.match(tokenLabelError('x'.repeat(TOKEN_LABEL_MAX_LENGTH + 1)) ?? '', /80 characters/);+ assert.equal(tokenLabelError(' Work laptop '), null);+});++test('expiry choices become days, and never becomes no expiry', () => {+ assert.equal(expiryDays('30'), 30);+ assert.equal(expiryDays('365'), 365);+ assert.equal(expiryDays('never'), null);+});++test('a token is expired once its expiry time has passed', () => {+ const now = Date.parse('2026-11-05T12:00:00.000Z');+ assert.equal(isExpired({ expiresAt: null }, now), false);+ assert.equal(isExpired({ expiresAt: '2026-11-05T11:59:59.000Z' }, now), true);+ assert.equal(isExpired({ expiresAt: '2026-11-06T00:00:00.000Z' }, now), false);+});++test('permissions read in plain words', () => {+ assert.equal(permissionLabel('read'), 'Read only');+ assert.equal(permissionLabel('write'), 'Read and make changes');+});