perf(i18n,shell): ship one locale and stop blocking the first paint

The client bundle carries only the active locale — resolved on the
server and handed to the provider with no hydration flash, halving the
dashboard route to under a megabyte parsed (288 KiB gzip). The auth
shell renders the app chrome immediately instead of a spinner while the
session resolves in parallel, the widgets request folds into the
snapshot it duplicated, and insight pills prefetch their sub-pages —
a first visit to a sub-page lands in about ninety milliseconds instead
of nearly a second.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 02:19:27 +02:00
1 parent 9445d89b76
commit 3b480b9885
284 files changed
+6058 -5398

No files matched your search

@@ -58,7 +58,7 @@ describe("<AiQualitySection>", () => {
mockQueryState.isError = false;
const html = render(<AiQualitySection />);
// v1.4.33 IW7 — admin section renamed from "AI Quality" to
// "Insights Quality" per the Marc-Voice rule.
// "Insights Quality" per the project-voice rule.
expect(html).toContain("Insights Quality");
expect(html).toContain("No feedback yet");
});
@@ -35,8 +35,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -30,7 +30,7 @@ const sampleTokens = [
expiresAt: null,
createdAt: "2026-05-01T08:00:00Z",
revoked: false,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
@@ -54,8 +54,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -107,7 +107,7 @@ describe("ApiTokenOverviewSection — responsive", () => {
// All data points the desktop table shows must also appear in the
// mobile cards. Token name + username + a permission badge + the
// last-used/created labels are all present.
expect(html).toContain("marc"); // username
expect(html).toContain("testuser"); // username
expect(html).toContain("iOS app"); // token name
// F-19 (v1.4.19): the wildcard `*` permission renders as the
// human-readable "All" with a tooltip explaining the semantics,
@@ -4,7 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.19 A7 — `/admin/api-tokens` 4th-attempt scrollbar fix.
*
* the maintainer reported a "minimaler Scrollbar" still painting at the
* The maintainer reported a "minimaler Scrollbar" still painting at the
* bottom-right of the api-tokens page, even after the v1.4.18 phase
* A2 mobile-strip `no-scrollbar` fix. The remaining culprits are
* inside the section card itself: long token names, long usernames,
@@ -37,7 +37,7 @@ const sampleTokens = [
revoked: false,
user: {
id: "u1",
username: "marc-the-very-long-username-that-overflows",
username: "user-the-very-long-username-that-overflows",
},
},
];
@@ -62,8 +62,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -51,8 +51,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -35,7 +35,7 @@ vi.mock("@tanstack/react-query", () => ({
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "ADMIN" },
user: { id: "u1", username: "testuser", role: "ADMIN" },
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
@@ -108,7 +108,7 @@ describe("CoachFeedbackSection", () => {
expect(html).toContain('role="alert"');
});
// v1.4.25 W8 regression — Marc reported a layout shift on
// v1.4.25 W8 regression — the maintainer reported a layout shift on
// /admin/coach-feedback. Root cause was the title only rendering in the
// empty + data branches, so the section grew taller (loading → data)
// and snapped down. Lock the heading + outer-card structure across
@@ -64,8 +64,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -15,7 +15,7 @@ import { toCSV } from "@/lib/export";
* `createdAt` string, which Excel/LibreOffice misread once the `Z`
* suffix was stripped. This test pins:
*
* - The column order Marc requested:
* - The column order the maintainer requested:
* `timestamp → user → IP → location → provider → outcome` (email
* is absent from the audit-log API so it's intentionally skipped)
* followed by `action` + `details` for triage completeness.
@@ -80,7 +80,7 @@ function deterministicFormatter(iso: string): string {
}
describe("buildAuditLogCsvRecords", () => {
it("emits Marc's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
it("emits the maintainer's column order: timestamp → user → ip → location → provider → outcome (+ action, details)", () => {
const entries: AuditCsvEntry[] = [
{
createdAt: "2026-05-11T09:05:00.000Z",
@@ -88,7 +88,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const [record] = buildAuditLogCsvRecords(
@@ -119,7 +119,7 @@ describe("buildAuditLogCsvRecords", () => {
ipAddress: null,
location: null,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -220,7 +220,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
ipAddress: "203.0.113.7",
location: "Berlin, DE",
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -234,12 +234,12 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
"Zeitpunkt,Benutzer,IP,Standort,Mobilfunkanbieter,Anbieter,Ergebnis,Aktion,Details",
);
expect(lines[1]).toBe(
'2026-05-11T09:05:00+00:00,marc,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
'2026-05-11T09:05:00+00:00,testuser,203.0.113.7,"Berlin, DE",,Passkey,Erfolgreich,auth.login.passkey,',
);
});
it("folds the GeoLite2 organisation string to the short DACH carrier label", () => {
// Marc's spec: the verbose MMDB org strings get a glanceable chip.
// The maintainer's spec: the verbose MMDB org strings get a glanceable chip.
// The CSV column carries the same folded text so a downstream
// spreadsheet matches what the admin overview screen renders.
const entries: AuditCsvEntry[] = [
@@ -251,7 +251,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Deutsche Telekom AG",
asn: 3320,
details: null,
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
},
{
createdAt: "2026-05-11T09:06:00.000Z",
@@ -261,7 +261,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Vodafone GmbH",
asn: 3209,
details: null,
user: { id: "u2", username: "marc" },
user: { id: "u2", username: "testuser" },
},
{
createdAt: "2026-05-11T09:07:00.000Z",
@@ -271,7 +271,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "1&1 Versatel GmbH",
asn: 8881,
details: null,
user: { id: "u3", username: "marc" },
user: { id: "u3", username: "testuser" },
},
{
createdAt: "2026-05-11T09:08:00.000Z",
@@ -281,7 +281,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Telefónica Germany GmbH & Co. OHG",
asn: 6805,
details: null,
user: { id: "u4", username: "marc" },
user: { id: "u4", username: "testuser" },
},
{
createdAt: "2026-05-11T09:09:00.000Z",
@@ -291,7 +291,7 @@ describe("toCSV(records, headerLabels) — audit-log integration", () => {
carrier: "Google LLC",
asn: 15169,
details: null,
user: { id: "u5", username: "marc" },
user: { id: "u5", username: "testuser" },
},
];
const records = buildAuditLogCsvRecords(
@@ -37,8 +37,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
timezone: "Europe/Berlin",
},
@@ -23,7 +23,7 @@ vi.mock("next/navigation", () => ({
const sampleEntries = [
{
id: "ev-1",
user: { id: "u1", username: "marc" },
user: { id: "u1", username: "testuser" },
action: "auth.login.success",
ipAddress: "203.0.113.10",
location: "Berlin, DE",
@@ -55,8 +55,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
timezone: "Europe/Berlin",
},
@@ -55,7 +55,7 @@ describe("providerForAction", () => {
describe("iconForAuthProvider", () => {
it("maps each provider to the documented lucide glyph", () => {
// Marc's brief pinned the exact icon for each provider so the
// The maintainer's brief pinned the exact icon for each provider so the
// visual language stays consistent across the admin surface.
expect(iconForAuthProvider("password")).toBe(KeyRound);
expect(iconForAuthProvider("passkey")).toBe(Fingerprint);
@@ -30,8 +30,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -149,7 +149,7 @@ describe("admin sections — SSR smoke", () => {
it("<AiQualitySection> renders the empty-state when no summary exists", () => {
const html = render(<AiQualitySection />);
// v1.4.33 IW7 — section renamed from "AI Quality" to
// "Insights Quality" per the Marc-Voice rule (no "KI"/"AI" prefix
// "Insights Quality" per the project-voice rule (no "KI"/"AI" prefix
// in user-facing copy).
expect(html).toContain("Insights Quality");
expect(html).toContain("No feedback yet");
@@ -37,8 +37,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -74,8 +74,8 @@ describe("/admin overview composition", () => {
it("renders the welcome card with the admin's username", () => {
const html = render(<AdminOverviewPage />);
// `welcomeTitle` interpolates the username; the mocked auth hook
// returns "marc".
expect(html).toContain("Welcome, marc");
// returns "testuser".
expect(html).toContain("Welcome, testuser");
expect(html).toContain("admin-overview-welcome-heading");
});
@@ -41,8 +41,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
@@ -25,8 +25,8 @@ vi.mock("next/navigation", () => ({
const sampleUsers = [
{
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN" as const,
passkeyCount: 2,
createdAt: "2026-04-01T08:00:00Z",
@@ -57,8 +57,8 @@ vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
username: "testuser",
email: "user@example.com",
role: "ADMIN",
},
isAuthenticated: true,
+6 -18
View File
@@ -8,6 +8,7 @@ import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { PasswordInput as SharedPasswordInput } from "@/components/ui/password-input";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
/**
* Re-export the canonical password input so admin sections have access to
@@ -228,9 +229,7 @@ export function useAdminSettings() {
return useQuery({
queryKey: queryKeys.adminSettings(),
queryFn: async () => {
const res = await fetch("/api/admin/settings");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminSettings;
return apiGet<AdminSettings>("/api/admin/settings");
},
});
}
@@ -240,14 +239,7 @@ export function useUpdateSettings() {
const { t } = useTranslations();
return useMutation({
mutationFn: async (data: Record<string, unknown>) => {
const res = await fetch("/api/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
await apiPut("/api/admin/settings", data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.adminSettings() });
@@ -423,7 +415,7 @@ export function carrierShortLabel(rawAsnOrg: string): string {
*
* Pulled out of the section component so the column order, header
* mapping, and provider/outcome derivation are reachable from a
* pure unit test without rendering the React tree. Marc's spec pins
* pure unit test without rendering the React tree. The maintainer's spec pins
* the column order at `timestamp → user → IP → location → provider
* → outcome` (email is absent from the audit-log API and would
* require schema/API changes that are out of scope). `action` and
@@ -526,9 +518,7 @@ export function useSystemStatus() {
return useQuery({
queryKey: queryKeys.adminStatus(),
queryFn: async () => {
const res = await fetch("/api/admin/status");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as SystemStatus;
return apiGet<SystemStatus>("/api/admin/status");
},
});
}
@@ -554,9 +544,7 @@ export function usePublicVersion() {
return useQuery({
queryKey: queryKeys.publicVersion(),
queryFn: async () => {
const res = await fetch("/api/version");
if (!res.ok) throw new Error("Failed to load version");
return (await res.json()).data as PublicVersion;
return apiGet<PublicVersion>("/api/version");
},
staleTime: 5 * 60_000,
});
+5 -9
View File
@@ -23,6 +23,7 @@ import { useQuery } from "@tanstack/react-query";
import { Sparkles, Loader2 } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { helpfulRateColour } from "./_shared";
interface FeedbackBucket {
@@ -42,11 +43,6 @@ interface FeedbackSummary {
buckets: FeedbackBucket[];
}
interface AiQualityResponse {
data: { summary: FeedbackSummary | null } | null;
error?: string | null;
}
const SEVERITY_TINT: Record<string, string> = {
info: "text-dracula-cyan",
suggestion: "text-dracula-purple",
@@ -61,10 +57,10 @@ export function AiQualitySection() {
const query = useQuery({
queryKey: queryKeys.adminAiQuality(),
queryFn: async () => {
const res = await fetch("/api/admin/ai-quality");
const json = (await res.json()) as AiQualityResponse;
if (!res.ok) throw new Error(json.error ?? "ai_quality_failed");
return json.data?.summary ?? null;
const data = await apiGet<{ summary: FeedbackSummary | null } | null>(
"/api/admin/ai-quality",
);
return data?.summary ?? null;
},
});
@@ -14,6 +14,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type ApiTokenInfo } from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
/**
* Wraps a string in `truncate` + tooltip so a long token name /
@@ -21,7 +22,7 @@ import { type ApiTokenInfo } from "./_shared";
*
* v1.4.19 phase A7 (4th attempt) — earlier fixes (column-hide,
* mobile card-list, mobile-strip `no-scrollbar`) cleared every
* scrollbar the maintainer reported except a residual painted bar he kept
* scrollbar the maintainer reported except a residual painted bar they kept
* seeing at the bottom-right. Production probe confirmed no
* remaining horizontal-overflow culprits, but the cards still
* carried `break-all` next to `truncate` (dead code; `white-space:
@@ -150,9 +151,7 @@ export function ApiTokenOverviewSection() {
const { data: tokens, isLoading } = useQuery({
queryKey: queryKeys.adminTokens(),
queryFn: async () => {
const res = await fetch("/api/admin/tokens");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as ApiTokenInfo[];
return apiGet<ApiTokenInfo[]>("/api/admin/tokens");
},
});
@@ -49,6 +49,7 @@ import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { WideEvent, LogLevel } from "@/lib/logging/types";
import { apiGet } from "@/lib/api/api-fetch";
type RangePreset = "15m" | "1h" | "6h" | "all";
@@ -103,9 +104,7 @@ export function AppLogPreviewSection() {
const { data, isLoading, refetch, isFetching } = useQuery({
queryKey: queryKeys.adminAppLogs(traceId, actionFilter, level, range),
queryFn: async () => {
const res = await fetch(`/api/admin/app-logs?${params.toString()}`);
if (!res.ok) throw new Error("Failed to load app logs");
return (await res.json()).data as AppLogsResponse;
return apiGet<AppLogsResponse>(`/api/admin/app-logs?${params.toString()}`);
},
refetchInterval: 30_000,
});
+4 -13
View File
@@ -6,7 +6,8 @@ import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { SettingsToggle, getApiErrorMessage } from "./_shared";
import { SettingsToggle } from "./_shared";
import { apiGet, apiPut } from "@/lib/api/api-fetch";
/**
* v1.4.31 — operator-side panel for the six assistant feature
@@ -48,9 +49,7 @@ function useAssistantFlags() {
return useQuery({
queryKey: queryKeys.adminAssistantFlags(),
queryFn: async () => {
const res = await fetch("/api/admin/settings/assistant-flags");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AssistantFlagsResponse;
return apiGet<AssistantFlagsResponse>("/api/admin/settings/assistant-flags");
},
});
}
@@ -62,15 +61,7 @@ function useUpdateAssistantFlags() {
mutationFn: async (
patch: Partial<AssistantFlagsResponse["raw"]>,
): Promise<AssistantFlagsResponse> => {
const res = await fetch("/api/admin/settings/assistant-flags", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as AssistantFlagsResponse;
return apiPut<AssistantFlagsResponse>("/api/admin/settings/assistant-flags", patch);
},
onSuccess: (data) => {
client.setQueryData(
+15 -30
View File
@@ -44,6 +44,7 @@ import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import type { BackupRow, BackupsList } from "@/types/backups";
import { getApiErrorMessage } from "./_shared";
import { apiFetch, apiFetchRaw, apiGet, apiPost } from "@/lib/api/api-fetch";
/**
* Typed-confirmation dialog for restore. The destructive Restore button
@@ -175,19 +176,13 @@ export function BackupsSection() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminBackups(),
queryFn: async () => {
const res = await fetch("/api/admin/backups");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as BackupsList;
return apiGet<BackupsList>("/api/admin/backups");
},
});
const runBackup = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/backups/run", { method: "POST" });
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as { jobId: string | null };
return apiPost<{ jobId: string | null }>("/api/admin/backups/run");
},
onSuccess: () => {
toast.success(t("admin.section.backups.runEnqueued"));
@@ -219,14 +214,9 @@ export function BackupsSection() {
mutationFn: async (file: File) => {
const fd = new FormData();
fd.append("file", file);
const res = await fetch("/api/admin/backups/upload", {
method: "POST",
body: fd,
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as {
// apiFetch with a raw init: the multipart body must NOT be JSON
// re-encoded, so the verb helper (which JSON-stringifies) is out.
return apiFetch<{
id: string;
valid: true;
summary: {
@@ -237,7 +227,7 @@ export function BackupsSection() {
cycles?: number;
cycleDayLogs?: number;
};
};
}>("/api/admin/backups/upload", { method: "POST", body: fd });
},
onSuccess: (data) => {
const total =
@@ -280,18 +270,11 @@ export function BackupsSection() {
// destructive transaction. Include the row id so two different
// backups can both be restored independently in the same minute.
const idempotencyKey = `restore-${row.id}-${crypto.randomUUID()}`;
const res = await fetch(`/api/admin/backups/${row.id}/restore`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({ confirm: "RESTORE" }),
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
return (await res.json()).data as { restored: true };
return apiPost<{ restored: true }>(
`/api/admin/backups/${row.id}/restore`,
{ confirm: "RESTORE" },
{ headers: { "Idempotency-Key": idempotencyKey } },
);
},
onSuccess: () => {
toast.success(t("admin.section.backups.restoreSuccess"));
@@ -312,7 +295,9 @@ export function BackupsSection() {
async function handleDownload(row: BackupRow) {
setDownloadingId(row.id);
try {
const res = await fetch(`/api/admin/backups/${row.id}/download`);
// apiFetchRaw: the download needs the raw Response for the blob +
// the Content-Disposition filename header.
const res = await apiFetchRaw(`/api/admin/backups/${row.id}/download`);
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
@@ -23,6 +23,7 @@ import { Loader2, Sparkles } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { helpfulRateColour } from "./_shared";
interface CoachFeedbackBucket {
@@ -41,11 +42,6 @@ interface FeedbackSummary {
coachBuckets?: CoachFeedbackBucket[];
}
interface CoachFeedbackResponse {
data: { summary: FeedbackSummary | null } | null;
error?: string | null;
}
export function CoachFeedbackSection() {
const { t } = useTranslations();
const fmt = useFormatters();
@@ -53,10 +49,10 @@ export function CoachFeedbackSection() {
const query = useQuery({
queryKey: queryKeys.adminCoachFeedback(),
queryFn: async () => {
const res = await fetch("/api/admin/ai-quality");
const json = (await res.json()) as CoachFeedbackResponse;
if (!res.ok) throw new Error(json.error ?? "coach_feedback_failed");
return json.data?.summary ?? null;
const data = await apiGet<{ summary: FeedbackSummary | null } | null>(
"/api/admin/ai-quality",
);
return data?.summary ?? null;
},
});
@@ -69,7 +65,7 @@ export function CoachFeedbackSection() {
// baseline stays at a constant Y-offset. Previously the loading branch
// returned a thin flex-row stub and the error branch a p-4 alert with
// NO heading, which made the entire section snap downward when the
// fetched data resolved — Marc reported the visible layout shift on
// fetched data resolved — the maintainer reported the visible layout shift on
// /admin/coach-feedback. Mirrors the canonical structure used by
// <SystemStatusSection> (header outside the fetch-state branch).
return (
+3 -9
View File
@@ -16,6 +16,7 @@ import {
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { apiDelete } from "@/lib/api/api-fetch";
export function DangerZoneSection() {
const { t } = useTranslations();
@@ -24,14 +25,7 @@ export function DangerZoneSection() {
const wipeAllData = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/data", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirm: "DELETE ALL" }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
return json.data as {
return apiDelete<{
measurements: number;
intakeEvents: number;
medications: number;
@@ -41,7 +35,7 @@ export function DangerZoneSection() {
notificationChannels: number;
pushSubscriptions: number;
telegramScheduledDeletions: number;
};
}>("/api/admin/data", { confirm: "DELETE ALL" });
},
onSuccess: (data) => {
queryClient.invalidateQueries();
@@ -38,9 +38,9 @@ import {
type FeedbackItem,
type FeedbackListResponse,
type FeedbackStatusType,
getApiErrorMessage,
useSystemStatus,
} from "./_shared";
import { apiDelete, apiGet, apiPatch, apiPost } from "@/lib/api/api-fetch";
export function FeedbackInboxSection() {
const { t } = useTranslations();
@@ -54,11 +54,7 @@ export function FeedbackInboxSection() {
const { data, isLoading } = useQuery({
queryKey: queryKeys.adminFeedback(activeStatus),
queryFn: async () => {
const res = await fetch(
`/api/admin/feedback?status=${activeStatus}&limit=100`,
);
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as FeedbackListResponse;
return apiGet<FeedbackListResponse>(`/api/admin/feedback?status=${activeStatus}&limit=100`);
},
});
@@ -259,12 +255,7 @@ function FeedbackDetailDialog({
status?: FeedbackStatusType;
adminNote?: string | null;
}) => {
const res = await fetch(`/api/admin/feedback/${item.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
await apiPatch(`/api/admin/feedback/${item.id}`, payload);
},
onSuccess: (_, vars) => {
onMutated();
@@ -281,10 +272,7 @@ function FeedbackDetailDialog({
const archive = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/admin/feedback/${item.id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
await apiDelete(`/api/admin/feedback/${item.id}`);
},
onSuccess: () => {
onMutated();
@@ -299,11 +287,7 @@ function FeedbackDetailDialog({
const publish = useMutation({
mutationFn: async () => {
const res = await fetch(`/api/admin/feedback/${item.id}/github`, {
method: "POST",
});
if (!res.ok) throw new Error(await getApiErrorMessage(res));
return (await res.json()).data as { issueUrl: string };
return apiPost<{ issueUrl: string }>(`/api/admin/feedback/${item.id}/github`);
},
onSuccess: (data) => {
setIssueUrl(data.issueUrl);
+5 -9
View File
@@ -11,10 +11,10 @@ import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
SettingsToggle,
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function GlitchtipSection() {
const { t } = useTranslations();
@@ -35,14 +35,10 @@ export function GlitchtipSection() {
const testGlitchtip = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/monitoring/glitchtip-test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as { data?: { message?: string } };
return json.data?.message ?? t("admin.monitoringTestSuccess");
const data = await apiPost<{ message?: string } | undefined>(
"/api/admin/monitoring/glitchtip-test",
);
return data?.message ?? t("admin.monitoringTestSuccess");
},
onSuccess: (message) => {
toast.success(message);
+2 -3
View File
@@ -39,6 +39,7 @@ import { useMemo } from "react";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { Skeleton } from "@/components/ui/skeleton";
import { apiGet } from "@/lib/api/api-fetch";
interface HostMetricsApiSample {
capturedAt: string;
@@ -134,9 +135,7 @@ export function HostMetricsChart() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminHostMetrics("2h"),
queryFn: async () => {
const res = await fetch("/api/admin/host-metrics?since=2h");
if (!res.ok) throw new Error("Failed to load host metrics");
return (await res.json()).data as HostMetricsApiResponse;
return apiGet<HostMetricsApiResponse>("/api/admin/host-metrics?since=2h");
},
// 60s matches the sampler cadence — anything faster would just
// re-render the same data.
+20 -16
View File
@@ -79,6 +79,7 @@ import { formatDate, formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { cn } from "@/lib/utils";
import { apiDelete, apiGet, apiPost } from "@/lib/api/api-fetch";
interface InviteRedemptionEntry {
id: string;
@@ -187,9 +188,7 @@ export function InviteTokensSection() {
const { data: invites, isError } = useQuery({
queryKey: queryKeys.adminInvites(),
queryFn: async () => {
const res = await fetch("/api/admin/invites");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminInvite[];
return apiGet<AdminInvite[]>("/api/admin/invites");
},
});
@@ -199,13 +198,10 @@ export function InviteTokensSection() {
expiresInDays: number;
maxUses: number;
}): Promise<MintedInvite> => {
const res = await fetch("/api/admin/invites", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()).data as Omit<MintedInvite, "qrDataUrl">;
const data = await apiPost<Omit<MintedInvite, "qrDataUrl">>(
"/api/admin/invites",
input,
);
// Lazy chunk: qrcode is only ever needed right here, at mint time.
const QRCode = (await import("qrcode")).default;
const qrDataUrl = await QRCode.toDataURL(data.url, {
@@ -226,10 +222,7 @@ export function InviteTokensSection() {
const revoke = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/admin/invites/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await apiDelete(`/api/admin/invites/${id}`);
},
onSuccess: () => {
toast.success(t("admin.invites.revokedToast"));
@@ -549,6 +542,16 @@ export function InviteTokensSection() {
{t("admin.invites.createDescription")}
</DialogDescription>
</DialogHeader>
{/* v1.16.4 — a real form so Enter in the max-uses field
submits; mirrors the intake-edit dialog convention. */}
<form
onSubmit={(e) => {
e.preventDefault();
if (create.isPending) return;
submitCreate();
}}
className="space-y-4"
>
<div className="space-y-5">
<fieldset>
<legend className="text-sm font-medium">
@@ -600,9 +603,9 @@ export function InviteTokensSection() {
</div>
<DialogFooter>
<Button
type="button"
type="submit"
disabled={create.isPending}
onClick={submitCreate}
aria-busy={create.isPending || undefined}
data-testid="admin-invites-submit-create"
>
{create.isPending ? (
@@ -616,6 +619,7 @@ export function InviteTokensSection() {
{t("admin.invites.createConfirm")}
</Button>
</DialogFooter>
</form>
</>
) : (
<>
@@ -36,6 +36,7 @@ import {
useAuthActionLabels,
useAuthProviderLabels,
} from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
type DateRangePreset = "all" | "24h" | "7d" | "30d";
type PerPageValue = 25 | 50 | 100;
@@ -130,9 +131,7 @@ export function LoginOverviewSection() {
if (filter === "failed") {
params.set("action", "auth.login.failed");
}
const res = await fetch(`/api/admin/audit-log?${params.toString()}`);
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AuditLogResponse;
return apiGet<AuditLogResponse>(`/api/admin/audit-log?${params.toString()}`);
},
});
@@ -140,9 +139,7 @@ export function LoginOverviewSection() {
const { data: actionsData } = useQuery({
queryKey: queryKeys.adminAuditActions(),
queryFn: async () => {
const res = await fetch("/api/admin/audit-log/actions");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as { actions: string[] };
return apiGet<{ actions: string[] }>("/api/admin/audit-log/actions");
},
staleTime: 5 * 60_000,
});
@@ -23,6 +23,7 @@ import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type AdminAuditEntry, useAuthActionLabels } from "./_shared";
import { apiGet } from "@/lib/api/api-fetch";
const PREVIEW_LIMIT = 10;
@@ -37,11 +38,7 @@ export function RecentAuditPreview() {
const { data, isLoading, isError } = useQuery({
queryKey: queryKeys.adminAuditOverview(),
queryFn: async () => {
const res = await fetch(
`/api/admin/audit-log?limit=${PREVIEW_LIMIT}&filter=auth`,
);
if (!res.ok) throw new Error("Failed to load audit log");
return (await res.json()).data as AuditLogResponse;
return apiGet<AuditLogResponse>(`/api/admin/audit-log?limit=${PREVIEW_LIMIT}&filter=auth`);
},
// Avoid hitting the DB on every page focus; the overview is the
// type of page admins keep open and re-render frequently.
+35 -50
View File
@@ -9,11 +9,8 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { useAdminSettings, useUpdateSettings } from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function RemindersSection() {
const { t } = useTranslations();
@@ -28,23 +25,17 @@ export function RemindersSection() {
const testNotification = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/notifications/test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as {
data?: {
message?: string;
results?: Array<{
channel: string;
success: boolean;
error?: string;
}>;
};
};
return json.data;
return apiPost<
| {
message?: string;
results?: Array<{
channel: string;
success: boolean;
error?: string;
}>;
}
| undefined
>("/api/admin/notifications/test");
},
onSuccess: (data) => {
const hasFailures = data?.results?.some((r) => !r.success);
@@ -65,35 +56,29 @@ export function RemindersSection() {
const reminderCheck = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/notifications/reminder-check", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as {
data?: {
message?: string;
medications?: Array<{
name: string;
dose: string;
user: string;
localTime: string;
dayOfWeek: string;
notificationsEnabled: boolean;
schedules: Array<{
window: string;
days: string;
status: string;
label: string;
notificationSent?: boolean;
return apiPost<
| {
message?: string;
medications?: Array<{
name: string;
dose: string;
user: string;
localTime: string;
dayOfWeek: string;
notificationsEnabled: boolean;
schedules: Array<{
window: string;
days: string;
status: string;
label: string;
notificationSent?: boolean;
}>;
eventsToday: number;
}>;
eventsToday: number;
}>;
notificationsSent?: number;
};
};
return json.data;
notificationsSent?: number;
}
| undefined
>("/api/admin/notifications/reminder-check");
},
onSuccess: (data) => {
toast.success(data?.message ?? t("admin.reminderCheckSuccess"));
+5 -9
View File
@@ -11,10 +11,10 @@ import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
SettingsToggle,
getApiErrorMessage,
useAdminSettings,
useUpdateSettings,
} from "./_shared";
import { apiPost } from "@/lib/api/api-fetch";
export function UmamiSection() {
const { t } = useTranslations();
@@ -38,14 +38,10 @@ export function UmamiSection() {
const testUmami = useMutation({
mutationFn: async () => {
const res = await fetch("/api/admin/monitoring/umami-test", {
method: "POST",
});
if (!res.ok) {
throw new Error(await getApiErrorMessage(res));
}
const json = (await res.json()) as { data?: { message?: string } };
return json.data?.message ?? t("admin.monitoringTestSuccess");
const data = await apiPost<{ message?: string } | undefined>(
"/api/admin/monitoring/umami-test",
);
return data?.message ?? t("admin.monitoringTestSuccess");
},
onSuccess: (message) => {
toast.success(message);
@@ -25,6 +25,7 @@ import { formatDate } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { type AdminUser, PasswordInput } from "./_shared";
import { apiGet, apiPost, apiPut } from "@/lib/api/api-fetch";
/**
* Filter values for the v1.5 users sub-route. The User model does NOT
@@ -52,9 +53,7 @@ export function UserManagementSection() {
const { data: users } = useQuery({
queryKey: queryKeys.adminUsers(),
queryFn: async () => {
const res = await fetch("/api/admin/users");
if (!res.ok) throw new Error("Failed");
return (await res.json()).data as AdminUser[];
return apiGet<AdminUser[]>("/api/admin/users");
},
});
@@ -73,13 +72,7 @@ export function UserManagementSection() {
id: string;
data: Record<string, unknown>;
}) => {
const res = await fetch(`/api/admin/users/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
await apiPut(`/api/admin/users/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: queryKeys.adminUsers() });
@@ -97,13 +90,7 @@ export function UserManagementSection() {
const resetPw = useMutation({
mutationFn: async ({ id, password }: { id: string; password: string }) => {
const res = await fetch(`/api/admin/users/${id}/reset-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
await apiPost(`/api/admin/users/${id}/reset-password`, { password });
},
onSuccess: () => {
setResetMsg(t("admin.passwordReset"));
@@ -116,12 +103,9 @@ export function UserManagementSection() {
const forceLogout = useMutation({
mutationFn: async ({ id }: { id: string }) => {
const res = await fetch(`/api/admin/users/${id}/force-logout`, {
method: "POST",
});
const json = await res.json();
if (!res.ok) throw new Error(json.error || t("common.error"));
return json.data as { sessionsRevoked: number };
return apiPost<{ sessionsRevoked: number }>(
`/api/admin/users/${id}/force-logout`,
);
},
onSuccess: (result, vars) => {
const username =
@@ -421,7 +405,22 @@ export function UserManagementSection() {
<h3 className="mb-3 text-sm font-semibold">
{t("admin.editUserTitle", { name: editingUser.username })}
</h3>
<div className="space-y-3">
{/* v1.16.4 — a real form so Enter in the username / email
fields submits; mirrors the dialog convention. */}
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
if (updateUser.isPending) return;
updateUser.mutate({
id: editingUser.id,
data: {
username: editUsername,
email: editEmail || null,
},
});
}}
>
<div className="space-y-1">
<Label htmlFor="edit-username">{t("auth.username")}</Label>
<Input
@@ -448,17 +447,10 @@ export function UserManagementSection() {
</div>
<div className="flex gap-2">
<Button
type="submit"
size="sm"
disabled={updateUser.isPending}
onClick={() =>
updateUser.mutate({
id: editingUser.id,
data: {
username: editUsername,
email: editEmail || null,
},
})
}
aria-busy={updateUser.isPending || undefined}
>
{updateUser.isPending && (
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
@@ -466,6 +458,7 @@ export function UserManagementSection() {
{t("common.save")}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setEditingUser(null)}
@@ -478,7 +471,7 @@ export function UserManagementSection() {
</span>
)}
</div>
</div>
</form>
</div>
)}
@@ -21,6 +21,7 @@ import { useQuery } from "@tanstack/react-query";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { ApiError, apiGet } from "@/lib/api/api-fetch";
import { StatusItem, usePublicVersion } from "./_shared";
type CheckUpdatesResult =
@@ -41,11 +42,13 @@ type CheckUpdatesResult =
| { status: "unknown"; current: string; reason: string };
async function fetchUpdateCheck(): Promise<CheckUpdatesResult> {
const res = await fetch("/api/version/check-updates");
if (!res.ok) {
return { status: "unknown", current: "", reason: `http_${res.status}` };
try {
return await apiGet<CheckUpdatesResult>("/api/version/check-updates");
} catch (err) {
const reason =
err instanceof ApiError ? `http_${err.status}` : "network_error";
return { status: "unknown", current: "", reason };
}
return (await res.json()).data as CheckUpdatesResult;
}
function shortSha(sha: string | null): string | null {