File size: 1,481 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useQuery } from '@tanstack/react-query';
import { getJson } from '../api/client';

/** A personal access token for AI assistants (MCP). The token itself is only ever in the create answer, shown once. */
export interface AccessToken {
  id: number;
  name: string;
  /** "read" or "read,act" */
  scopes: string;
  last4: string;
  created_at: string;
  last_used_at: string | null;
  expires_at: string;
  revoked_at: string | null;
}
export interface CreatedToken { id: number; token: string; expires_at: string }

export const TOKENS_KEY = ['access-tokens'] as const;
export const useAccessTokens = () =>
  useQuery({ queryKey: TOKENS_KEY, queryFn: () => getJson<{ items: AccessToken[] }>('/api/tokens'), retry: false });

export const canAct = (t: Pick<AccessToken, 'scopes'>) => t.scopes.split(',').map((s) => s.trim()).includes('act');
export const scopeWords = (t: Pick<AccessToken, 'scopes'>) =>
  canAct(t) ? 'Read and start runs or approve (you confirm each)' : 'Read only';
export const isActive = (t: AccessToken, now = Date.now()) => !t.revoked_at && new Date(t.expires_at).getTime() > now;

const DAY = 24 * 3600 * 1000;
/** An assistant counts as connected when one of your active tokens was used in the last 30 days. */
export const recentlyUsed = (items: AccessToken[] | undefined, now = Date.now()) =>
  (items ?? []).some((t) => isActive(t, now) && !!t.last_used_at && now - new Date(t.last_used_at).getTime() <= 30 * DAY);