feat(client): show the TREK services allowance on the TREK API card

A calm panel under the card's facts: a dot with the state, the tier, a bar of today's use against the limit, what is left and the local time the count starts again. It reads when the card comes into view and every 30 seconds while it stays there and the tab is in front, says why when the services are off, revoked or cannot be read, and offers a new identity behind a confirmation unless the key comes from the environment.
This commit is contained in:
Maurice
2026-10-29 08:59:13 +01:00
committed by Maurice
parent 01ae91c939
commit baf69da27f
11 changed files with 570 additions and 2 deletions
+8
View File
@@ -0,0 +1,8 @@
import apiClient from './client';
/** /api/admin/service-identity: how this installation stands with the TREK services. Admin only. */
export const serviceIdentityApi = {
status: (signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/service-identity', { signal }).then((r) => r.data),
regenerate: (): Promise<unknown> => apiClient.post('/admin/service-identity/regenerate').then((r) => r.data),
};
@@ -0,0 +1,106 @@
// FE-ADMIN-SVCID-001 to FE-ADMIN-SVCID-007
import userEvent from '@testing-library/user-event';
import type { ServiceIdentityStatus } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import ServiceIdentityPanel from './ServiceIdentityPanel';
// The keys themselves, so a test fails on a missing or renamed key rather than on wording.
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const CONNECTED: ServiceIdentityStatus = {
state: 'connected',
tier: 'std',
keySource: 'registered',
quota: { limit: 10_000, used: 2_500, remaining: 7_500, resetAt: '2026-10-30T00:00:00.000Z' },
lastSeenAt: '2026-10-29T12:00:00.000Z',
};
function serve(status: ServiceIdentityStatus) {
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(status)));
}
describe('ServiceIdentityPanel', () => {
it('FE-ADMIN-SVCID-001: shows the state, the tier and today against the limit', async () => {
serve(CONNECTED);
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.state.connected')).toBeInTheDocument();
expect(screen.getByText('admin.trekApi.quota.tier.std')).toBeInTheDocument();
const bar = screen.getByRole('progressbar', { name: 'admin.trekApi.quota.title' });
expect(bar).toHaveAttribute('aria-valuenow', '2500');
expect(bar).toHaveAttribute('aria-valuemax', '10000');
expect(screen.getByText('2,500 / 10,000')).toBeInTheDocument();
expect(screen.getByText('7,500')).toBeInTheDocument();
expect(screen.getByText('admin.trekApi.quota.resets')).toBeInTheDocument();
expect(screen.queryByText(/admin\.trekApi\.quota\.hint\./)).toBeNull();
});
it('FE-ADMIN-SVCID-002: an installation without a key says so and offers a new identity', async () => {
serve({ state: 'legacy', tier: 'legacy', keySource: null, quota: null, lastSeenAt: null });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.legacy')).toBeInTheDocument();
expect(screen.queryByRole('progressbar')).toBeNull();
expect(screen.getByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-003: switched off, it shows why and offers nothing', async () => {
serve({ state: 'off', tier: null, keySource: null, quota: null, lastSeenAt: null });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.off')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeNull();
});
it('FE-ADMIN-SVCID-004: a key from the environment is named, and only changed there', async () => {
serve({ ...CONNECTED, keySource: 'env', tier: 'own' });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.envKey')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeNull();
});
it('FE-ADMIN-SVCID-005: a connected key without an allowance to show says it cannot be read', async () => {
serve({ ...CONNECTED, quota: null });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.unavailable')).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-006: a failed read says so instead of showing nothing', async () => {
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.unavailable')).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-007: a revoked key asks before it starts over, then shows the new state', async () => {
let regenerated = 0;
serve({ state: 'revoked', tier: 'std', keySource: 'registered', quota: null, lastSeenAt: null });
server.use(
http.post('/api/admin/service-identity/regenerate', () => {
regenerated += 1;
return HttpResponse.json({
state: 'registering',
tier: 'legacy',
keySource: null,
quota: null,
lastSeenAt: null,
});
})
);
const user = userEvent.setup();
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.revoked')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'admin.trekApi.quota.regenerate' }));
expect(screen.getByText('admin.trekApi.quota.regenerateBody')).toBeInTheDocument();
expect(regenerated).toBe(0);
const confirm = screen.getAllByRole('button', { name: 'admin.trekApi.quota.regenerate' }).at(-1);
if (!confirm) throw new Error('no confirm button');
await user.click(confirm);
await waitFor(() => expect(regenerated).toBe(1));
expect(await screen.findByText('admin.trekApi.quota.hint.registering')).toBeInTheDocument();
});
});
@@ -0,0 +1,157 @@
import type { ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
import { RefreshCw } from 'lucide-react';
import { useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { formatClockTime } from '../../utils/formatters';
import ConfirmDialog from '../shared/ConfirmDialog';
import { useToast } from '../shared/Toast';
import { useServiceIdentity } from './useServiceIdentity';
const STATE_DOT: Record<ServiceIdentityState, string> = {
connected: 'bg-success',
registering: 'bg-warning motion-safe:animate-pulse',
legacy: 'bg-[var(--text-faint)]',
off: 'bg-[var(--text-faint)]',
revoked: 'bg-danger',
};
/** Below a tenth of the day left the bar turns amber, at nothing left red. */
function barTone(quota: ServiceQuotaView): string {
if (quota.remaining === 0) return 'bg-danger';
return quota.remaining < quota.limit / 10 ? 'bg-warning' : 'bg-accent';
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<div className="min-w-0">
<dt className="text-caption text-content-muted">{label}</dt>
<dd className="m-0 truncate text-body font-medium tabular-nums text-content">{value}</dd>
</div>
);
}
function QuotaMeter({ quota }: { quota: ServiceQuotaView }) {
const { t, locale } = useTranslation();
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
const number = new Intl.NumberFormat(locale);
const share = quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
const reset = new Date(quota.resetAt);
const resetAt = formatClockTime(
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
is12h
);
return (
<div className="flex flex-col gap-2.5">
<div
role="progressbar"
aria-label={t('admin.trekApi.quota.title')}
aria-valuemin={0}
aria-valuemax={quota.limit}
aria-valuenow={quota.used}
className="h-1.5 overflow-hidden rounded-full bg-surface-tertiary"
>
<div
className={`h-full rounded-full transition-[width] duration-500 ${barTone(quota)}`}
style={{ width: `${share}%` }}
/>
</div>
<dl className="m-0 grid grid-cols-3 gap-3">
<Stat
label={t('admin.trekApi.quota.used')}
value={`${number.format(quota.used)} / ${number.format(quota.limit)}`}
/>
<Stat label={t('admin.trekApi.quota.remaining')} value={number.format(quota.remaining)} />
<Stat label={t('admin.trekApi.quota.resets')} value={resetAt} />
</dl>
</div>
);
}
function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
if (status.state !== 'connected') return t(`admin.trekApi.quota.hint.${status.state}`);
return status.quota ? null : t('admin.trekApi.quota.unavailable');
}
/**
* How this installation stands with the TREK services: whether it has its key,
* today's allowance against what is used, and when the count starts again.
* Read when the card is in view and refreshed every 30 seconds while it stays.
*/
export default function ServiceIdentityPanel() {
const { t } = useTranslation();
const toast = useToast();
const panel = useRef<HTMLElement>(null);
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
const [confirming, setConfirming] = useState(false);
const confirmRegenerate = async () => {
setConfirming(false);
try {
await regenerate();
toast.success(t('admin.trekApi.quota.regenerated'));
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
}
};
const hint = stateHint(t, status, failed);
const canRegenerate = status !== null && status.keySource !== 'env' && status.state !== 'off';
return (
<section
ref={panel}
aria-label={t('admin.trekApi.quota.title')}
className="flex flex-col gap-3 rounded-xl border border-edge-faint bg-surface-secondary px-3.5 py-3"
>
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="m-0 flex items-center gap-2 text-body font-medium text-content">
<span aria-hidden="true" className={`h-2 w-2 flex-none rounded-full ${STATE_DOT[status?.state ?? 'off']}`} />
{status ? t(`admin.trekApi.quota.state.${status.state}`) : t('admin.trekApi.quota.title')}
</p>
{status?.tier && (
<span className="rounded-full border border-edge-faint bg-surface-card px-2 py-0.5 text-caption font-medium text-content-secondary">
{t(`admin.trekApi.quota.tier.${status.tier}`)}
</span>
)}
</div>
{status?.quota && status.state !== 'off' && <QuotaMeter quota={status.quota} />}
{hint && <p className="m-0 text-caption leading-snug text-content-muted">{hint}</p>}
{status?.keySource === 'env' && (
<p className="m-0 text-caption text-content-faint">{t('admin.trekApi.quota.envKey')}</p>
)}
{canRegenerate && (
<button
type="button"
onClick={() => setConfirming(true)}
disabled={regenerating}
className="inline-flex items-center gap-1.5 self-start rounded-lg text-caption font-medium text-content-secondary hover:text-content disabled:opacity-50"
>
<RefreshCw
size={13}
strokeWidth={2}
className={regenerating ? 'motion-safe:animate-spin' : ''}
aria-hidden="true"
/>
{t('admin.trekApi.quota.regenerate')}
</button>
)}
<ConfirmDialog
isOpen={confirming}
onClose={() => setConfirming(false)}
onConfirm={() => void confirmRegenerate()}
title={t('admin.trekApi.quota.regenerateTitle')}
message={t('admin.trekApi.quota.regenerateBody')}
confirmLabel={t('admin.trekApi.quota.regenerate')}
danger={false}
/>
</section>
);
}
@@ -0,0 +1,91 @@
// FE-ADMIN-SVCID-HOOK-001 to FE-ADMIN-SVCID-HOOK-004
import { act, renderHook } from '@testing-library/react';
import type { ServiceIdentityStatus } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useServiceIdentity } from './useServiceIdentity';
const { status, regenerate, visible } = vi.hoisted(() => ({
status: vi.fn(),
regenerate: vi.fn(),
visible: { current: true },
}));
vi.mock('../../repo/serviceIdentityRepo', () => ({ serviceIdentityRepo: { status, regenerate } }));
vi.mock('../../hooks/useElementVisible', () => ({ useElementVisible: () => visible.current }));
const LEGACY: ServiceIdentityStatus = {
state: 'legacy',
tier: 'legacy',
keySource: null,
quota: null,
lastSeenAt: null,
};
const card = { current: null };
beforeEach(() => {
vi.useFakeTimers();
visible.current = true;
status.mockReset().mockResolvedValue(LEGACY);
regenerate.mockReset();
});
afterEach(() => vi.useRealTimers());
describe('useServiceIdentity', () => {
it('FE-ADMIN-SVCID-HOOK-001: reads once in view, then every 30 seconds', async () => {
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {});
expect(result.current.status).toEqual(LEGACY);
expect(status).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000);
});
expect(status).toHaveBeenCalledTimes(2);
});
it('FE-ADMIN-SVCID-HOOK-002: reads nothing while the card is out of view, and stops when it leaves', async () => {
visible.current = false;
const { rerender } = renderHook(() => useServiceIdentity(card));
await act(async () => {
await vi.advanceTimersByTimeAsync(90_000);
});
expect(status).not.toHaveBeenCalled();
visible.current = true;
rerender();
await act(async () => {});
expect(status).toHaveBeenCalledTimes(1);
visible.current = false;
rerender();
await act(async () => {
await vi.advanceTimersByTimeAsync(90_000);
});
expect(status).toHaveBeenCalledTimes(1);
});
it('FE-ADMIN-SVCID-HOOK-003: marks a failed read, and clears the mark on the next good one', async () => {
status.mockRejectedValueOnce(new Error('offline'));
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {});
expect(result.current.failed).toBe(true);
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000);
});
expect(result.current.failed).toBe(false);
});
it('FE-ADMIN-SVCID-HOOK-004: a new identity replaces the status, and a refusal reaches the caller', async () => {
const registering = { ...LEGACY, state: 'registering' as const };
regenerate.mockResolvedValueOnce(registering).mockRejectedValueOnce(new Error('409'));
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {
await result.current.regenerate();
});
expect(result.current.status).toEqual(registering);
await act(async () => {
await expect(result.current.regenerate()).rejects.toThrow('409');
});
expect(result.current.regenerating).toBe(false);
});
});
@@ -0,0 +1,51 @@
import type { ServiceIdentityStatus } from '@trek/shared';
import { useCallback, useEffect, useState, type RefObject } from 'react';
import { useElementVisible } from '../../hooks/useElementVisible';
import { serviceIdentityRepo } from '../../repo/serviceIdentityRepo';
const REFRESH_MS = 30_000;
/**
* The installation's standing with the TREK services for the admin card:
* read when the card comes into view, then every 30 seconds while it stays
* there. Admin configuration, online only like the rest of the settings tab.
*/
export function useServiceIdentity(card: RefObject<Element | null>) {
const visible = useElementVisible(card);
const [status, setStatus] = useState<ServiceIdentityStatus | null>(null);
const [failed, setFailed] = useState(false);
const [regenerating, setRegenerating] = useState(false);
useEffect(() => {
if (!visible) return;
const controller = new AbortController();
const refresh = () => {
serviceIdentityRepo.status(controller.signal).then(
(next) => {
setStatus(next);
setFailed(false);
},
() => {
if (!controller.signal.aborted) setFailed(true);
}
);
};
refresh();
const timer = setInterval(refresh, REFRESH_MS);
return () => {
controller.abort();
clearInterval(timer);
};
}, [visible]);
const regenerate = useCallback(async (): Promise<void> => {
setRegenerating(true);
try {
setStatus(await serviceIdentityRepo.regenerate());
} finally {
setRegenerating(false);
}
}, []);
return { status, failed, regenerating, regenerate };
}
@@ -0,0 +1,58 @@
// FE-HOOK-VISIBLE-001 to FE-HOOK-VISIBLE-003
import { act, renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useElementVisible } from './useElementVisible';
let report: ((entries: Array<{ isIntersecting: boolean }>) => void) | null = null;
const disconnect = vi.fn();
class FakeIntersectionObserver {
constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) {
report = callback;
}
observe() {}
disconnect() {
disconnect();
}
}
function setVisibility(state: 'visible' | 'hidden') {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state });
document.dispatchEvent(new Event('visibilitychange'));
}
afterEach(() => {
vi.unstubAllGlobals();
setVisibility('visible');
report = null;
});
describe('useElementVisible', () => {
it('FE-HOOK-VISIBLE-001: follows the element in and out of view', () => {
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
const target = { current: document.createElement('div') };
const { result, unmount } = renderHook(() => useElementVisible(target));
act(() => report?.([{ isIntersecting: false }]));
expect(result.current).toBe(false);
act(() => report?.([{ isIntersecting: true }]));
expect(result.current).toBe(true);
unmount();
expect(disconnect).toHaveBeenCalled();
});
it('FE-HOOK-VISIBLE-002: counts as hidden while the tab is in the background', () => {
const target = { current: document.createElement('div') };
const { result } = renderHook(() => useElementVisible(target));
expect(result.current).toBe(true);
act(() => setVisibility('hidden'));
expect(result.current).toBe(false);
act(() => setVisibility('visible'));
expect(result.current).toBe(true);
});
it('FE-HOOK-VISIBLE-003: without IntersectionObserver the element counts as on screen', () => {
vi.stubGlobal('IntersectionObserver', undefined);
const { result } = renderHook(() => useElementVisible({ current: document.createElement('div') }));
expect(result.current).toBe(true);
});
});
+27
View File
@@ -0,0 +1,27 @@
import { useEffect, useState, type RefObject } from 'react';
/**
* Whether an element is on screen and its tab in front. Without
* IntersectionObserver (an old browser, a test) the element counts as on
* screen, so whatever depends on it still runs.
*/
export function useElementVisible(target: RefObject<Element | null>): boolean {
const [onScreen, setOnScreen] = useState(true);
const [tabShown, setTabShown] = useState(() => document.visibilityState !== 'hidden');
useEffect(() => {
const element = target.current;
if (!element || typeof IntersectionObserver === 'undefined') return;
const observer = new IntersectionObserver(([entry]) => setOnScreen(entry?.isIntersecting ?? false));
observer.observe(element);
return () => observer.disconnect();
}, [target]);
useEffect(() => {
const onChange = () => setTabShown(document.visibilityState !== 'hidden');
document.addEventListener('visibilitychange', onChange);
return () => document.removeEventListener('visibilitychange', onChange);
}, []);
return onScreen && tabShown;
}
+6 -2
View File
@@ -4,6 +4,7 @@ import TrekMark from '../../components/shared/TrekMark'
import { fs } from '../../components/shared/DialogShell'
import { StatusPill } from '../../components/Settings/settingsKit'
import FoldSummary from './FoldSummary'
import ServiceIdentityPanel from '../../components/Admin/ServiceIdentityPanel'
import type { TranslationFn } from '../../types'
import { TREK_API_SOURCES as SOURCES, trekApiFacts, trekApiFields } from '../../components/Admin/trekApiModel'
@@ -20,8 +21,9 @@ interface TrekApiCardProps {
* to do and what made it shout over the settings it sat next to.
*
* Everything a reader can check is a measured number, not a claim: 73.6 million
* is the row count of the current index, and "no queries logged" is enforced in
* three places on the server rather than promised here.
* is the row count of the current index, "no queries logged" is enforced in
* three places on the server rather than promised here, and the allowance below
* the facts is what the service itself reports for this installation.
*/
const CHIP = 'rounded-full border px-2.5 py-[3px] font-medium'
@@ -70,6 +72,8 @@ export default function TrekApiCard({ t }: TrekApiCardProps): React.ReactElement
</li>
))}
</ul>
<ServiceIdentityPanel />
</div>
<details className="group border-t border-edge-faint">
@@ -0,0 +1,41 @@
// FE-SVCID-REPO-001 to FE-SVCID-REPO-003
import type { ServiceIdentityStatus } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { _resetNetworkMode, setForcedOffline } from '../sync/networkMode';
import { OnlineOnlyError } from './onlineOnly';
import { serviceIdentityRepo } from './serviceIdentityRepo';
const STATUS: ServiceIdentityStatus = {
state: 'connected',
tier: 'std',
keySource: 'registered',
quota: { limit: 10_000, used: 1, remaining: 9_999, resetAt: '2026-10-30T00:00:00.000Z' },
lastSeenAt: null,
};
beforeEach(() => _resetNetworkMode());
afterEach(() => _resetNetworkMode());
describe('serviceIdentityRepo', () => {
it('FE-SVCID-REPO-001: reads and parses the status', async () => {
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(STATUS)));
await expect(serviceIdentityRepo.status()).resolves.toEqual(STATUS);
});
it('FE-SVCID-REPO-002: asks for a new identity and refuses an answer of another shape', async () => {
server.use(
http.post('/api/admin/service-identity/regenerate', () => HttpResponse.json({ ...STATUS, state: 'registering' }))
);
await expect(serviceIdentityRepo.regenerate()).resolves.toMatchObject({ state: 'registering' });
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json({ state: 'gold' })));
await expect(serviceIdentityRepo.status()).rejects.toThrow();
});
it('FE-SVCID-REPO-003: asks nothing while offline', async () => {
setForcedOffline(true);
await expect(serviceIdentityRepo.status()).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(serviceIdentityRepo.regenerate()).rejects.toBeInstanceOf(OnlineOnlyError);
});
});
+20
View File
@@ -0,0 +1,20 @@
import { serviceIdentityStatusSchema, type ServiceIdentityStatus } from '@trek/shared';
import { serviceIdentityApi } from '../api/serviceIdentity';
import { requireOnline } from './onlineOnly';
/**
* The installation's identity towards the TREK services, as the admin card
* shows it. **Deliberately online-only, and no Dexie table:** it is live
* server state, and a cached copy would show an allowance that is long gone.
*/
export const serviceIdentityRepo = {
async status(signal?: AbortSignal): Promise<ServiceIdentityStatus> {
requireOnline();
return serviceIdentityStatusSchema.parse(await serviceIdentityApi.status(signal));
},
async regenerate(): Promise<ServiceIdentityStatus> {
requireOnline();
return serviceIdentityStatusSchema.parse(await serviceIdentityApi.regenerate());
},
};
@@ -161,4 +161,9 @@ export const adminHandlers = [
http.get('/api/auth/validate-keys', () => {
return HttpResponse.json({ maps: true, weather: true });
}),
// The TREK API card's allowance panel, read whenever the settings tab renders it.
http.get('/api/admin/service-identity', () => {
return HttpResponse.json({ state: 'legacy', tier: 'legacy', keySource: null, quota: null, lastSeenAt: null });
}),
];