Email for professionals and teams
Translate activity, agent and AI usage admin pages
Hieu Nguyen (Jack)84ec386c7651
diff --git a/src/app/(admin)/activity/page.tsx b/src/app/(admin)/activity/page.tsxindex 5229018..2d3420f 100644--- a/src/app/(admin)/activity/page.tsx+++ b/src/app/(admin)/activity/page.tsx@@ -2,6 +2,7 @@import { useQuery } from "@tanstack/react-query";import { LogIn, LogOut } from "lucide-react";+import { useLanguage } from "@/components/language-provider";import { Badge } from "@/components/ui/badge";import { Skeleton } from "@/components/ui/skeleton";import {@@ -12,6 +13,7 @@ import {} from "./utils";export default function ActivityPage() {+ const { t } = useLanguage();const activity = useQuery({queryKey: ["activity"],queryFn: fetchActivity,@@ -20,9 +22,9 @@ export default function ActivityPage() {return (<div className="space-y-6"><div>- <h1 className="text-2xl md:text-3xl font-medium text-neutral-900">Activity</h1>+ <h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("activity.title")}</h1><p className="mt-1 text-sm text-neutral-500">- Login and logout activity across user accounts.+ {t("activity.description")}</p></div>@@ -30,10 +32,10 @@ export default function ActivityPage() {<table className="w-full min-w-[760px] table-fixed text-left"><thead className="border-b border-neutral-100 bg-neutral-50 text-xs font-semibold uppercase tracking-wide text-neutral-500"><tr>- <th className="w-32 px-5 py-3">Activity</th>- <th className="px-5 py-3">User</th>- <th className="w-64 px-5 py-3">Device</th>- <th className="w-48 px-5 py-3">Time</th>+ <th className="w-32 px-5 py-3">{t("activity.col.activity")}</th>+ <th className="px-5 py-3">{t("activity.col.user")}</th>+ <th className="w-64 px-5 py-3">{t("activity.col.device")}</th>+ <th className="w-48 px-5 py-3">{t("activity.col.time")}</th></tr></thead><tbody className="divide-y divide-neutral-100">@@ -57,7 +59,7 @@ export default function ActivityPage() {{!activity.isLoading && (activity.data ?? []).length === 0 && (<tr><td colSpan={4} className="px-5 py-4 text-sm text-neutral-500">- No login or logout activity yet+ {t("activity.none")}</td></tr>)}@@ -69,26 +71,26 @@ export default function ActivityPage() {<td className="px-5 py-4"><Badge variant="outline" className="gap-1"><Icon className="h-3 w-3" />- {getActivityLabel(log.action)}+ {getActivityLabel(log.action, t)}</Badge></td><td className="px-5 py-4"><p className="flex flex-col truncate no-font-mono">- <span>{log.actorEmail ?? "(unknown email)"}</span>+ <span>{log.actorEmail ?? t("activity.unknownEmail")}</span></p><small className="text-neutral-500">- {metadata.city || "(unknown city)"} •{" "}- {metadata.country || "(unknown country)"}+ {metadata.city || t("activity.unknownCity")} •{" "}+ {metadata.country || t("activity.unknownCountry")}</small></td><td className="px-5 py-4"><p className="flex flex-col truncate no-font-mono">- {metadata.device ?? "(unknown device)"}+ {metadata.device ?? t("activity.unknownDevice")}</p><small className="text-neutral-500">- {metadata.platform || "(unknown platform)"} •{" "}- {metadata.ipAddress ?? "(unknown IP)"}+ {metadata.platform || t("activity.unknownPlatform")} •{" "}+ {metadata.ipAddress ?? t("activity.unknownIp")}</small></td><td className="px-5 py-4 text-sm text-neutral-500">diff --git a/src/app/(admin)/activity/utils.ts b/src/app/(admin)/activity/utils.tsindex f0ffe05..1c27a6a 100644--- a/src/app/(admin)/activity/utils.ts+++ b/src/app/(admin)/activity/utils.ts@@ -1,3 +1,4 @@+import { defaultTranslator, type Translator } from "@/lib/i18n/utils";import { authFetch } from "@/lib/auth/client";import { formatUserDate } from "@/lib/time/utils";import type { ActivityLog, ActivityMetadata } from "./types";@@ -16,9 +17,9 @@ export function formatActivityDate(value: string): string {});}-export function getActivityLabel(action: string): string {- if (action === "auth.login") return "Login";- if (action === "auth.logout") return "Logout";+export function getActivityLabel(action: string, t: Translator = defaultTranslator): string {+ if (action === "auth.login") return t("activity.login");+ if (action === "auth.logout") return t("activity.logout");return action;}diff --git a/src/app/(admin)/agent/page.tsx b/src/app/(admin)/agent/page.tsxindex c05cdca..1e7ec66 100644--- a/src/app/(admin)/agent/page.tsx+++ b/src/app/(admin)/agent/page.tsx@@ -3,6 +3,7 @@import Link from "next/link";import { useEffect, useState } from "react";import { Bot } from "lucide-react";+import { useLanguage } from "@/components/language-provider";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";@@ -19,6 +20,7 @@ import { baseUrlForPreset, loadAgentAdminSettings, loadAgentModels, PROVIDER_PREconst initialForm: AgentAdminForm = { provider: "cloudflare", preset: "openai", baseUrl: "", apiKey: "", model: DEFAULT_CLOUDFLARE_MODEL, rates: {} };export default function AdminAgentPage() {+ const { t } = useLanguage();const [form, setForm] = useState<AgentAdminForm>(initialForm);const [assistantEnabled, setAssistantEnabled] = useState(true);const [enabledSaving, setEnabledSaving] = useState(false);@@ -44,9 +46,9 @@ export default function AdminAgentPage() {setHasSavedKey(data.config.hasApiKey);setSavedEndpoint(`${data.config.preset}|${data.config.baseUrl}`);setLoaded(true);- }).catch((error) => { if (active) setStatus(error instanceof Error ? error.message : "Could not load agent settings"); });+ }).catch((error) => { if (active) setStatus(error instanceof Error ? error.message : t("agentAdmin.loadFailed")); });return () => { active = false; };- }, []);+ }, [t]);const canUseSavedKey = hasSavedKey && savedEndpoint === `${form.preset}|${form.baseUrl}`;const selectedModelIds = parseAgentModelIds(form.model);@@ -56,7 +58,7 @@ export default function AdminAgentPage() {setModelSource(null);setModelError(null);if (form.provider === "compatible" && (!form.baseUrl || (!form.apiKey.trim() && !canUseSavedKey))) {- setModelError(form.preset === "custom" && !form.baseUrl ? "Enter an HTTPS base URL to load models." : "Enter an API key to load models.");+ setModelError(form.preset === "custom" && !form.baseUrl ? t("agentAdmin.enterUrl") : t("agentAdmin.enterKey"));return;}const controller = new AbortController();@@ -68,11 +70,11 @@ export default function AdminAgentPage() {const published = Object.fromEntries(data.models.flatMap((item) => item.rates ? [[item.id, item.rates]] : []));if (Object.keys(published).length) setForm((current) => ({ ...current, rates: { ...current.rates, ...published } }));}).catch((error) => {- if (!controller.signal.aborted) setModelError(error instanceof Error ? error.message : "Could not load models");+ if (!controller.signal.aborted) setModelError(error instanceof Error ? error.message : t("agentAdmin.modelsFailed"));}).finally(() => { if (!controller.signal.aborted) setModelsLoading(false); });}, form.provider === "cloudflare" ? 0 : 500);return () => { window.clearTimeout(timer); controller.abort(); };- }, [loaded, form.provider, form.preset, form.baseUrl, form.apiKey, canUseSavedKey]);+ }, [loaded, form.provider, form.preset, form.baseUrl, form.apiKey, canUseSavedKey, t]);async function submit(event: React.FormEvent<HTMLFormElement>) {event.preventDefault();@@ -83,38 +85,38 @@ export default function AdminAgentPage() {setForm((current) => ({ ...current, apiKey: "", model: data.config.models.join(", "), rates: data.config.rates }));setHasSavedKey(data.config.hasApiKey);setSavedEndpoint(`${data.config.preset}|${data.config.baseUrl}`);- setStatus("Agent provider saved. Assistant settings can now choose from these models.");+ setStatus(t("agentAdmin.saved"));} catch (error) {- setStatus(error instanceof Error ? error.message : "Could not save agent settings");+ setStatus(error instanceof Error ? error.message : t("agentAdmin.saveFailed"));} finally { setSaving(false); }}return <div className="space-y-6">- <div className="flex items-start justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">Agent</h1><p className="mt-2 text-sm text-neutral-500">Choose the AI provider and models used by the email assistant for chat and drafts.</p></div><Link href="/ai-usage" className="shrink-0 rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-medium text-neutral-800 hover:bg-neutral-50">View Usage</Link></div>+ <div className="flex items-start justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("agentAdmin.title")}</h1><p className="mt-2 text-sm text-neutral-500">{t("agentAdmin.description")}</p></div><Link href="/ai-usage" className="shrink-0 rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-medium text-neutral-800 hover:bg-neutral-50">{t("agentAdmin.viewUsage")}</Link></div><Card className="rounded-3xl border-0 bg-white p-6"><CardContent className="flex items-center justify-between gap-4 p-0">- <div><p className="font-medium text-neutral-900">Enable assistant</p><p className="mt-1 text-sm text-neutral-500">Show assistant chat and allow automatic drafts for everyone.</p></div>+ <div><p className="font-medium text-neutral-900">{t("agentAdmin.enable")}</p><p className="mt-1 text-sm text-neutral-500">{t("agentAdmin.enableHint")}</p></div><Switch checked={assistantEnabled} disabled={!loaded || enabledSaving} onCheckedChange={(checked) => {setEnabledSaving(true);setEnabledStatus(null);- void saveAgentEnabled(checked).then((data) => { setAssistantEnabled(data.assistantEnabled); saveAssistantAvailability(data.assistantEnabled); }).catch((error) => setEnabledStatus(error instanceof Error ? error.message : "Could not update assistant availability")).finally(() => setEnabledSaving(false));- }} aria-label="Enable assistant" />+ void saveAgentEnabled(checked).then((data) => { setAssistantEnabled(data.assistantEnabled); saveAssistantAvailability(data.assistantEnabled); }).catch((error) => setEnabledStatus(error instanceof Error ? error.message : t("agentAdmin.availabilityFailed"))).finally(() => setEnabledSaving(false));+ }} aria-label={t("agentAdmin.enable")} /></CardContent>{enabledStatus && <p role="status" className="mt-3 text-sm text-red-700">{enabledStatus}</p>}</Card><Card className="rounded-3xl border-0 bg-white p-6">- <CardHeader className="py-0"><CardTitle className="flex items-center gap-2"><Bot className="h-5 w-5" />AI provider</CardTitle><CardDescription>Email content is sent to the selected provider when someone uses the assistant. Sending a draft still requires human approval.</CardDescription></CardHeader>+ <CardHeader className="py-0"><CardTitle className="flex items-center gap-2"><Bot className="h-5 w-5" />{t("agentAdmin.provider")}</CardTitle><CardDescription>{t("agentAdmin.providerWarning")}</CardDescription></CardHeader><CardContent className="pt-6"><form onSubmit={submit} className="space-y-5">- <div className="space-y-2"><Label htmlFor="agent-provider">Provider</Label><select id="agent-provider" className="flex h-10 w-full rounded-md border border-neutral-200 bg-transparent px-3 text-sm shadow-sm shadow-neutral-200/50 focus-visible:border-blue-600 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50" value={form.provider} disabled={!loaded} onChange={(event) => setForm((current) => ({ ...current, provider: event.target.value as AgentAdminForm["provider"], baseUrl: event.target.value === "compatible" ? baseUrlForPreset(current.preset, current.baseUrl) : "", model: event.target.value === "cloudflare" ? DEFAULT_CLOUDFLARE_MODEL : "" }))}><option value="cloudflare">Cloudflare Workers AI</option><option value="compatible">OpenAI-compatible provider</option></select>{form.provider === "cloudflare" && !cloudflareAvailable && <p className="text-xs text-amber-700">Cloudflare Workers AI requires an AI binding on this installation.</p>}</div>+ <div className="space-y-2"><Label htmlFor="agent-provider">{t("agentAdmin.providerLabel")}</Label><select id="agent-provider" className="flex h-10 w-full rounded-md border border-neutral-200 bg-transparent px-3 text-sm shadow-sm shadow-neutral-200/50 focus-visible:border-blue-600 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50" value={form.provider} disabled={!loaded} onChange={(event) => setForm((current) => ({ ...current, provider: event.target.value as AgentAdminForm["provider"], baseUrl: event.target.value === "compatible" ? baseUrlForPreset(current.preset, current.baseUrl) : "", model: event.target.value === "cloudflare" ? DEFAULT_CLOUDFLARE_MODEL : "" }))}><option value="cloudflare">{t("agentAdmin.cloudflareAi")}</option><option value="compatible">{t("agentAdmin.openaiCompatible")}</option></select>{form.provider === "cloudflare" && !cloudflareAvailable && <p className="text-xs text-amber-700">{t("agentAdmin.needsBinding")}</p>}</div>{form.provider === "compatible" && <>- <div className="space-y-2"><Label htmlFor="agent-preset">Provider template</Label><select id="agent-preset" className="flex h-10 w-full rounded-md border border-neutral-200 bg-transparent px-3 text-sm shadow-sm shadow-neutral-200/50 focus-visible:border-blue-600 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50" value={form.preset} onChange={(event) => { const preset = event.target.value as AgentProviderPreset; setForm((current) => ({ ...current, preset, baseUrl: baseUrlForPreset(preset), apiKey: "", model: "" })); }}>{PROVIDER_PRESETS.map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}</select></div>- <div className="space-y-2"><Label htmlFor="agent-url">API base URL</Label><Input id="agent-url" type="url" value={form.baseUrl} readOnly={form.preset !== "custom"} placeholder="https://provider.example/v1" onChange={(event) => setForm((current) => ({ ...current, baseUrl: event.target.value, model: "" }))} required /></div>- <div className="space-y-2"><Label htmlFor="agent-key">API key</Label><Input id="agent-key" type="password" value={form.apiKey} autoComplete="new-password" placeholder={canUseSavedKey ? "Saved key (leave blank to keep)" : "Enter API key"} onChange={(event) => setForm((current) => ({ ...current, apiKey: event.target.value }))} /><p className="text-xs text-neutral-500">{canUseSavedKey ? "An API key is saved on the server. Enter a new one to replace it." : "The API key is stored on the server and is never shown again."}</p></div>+ <div className="space-y-2"><Label htmlFor="agent-preset">{t("agentAdmin.template")}</Label><select id="agent-preset" className="flex h-10 w-full rounded-md border border-neutral-200 bg-transparent px-3 text-sm shadow-sm shadow-neutral-200/50 focus-visible:border-blue-600 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50" value={form.preset} onChange={(event) => { const preset = event.target.value as AgentProviderPreset; setForm((current) => ({ ...current, preset, baseUrl: baseUrlForPreset(preset), apiKey: "", model: "" })); }}>{PROVIDER_PRESETS.map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}</select></div>+ <div className="space-y-2"><Label htmlFor="agent-url">{t("agentAdmin.baseUrl")}</Label><Input id="agent-url" type="url" value={form.baseUrl} readOnly={form.preset !== "custom"} placeholder="https://provider.example/v1" onChange={(event) => setForm((current) => ({ ...current, baseUrl: event.target.value, model: "" }))} required /></div>+ <div className="space-y-2"><Label htmlFor="agent-key">{t("agentAdmin.apiKey")}</Label><Input id="agent-key" type="password" value={form.apiKey} autoComplete="new-password" placeholder={canUseSavedKey ? t("agentAdmin.savedKeyPlaceholder") : t("agentAdmin.enterKeyPlaceholder")} onChange={(event) => setForm((current) => ({ ...current, apiKey: event.target.value }))} /><p className="text-xs text-neutral-500">{canUseSavedKey ? t("agentAdmin.keySaved") : t("agentAdmin.keyNote")}</p></div></>}- <div className="space-y-2"><p className="text-sm font-medium">Models</p><div className="max-h-64 space-y-2 overflow-y-auto rounded-md border border-neutral-200 p-3">{modelsLoading && <p className="text-sm text-neutral-500">Loading models…</p>}{!modelsLoading && !models.length && <p className="text-sm text-neutral-500">Models unavailable</p>}{models.map((item) => <label key={item.id} className="flex items-start gap-2 text-sm"><Checkbox checked={selectedModelIds.includes(item.id)} onChange={(event) => setForm((current) => ({ ...current, model: toggleAgentModelId(current.model, item.id, event.target.checked) }))} /><span>{item.name === item.id ? item.id : `${item.name} · ${item.id}`}</span></label>)}</div>{modelSource === "suggested" && <p className="text-xs text-neutral-500">Showing suggested Cloudflare models because a full catalog is unavailable.</p>}{modelError && <p className="text-xs text-amber-700">{modelError}</p>}<Label htmlFor="agent-model-id" className="block pt-2 text-xs text-neutral-500">Or enter model IDs (comma-separated)</Label><Input id="agent-model-id" value={form.model} onChange={(event) => setForm((current) => ({ ...current, model: event.target.value }))} placeholder={form.provider === "cloudflare" ? DEFAULT_CLOUDFLARE_MODEL : "provider/model-id, provider/another-model"} required /><p className="text-xs text-neutral-500">Choose models that support tool calling so the assistant can read mail and create drafts. The first model is the default.</p></div>- <div className="space-y-3"><p className="text-sm font-medium">Estimated cost rates</p><p className="text-xs text-neutral-500">USD per 1 million tokens. Rates published by the provider are used automatically; enter them yourself for models that don't publish any. Usage without both rates shows spending as unavailable.</p>{selectedModelIds.map((model) => models.find((item) => item.id === model)?.rates ? <div key={model} className="grid gap-2 rounded-xl border border-neutral-200 p-3 text-sm sm:grid-cols-[minmax(0,1fr)_auto]"><span className="min-w-0 break-all">{model}</span><span className="text-neutral-500">Input ${form.rates[model]?.input} · Output ${form.rates[model]?.output} / 1M <span className="text-xs">(from provider)</span></span></div> : <div key={model} className="grid gap-2 rounded-xl border border-neutral-200 p-3 sm:grid-cols-[minmax(0,1fr)_6rem_6rem]"><span className="min-w-0 break-all text-sm">{model}</span><label className="text-xs text-neutral-500">Input <Input type="number" min="0" step="any" value={form.rates[model]?.input ?? ""} onChange={(event) => setForm((current) => updateAgentModelRate(current, model, "input", event.target.value))} placeholder="USD / 1M" /></label><label className="text-xs text-neutral-500">Output <Input type="number" min="0" step="any" value={form.rates[model]?.output ?? ""} onChange={(event) => setForm((current) => updateAgentModelRate(current, model, "output", event.target.value))} placeholder="USD / 1M" /></label></div>)}</div>+ <div className="space-y-2"><p className="text-sm font-medium">{t("agentAdmin.models")}</p><div className="max-h-64 space-y-2 overflow-y-auto rounded-md border border-neutral-200 p-3">{modelsLoading && <p className="text-sm text-neutral-500">{t("agentAdmin.loadingModels")}</p>}{!modelsLoading && !models.length && <p className="text-sm text-neutral-500">{t("agentAdmin.modelsUnavailable")}</p>}{models.map((item) => <label key={item.id} className="flex items-start gap-2 text-sm"><Checkbox checked={selectedModelIds.includes(item.id)} onChange={(event) => setForm((current) => ({ ...current, model: toggleAgentModelId(current.model, item.id, event.target.checked) }))} /><span>{item.name === item.id ? item.id : `${item.name} · ${item.id}`}</span></label>)}</div>{modelSource === "suggested" && <p className="text-xs text-neutral-500">{t("agentAdmin.suggested")}</p>}{modelError && <p className="text-xs text-amber-700">{modelError}</p>}<Label htmlFor="agent-model-id" className="block pt-2 text-xs text-neutral-500">{t("agentAdmin.orEnterIds")}</Label><Input id="agent-model-id" value={form.model} onChange={(event) => setForm((current) => ({ ...current, model: event.target.value }))} placeholder={form.provider === "cloudflare" ? DEFAULT_CLOUDFLARE_MODEL : "provider/model-id, provider/another-model"} required /><p className="text-xs text-neutral-500">{t("agentAdmin.toolCalling")}</p></div>+ <div className="space-y-3"><p className="text-sm font-medium">{t("agentAdmin.rates")}</p><p className="text-xs text-neutral-500">{t("agentAdmin.ratesHint")}</p>{selectedModelIds.map((model) => models.find((item) => item.id === model)?.rates ? <div key={model} className="grid gap-2 rounded-xl border border-neutral-200 p-3 text-sm sm:grid-cols-[minmax(0,1fr)_auto]"><span className="min-w-0 break-all">{model}</span><span className="text-neutral-500">{t("agentAdmin.rateLine", { input: form.rates[model]?.input, output: form.rates[model]?.output })} <span className="text-xs">{t("agentAdmin.fromProvider")}</span></span></div> : <div key={model} className="grid gap-2 rounded-xl border border-neutral-200 p-3 sm:grid-cols-[minmax(0,1fr)_6rem_6rem]"><span className="min-w-0 break-all text-sm">{model}</span><label className="text-xs text-neutral-500">{t("agentAdmin.input")} <Input type="number" min="0" step="any" value={form.rates[model]?.input ?? ""} onChange={(event) => setForm((current) => updateAgentModelRate(current, model, "input", event.target.value))} placeholder={t("agentAdmin.usdPerM")} /></label><label className="text-xs text-neutral-500">{t("agentAdmin.output")} <Input type="number" min="0" step="any" value={form.rates[model]?.output ?? ""} onChange={(event) => setForm((current) => updateAgentModelRate(current, model, "output", event.target.value))} placeholder={t("agentAdmin.usdPerM")} /></label></div>)}</div>{status && <p role="status" className="text-sm text-neutral-700">{status}</p>}- <Button type="submit" disabled={!loaded || saving || !selectedModelIds.length || (form.provider === "cloudflare" && !cloudflareAvailable) || (form.provider === "compatible" && (!form.baseUrl || (!form.apiKey.trim() && !canUseSavedKey))) }>{saving ? "Saving…" : "Save agent settings"}</Button>+ <Button type="submit" disabled={!loaded || saving || !selectedModelIds.length || (form.provider === "cloudflare" && !cloudflareAvailable) || (form.provider === "compatible" && (!form.baseUrl || (!form.apiKey.trim() && !canUseSavedKey))) }>{saving ? t("common.saving") : t("agentAdmin.save")}</Button></form></CardContent></Card></div>;diff --git a/src/app/(admin)/ai-usage/page.tsx b/src/app/(admin)/ai-usage/page.tsxindex 61a1b66..40d28cc 100644--- a/src/app/(admin)/ai-usage/page.tsx+++ b/src/app/(admin)/ai-usage/page.tsx@@ -2,34 +2,36 @@import Link from "next/link";import { useEffect, useState } from "react";+import { useLanguage } from "@/components/language-provider";import { Button } from "@/components/ui/button";import type { AiUsageResponse } from "./types";import { fetchAiUsage, formatEstimatedUsd, formatTokenCount, formatUsageDate, formatUsageProvider } from "./utils";import { UsageChart } from "./usage-chart";export default function AiUsagePage() {+ const { t } = useLanguage();const [data, setData] = useState<AiUsageResponse | null>(null);const [error, setError] = useState<string | null>(null);const [loadingPage, setLoadingPage] = useState(false);useEffect(() => {let active = true;- void fetchAiUsage(1).then((result) => { if (active) setData(result); }).catch((cause) => { if (active) setError(cause instanceof Error ? cause.message : "Could not load AI usage"); });+ void fetchAiUsage(1).then((result) => { if (active) setData(result); }).catch((cause) => { if (active) setError(cause instanceof Error ? cause.message : t("aiUsage.loadFailed")); });return () => { active = false; };- }, []);+ }, [t]);const totals = data?.totals;return <div className="space-y-6">- <div className="flex items-start justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">AI Usage</h1><p className="mt-2 text-sm text-neutral-500">Requests recorded since usage tracking was added.</p></div><Link href="/agent" className="shrink-0 text-sm font-medium text-blue-700 hover:underline">Back to Agent</Link></div>+ <div className="flex items-start justify-between gap-4"><div><h1 className="text-2xl md:text-3xl font-medium text-neutral-900">{t("aiUsage.title")}</h1><p className="mt-2 text-sm text-neutral-500">{t("aiUsage.description")}</p></div><Link href="/agent" className="shrink-0 text-sm font-medium text-blue-700 hover:underline">{t("aiUsage.back")}</Link></div>{error && <p role="alert" className="text-sm text-red-700">{error}</p>}<div className="grid gap-4 sm:grid-cols-3">- <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">Total tokens</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals ? formatTokenCount(totals.totalTokens) : "—"}</p></section>- <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">Total requests</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals ? formatTokenCount(totals.requests) : "—"}</p></section>- <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">Estimated spend</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals && totals.pricedRequests ? formatEstimatedUsd(totals.costUsdMicros) : "—"}</p>{totals && totals.pricedRequests < totals.requests && <p className="mt-1 text-xs text-neutral-500">{formatTokenCount(totals.requests - totals.pricedRequests)} requests have no rate.</p>}</section>+ <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">{t("aiUsage.totalTokens")}</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals ? formatTokenCount(totals.totalTokens) : "—"}</p></section>+ <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">{t("aiUsage.totalRequests")}</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals ? formatTokenCount(totals.requests) : "—"}</p></section>+ <section className="rounded-2xl bg-white p-5"><p className="text-sm text-neutral-500">{t("aiUsage.spend")}</p><p className="mt-2 text-2xl font-semibold text-neutral-900">{totals && totals.pricedRequests ? formatEstimatedUsd(totals.costUsdMicros) : "—"}</p>{totals && totals.pricedRequests < totals.requests && <p className="mt-1 text-xs text-neutral-500">{t("aiUsage.noRate", { count: formatTokenCount(totals.requests - totals.pricedRequests) })}</p>}</section></div><UsageChart daily={data?.daily ?? []} timeZone={data?.timeZone} />- <section className="overflow-x-auto rounded-2xl bg-white" aria-busy={loadingPage}><table className="w-full min-w-[850px] text-left text-sm"><thead className="border-b border-neutral-100 bg-neutral-50 text-xs font-semibold uppercase tracking-wide text-neutral-500"><tr><th className="px-4 py-3">Date & time</th><th className="px-4 py-3">Model</th><th className="px-4 py-3">Provider</th><th className="px-4 py-3 text-right">Input tokens</th><th className="px-4 py-3 text-right">Output tokens</th><th className="px-4 py-3 text-right">Spending</th></tr></thead><tbody className="divide-y divide-neutral-100">{data?.rows.map((row) => <tr key={row.id}><td className="whitespace-nowrap px-4 py-3 text-neutral-600">{formatUsageDate(row.createdAt)}</td><td className="max-w-56 break-all px-4 py-3">{row.model}</td><td className="px-4 py-3">{formatUsageProvider(row.provider)}</td><td className="px-4 py-3 text-right tabular-nums">{formatTokenCount(row.inputTokens)}</td><td className="px-4 py-3 text-right tabular-nums">{formatTokenCount(row.outputTokens)}</td><td className="px-4 py-3 text-right tabular-nums">{formatEstimatedUsd(row.costUsdMicros)}</td></tr>)}{data && data.rows.length === 0 && <tr><td colSpan={6} className="px-4 py-8 text-center text-neutral-500">No AI usage recorded yet.</td></tr>}{!data && !error && <tr><td colSpan={6} className="px-4 py-8 text-center text-neutral-500">Loading usage…</td></tr>}</tbody></table></section>- {data && <div className="flex items-center justify-end gap-3 text-sm text-neutral-600"><span>Page {data.page} of {data.totalPages} · {data.pageSize} per page</span><Button type="button" variant="outline" size="sm" disabled={loadingPage || data.page <= 1} onClick={() => { setLoadingPage(true); setError(null); void fetchAiUsage(data.page - 1).then(setData).catch((cause) => setError(cause instanceof Error ? cause.message : "Could not load usage page")).finally(() => setLoadingPage(false)); }}>Previous</Button><Button type="button" variant="outline" size="sm" disabled={loadingPage || data.page >= data.totalPages} onClick={() => { setLoadingPage(true); setError(null); void fetchAiUsage(data.page + 1).then(setData).catch((cause) => setError(cause instanceof Error ? cause.message : "Could not load usage page")).finally(() => setLoadingPage(false)); }}>Next</Button></div>}- <p className="text-xs text-neutral-500">Spending is estimated from the per-model rates saved in Agent settings. A dash means no rate or token count was available.</p>+ <section className="overflow-x-auto rounded-2xl bg-white" aria-busy={loadingPage}><table className="w-full min-w-[850px] text-left text-sm"><thead className="border-b border-neutral-100 bg-neutral-50 text-xs font-semibold uppercase tracking-wide text-neutral-500"><tr><th className="px-4 py-3">{t("aiUsage.col.dateTime")}</th><th className="px-4 py-3">{t("aiUsage.col.model")}</th><th className="px-4 py-3">{t("aiUsage.col.provider")}</th><th className="px-4 py-3 text-right">{t("aiUsage.col.input")}</th><th className="px-4 py-3 text-right">{t("aiUsage.col.output")}</th><th className="px-4 py-3 text-right">{t("aiUsage.col.spending")}</th></tr></thead><tbody className="divide-y divide-neutral-100">{data?.rows.map((row) => <tr key={row.id}><td className="whitespace-nowrap px-4 py-3 text-neutral-600">{formatUsageDate(row.createdAt)}</td><td className="max-w-56 break-all px-4 py-3">{row.model}</td><td className="px-4 py-3">{formatUsageProvider(row.provider)}</td><td className="px-4 py-3 text-right tabular-nums">{formatTokenCount(row.inputTokens)}</td><td className="px-4 py-3 text-right tabular-nums">{formatTokenCount(row.outputTokens)}</td><td className="px-4 py-3 text-right tabular-nums">{formatEstimatedUsd(row.costUsdMicros)}</td></tr>)}{data && data.rows.length === 0 && <tr><td colSpan={6} className="px-4 py-8 text-center text-neutral-500">{t("aiUsage.none")}</td></tr>}{!data && !error && <tr><td colSpan={6} className="px-4 py-8 text-center text-neutral-500">{t("aiUsage.loading")}</td></tr>}</tbody></table></section>+ {data && <div className="flex items-center justify-end gap-3 text-sm text-neutral-600"><span>{t("aiUsage.pageOf", { page: data.page, total: data.totalPages, size: data.pageSize })}</span><Button type="button" variant="outline" size="sm" disabled={loadingPage || data.page <= 1} onClick={() => { setLoadingPage(true); setError(null); void fetchAiUsage(data.page - 1).then(setData).catch((cause) => setError(cause instanceof Error ? cause.message : t("aiUsage.pageFailed"))).finally(() => setLoadingPage(false)); }}>{t("aiUsage.previous")}</Button><Button type="button" variant="outline" size="sm" disabled={loadingPage || data.page >= data.totalPages} onClick={() => { setLoadingPage(true); setError(null); void fetchAiUsage(data.page + 1).then(setData).catch((cause) => setError(cause instanceof Error ? cause.message : t("aiUsage.pageFailed"))).finally(() => setLoadingPage(false)); }}>{t("aiUsage.next")}</Button></div>}+ <p className="text-xs text-neutral-500">{t("aiUsage.note")}</p></div>;}diff --git a/src/app/(admin)/ai-usage/usage-chart.tsx b/src/app/(admin)/ai-usage/usage-chart.tsxindex e5a571d..70d0d0f 100644--- a/src/app/(admin)/ai-usage/usage-chart.tsx+++ b/src/app/(admin)/ai-usage/usage-chart.tsx@@ -1,19 +1,21 @@+import { useLanguage } from "@/components/language-provider";import type { UsageChartProps } from "./types";import { fillDailyUsage, formatDailyLabel, formatTokenCount } from "./utils";import { getUserTimeZone } from "@/lib/time/utils";export function UsageChart({ daily, timeZone = getUserTimeZone() }: UsageChartProps) {+ const { t } = useLanguage();const days = daily.length ? daily : fillDailyUsage([], timeZone);const maxTokens = Math.max(0, ...days.map((day) => day.inputTokens + day.outputTokens));return <section className="rounded-2xl bg-white p-5">- <div className="flex flex-wrap items-center justify-between gap-3"><div><h2 className="text-base font-semibold text-neutral-900">Usage by day</h2><p className="mt-1 text-xs text-neutral-500">Input and output tokens over the last 30 days ({timeZone})</p></div><div className="flex items-center gap-4 text-xs text-neutral-600"><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-sm bg-blue-600" /> Input</span><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-sm bg-sky-300" /> Output</span></div></div>- <div className="mt-5 flex gap-3" role="img" aria-label="Daily AI token usage for the last 30 days">+ <div className="flex flex-wrap items-center justify-between gap-3"><div><h2 className="text-base font-semibold text-neutral-900">{t("aiUsage.byDay")}</h2><p className="mt-1 text-xs text-neutral-500">{t("aiUsage.chartHint", { zone: timeZone })}</p></div><div className="flex items-center gap-4 text-xs text-neutral-600"><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-sm bg-blue-600" /> {t("aiUsage.legendInput")}</span><span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-sm bg-sky-300" /> {t("aiUsage.legendOutput")}</span></div></div>+ <div className="mt-5 flex gap-3" role="img" aria-label={t("aiUsage.chartLabel")}><div className="flex h-48 flex-col justify-between pb-5 text-right text-[10px] text-neutral-400"><span>{formatTokenCount(maxTokens)}</span><span>0</span></div><div className="flex min-w-0 flex-1 items-end gap-1 border-b border-neutral-200">{days.map((day, index) => {const total = day.inputTokens + day.outputTokens;- return <div key={day.date} className="flex h-48 min-w-0 flex-1 flex-col items-center" title={`${formatDailyLabel(day.date)}: ${formatTokenCount(total)} tokens, ${formatTokenCount(day.requests)} requests`}>+ return <div key={day.date} className="flex h-48 min-w-0 flex-1 flex-col items-center" title={t("aiUsage.barTitle", { day: formatDailyLabel(day.date), tokens: formatTokenCount(total), requests: formatTokenCount(day.requests) })}><div className="flex h-[172px] w-full items-end justify-center"><div className="relative w-full max-w-5 rounded-t-sm" style={{ height: `${total ? Math.max(2, total / maxTokens * 100) : 0}%` }}><div className="absolute inset-x-0 bottom-0 bg-blue-600" style={{ height: `${total ? day.inputTokens / total * 100 : 0}%` }} /><div className="absolute inset-x-0 top-0 bg-sky-300" style={{ height: `${total ? day.outputTokens / total * 100 : 0}%` }} /></div></div><span className="h-5 whitespace-nowrap pt-1 text-[9px] text-neutral-400">{index % 5 === 0 || index === days.length - 1 ? formatDailyLabel(day.date) : ""}</span></div>;diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex cbaadf4..2f277e6 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -1401,5 +1401,86 @@"licenses.validate": "Validate license","licenses.deactivateShort": "Deactivate","licenses.activating": "Activating...",- "licenses.activate": "Activate"+ "licenses.activate": "Activate",+ "activity.title": "Activity",+ "activity.description": "Login and logout activity across user accounts.",+ "activity.col.activity": "Activity",+ "activity.col.user": "User",+ "activity.col.device": "Device",+ "activity.col.time": "Time",+ "activity.none": "No login or logout activity yet",+ "activity.login": "Login",+ "activity.logout": "Logout",+ "activity.unknownEmail": "(unknown email)",+ "activity.unknownCity": "(unknown city)",+ "activity.unknownCountry": "(unknown country)",+ "activity.unknownDevice": "(unknown device)",+ "activity.unknownPlatform": "(unknown platform)",+ "activity.unknownIp": "(unknown IP)",+ "agentAdmin.loadFailed": "Could not load agent settings",+ "agentAdmin.enterUrl": "Enter an HTTPS base URL to load models.",+ "agentAdmin.enterKey": "Enter an API key to load models.",+ "agentAdmin.modelsFailed": "Could not load models",+ "agentAdmin.saved": "Agent provider saved. Assistant settings can now choose from these models.",+ "agentAdmin.saveFailed": "Could not save agent settings",+ "agentAdmin.title": "Agent",+ "agentAdmin.description": "Choose the AI provider and models used by the email assistant for chat and drafts.",+ "agentAdmin.viewUsage": "View Usage",+ "agentAdmin.enable": "Enable assistant",+ "agentAdmin.enableHint": "Show assistant chat and allow automatic drafts for everyone.",+ "agentAdmin.availabilityFailed": "Could not update assistant availability",+ "agentAdmin.provider": "AI provider",+ "agentAdmin.providerWarning": "Email content is sent to the selected provider when someone uses the assistant. Sending a draft still requires human approval.",+ "agentAdmin.providerLabel": "Provider",+ "agentAdmin.cloudflareAi": "Cloudflare Workers AI",+ "agentAdmin.openaiCompatible": "OpenAI-compatible provider",+ "agentAdmin.needsBinding": "Cloudflare Workers AI requires an AI binding on this installation.",+ "agentAdmin.template": "Provider template",+ "agentAdmin.baseUrl": "API base URL",+ "agentAdmin.apiKey": "API key",+ "agentAdmin.savedKeyPlaceholder": "Saved key (leave blank to keep)",+ "agentAdmin.enterKeyPlaceholder": "Enter API key",+ "agentAdmin.keySaved": "An API key is saved on the server. Enter a new one to replace it.",+ "agentAdmin.keyNote": "The API key is stored on the server and is never shown again.",+ "agentAdmin.models": "Models",+ "agentAdmin.loadingModels": "Loading models…",+ "agentAdmin.modelsUnavailable": "Models unavailable",+ "agentAdmin.suggested": "Showing suggested Cloudflare models because a full catalog is unavailable.",+ "agentAdmin.orEnterIds": "Or enter model IDs (comma-separated)",+ "agentAdmin.toolCalling": "Choose models that support tool calling so the assistant can read mail and create drafts. The first model is the default.",+ "agentAdmin.rates": "Estimated cost rates",+ "agentAdmin.ratesHint": "USD per 1 million tokens. Rates published by the provider are used automatically; enter them yourself for models that don't publish any. Usage without both rates shows spending as unavailable.",+ "agentAdmin.rateLine": "Input ${input} · Output ${output} / 1M",+ "agentAdmin.fromProvider": "(from provider)",+ "agentAdmin.input": "Input",+ "agentAdmin.output": "Output",+ "agentAdmin.usdPerM": "USD / 1M",+ "agentAdmin.save": "Save agent settings",+ "aiUsage.loadFailed": "Could not load AI usage",+ "aiUsage.pageFailed": "Could not load usage page",+ "aiUsage.title": "AI Usage",+ "aiUsage.description": "Requests recorded since usage tracking was added.",+ "aiUsage.back": "Back to Agent",+ "aiUsage.totalTokens": "Total tokens",+ "aiUsage.totalRequests": "Total requests",+ "aiUsage.spend": "Estimated spend",+ "aiUsage.noRate": "{count} requests have no rate.",+ "aiUsage.col.dateTime": "Date & time",+ "aiUsage.col.model": "Model",+ "aiUsage.col.provider": "Provider",+ "aiUsage.col.input": "Input tokens",+ "aiUsage.col.output": "Output tokens",+ "aiUsage.col.spending": "Spending",+ "aiUsage.none": "No AI usage recorded yet.",+ "aiUsage.loading": "Loading usage…",+ "aiUsage.pageOf": "Page {page} of {total} · {size} per page",+ "aiUsage.previous": "Previous",+ "aiUsage.next": "Next",+ "aiUsage.note": "Spending is estimated from the per-model rates saved in Agent settings. A dash means no rate or token count was available.",+ "aiUsage.byDay": "Usage by day",+ "aiUsage.chartHint": "Input and output tokens over the last 30 days ({zone})",+ "aiUsage.legendInput": "Input",+ "aiUsage.legendOutput": "Output",+ "aiUsage.chartLabel": "Daily AI token usage for the last 30 days",+ "aiUsage.barTitle": "{day}: {tokens} tokens, {requests} requests"}diff --git a/src/lib/i18n/pt-BR.json b/src/lib/i18n/pt-BR.jsonindex 1b1c5a2..61b8da0 100644--- a/src/lib/i18n/pt-BR.json+++ b/src/lib/i18n/pt-BR.json@@ -1401,5 +1401,86 @@"licenses.validate": "Validar licença","licenses.deactivateShort": "Desativar","licenses.activating": "Ativando...",- "licenses.activate": "Ativar"+ "licenses.activate": "Ativar",+ "activity.title": "Atividade",+ "activity.description": "Atividade de login e logout nas contas de usuário.",+ "activity.col.activity": "Atividade",+ "activity.col.user": "Usuário",+ "activity.col.device": "Dispositivo",+ "activity.col.time": "Hora",+ "activity.none": "Nenhuma atividade de login ou logout ainda",+ "activity.login": "Login",+ "activity.logout": "Logout",+ "activity.unknownEmail": "(e-mail desconhecido)",+ "activity.unknownCity": "(cidade desconhecida)",+ "activity.unknownCountry": "(país desconhecido)",+ "activity.unknownDevice": "(dispositivo desconhecido)",+ "activity.unknownPlatform": "(plataforma desconhecida)",+ "activity.unknownIp": "(IP desconhecido)",+ "agentAdmin.loadFailed": "Não foi possível carregar as configurações do agente",+ "agentAdmin.enterUrl": "Digite uma URL base HTTPS para carregar os modelos.",+ "agentAdmin.enterKey": "Digite uma chave de API para carregar os modelos.",+ "agentAdmin.modelsFailed": "Não foi possível carregar os modelos",+ "agentAdmin.saved": "Provedor do agente salvo. As configurações do assistente agora podem escolher entre estes modelos.",+ "agentAdmin.saveFailed": "Não foi possível salvar as configurações do agente",+ "agentAdmin.title": "Agente",+ "agentAdmin.description": "Escolha o provedor de IA e os modelos usados pelo assistente de e-mail para conversas e rascunhos.",+ "agentAdmin.viewUsage": "Ver uso",+ "agentAdmin.enable": "Ativar assistente",+ "agentAdmin.enableHint": "Mostrar o chat do assistente e permitir rascunhos automáticos para todos.",+ "agentAdmin.availabilityFailed": "Não foi possível atualizar a disponibilidade do assistente",+ "agentAdmin.provider": "Provedor de IA",+ "agentAdmin.providerWarning": "O conteúdo dos e-mails é enviado ao provedor selecionado quando alguém usa o assistente. O envio de um rascunho ainda exige aprovação humana.",+ "agentAdmin.providerLabel": "Provedor",+ "agentAdmin.cloudflareAi": "Cloudflare Workers AI",+ "agentAdmin.openaiCompatible": "Provedor compatível com OpenAI",+ "agentAdmin.needsBinding": "O Cloudflare Workers AI exige um binding de AI nesta instalação.",+ "agentAdmin.template": "Modelo de provedor",+ "agentAdmin.baseUrl": "URL base da API",+ "agentAdmin.apiKey": "Chave de API",+ "agentAdmin.savedKeyPlaceholder": "Chave salva (deixe em branco para manter)",+ "agentAdmin.enterKeyPlaceholder": "Digite a chave de API",+ "agentAdmin.keySaved": "Uma chave de API está salva no servidor. Digite uma nova para substituí-la.",+ "agentAdmin.keyNote": "A chave de API fica armazenada no servidor e nunca é exibida novamente.",+ "agentAdmin.models": "Modelos",+ "agentAdmin.loadingModels": "Carregando modelos…",+ "agentAdmin.modelsUnavailable": "Modelos indisponíveis",+ "agentAdmin.suggested": "Mostrando modelos sugeridos da Cloudflare porque um catálogo completo não está disponível.",+ "agentAdmin.orEnterIds": "Ou digite IDs de modelos (separados por vírgula)",+ "agentAdmin.toolCalling": "Escolha modelos que ofereçam chamada de ferramentas para que o assistente possa ler e-mails e criar rascunhos. O primeiro modelo é o padrão.",+ "agentAdmin.rates": "Taxas de custo estimadas",+ "agentAdmin.ratesHint": "USD por 1 milhão de tokens. As taxas publicadas pelo provedor são usadas automaticamente; digite-as você mesmo para modelos que não publicam nenhuma. O uso sem as duas taxas mostra o gasto como indisponível.",+ "agentAdmin.rateLine": "Entrada US$ {input} · Saída US$ {output} / 1M",+ "agentAdmin.fromProvider": "(do provedor)",+ "agentAdmin.input": "Entrada",+ "agentAdmin.output": "Saída",+ "agentAdmin.usdPerM": "USD / 1M",+ "agentAdmin.save": "Salvar configurações do agente",+ "aiUsage.loadFailed": "Não foi possível carregar o uso de IA",+ "aiUsage.pageFailed": "Não foi possível carregar a página de uso",+ "aiUsage.title": "Uso de IA",+ "aiUsage.description": "Solicitações registradas desde que o rastreamento de uso foi adicionado.",+ "aiUsage.back": "Voltar ao Agente",+ "aiUsage.totalTokens": "Total de tokens",+ "aiUsage.totalRequests": "Total de solicitações",+ "aiUsage.spend": "Gasto estimado",+ "aiUsage.noRate": "{count} solicitações não têm taxa.",+ "aiUsage.col.dateTime": "Data e hora",+ "aiUsage.col.model": "Modelo",+ "aiUsage.col.provider": "Provedor",+ "aiUsage.col.input": "Tokens de entrada",+ "aiUsage.col.output": "Tokens de saída",+ "aiUsage.col.spending": "Gasto",+ "aiUsage.none": "Nenhum uso de IA registrado ainda.",+ "aiUsage.loading": "Carregando uso…",+ "aiUsage.pageOf": "Página {page} de {total} · {size} por página",+ "aiUsage.previous": "Anterior",+ "aiUsage.next": "Próxima",+ "aiUsage.note": "O gasto é estimado a partir das taxas por modelo salvas nas configurações do Agente. Um traço significa que nenhuma taxa ou contagem de tokens estava disponível.",+ "aiUsage.byDay": "Uso por dia",+ "aiUsage.chartHint": "Tokens de entrada e saída nos últimos 30 dias ({zone})",+ "aiUsage.legendInput": "Entrada",+ "aiUsage.legendOutput": "Saída",+ "aiUsage.chartLabel": "Uso diário de tokens de IA nos últimos 30 dias",+ "aiUsage.barTitle": "{day}: {tokens} tokens, {requests} solicitações"}