Files
crosscode-platform/apps/events/frontend/src/components/admin/AiTab.tsx
T
joshuaandClaude Opus 5.5 38ebce24ab Events: AI use in tokens, not rand (for 2.3.0); contracts: token fields on the AI status
Site settings → AI, the usage tables and the 80% email show input/output
tokens and the percentage; the rand amounts from the Hub are dropped on
arrival. AiCall stores each call's tokens (migration ai_tokens). v2
/ai/status and /ai/usage carry tokens instead of cents. Needs Hub 2.0.1
for the token figures; older Hubs show the percentage only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:59:36 +02:00

160 lines
9.5 KiB
TypeScript

"use client";
import React, { useEffect, useState } from "react";
import { Sparkles } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { loadAiStatus, renewsText, tokenText } from "@/lib/ai";
import { errorMessage } from "@/lib/utils";
type Usage = V2Result<"/ai/usage", "get">["data"];
type Helper = keyof Usage["settings"]["helpers"];
const HELPERS: { key: Helper; label: string; where: string }[] = [
{ key: "draft_event", label: "Draft an event", where: "New event: describe it and the form is filled in" },
{ key: "summarise_report", label: "Summarise this report", where: "Reports: a few plain-language insights" },
{ key: "draft_message", label: "Draft a message", where: "Emails and WhatsApp messages to attendees, broadcasts" },
{ key: "summarise_feedback", label: "Summarise feedback", where: "Post-event feedback results" },
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
];
/** "12K in · 3K out" for a row of use. */
const inOut = (u: { inputTokens: number; outputTokens: number }) => `${tokenText(u.inputTokens)} in · ${tokenText(u.outputTokens)} out`;
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
export function AiTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [usage, setUsage] = useState<Usage | null>(null);
const [limit, setLimit] = useState("0");
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!active || !token) return;
let alive = true;
apiV2("get", "/ai/usage", { authToken: token })
.then(({ data }) => { if (alive) { setUsage(data); setLimit(String(data.settings.dailyLimitPerPerson)); } })
.catch(e => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load AI use." }); });
return () => { alive = false; };
}, [active, token]);
const save = async (helpers: Partial<Record<Helper, boolean>>, dailyLimitPerPerson?: number) => {
if (!token) return;
setBusy(true);
setMsg(null);
try {
const { data } = await apiV2("put", "/ai/settings", { authToken: token, body: { helpers, ...(dailyLimitPerPerson != null ? { dailyLimitPerPerson } : {}) } });
setUsage(u => (u ? { ...u, settings: data, status: { ...u.status, helpers: data.helpers } } : u));
setMsg({ ok: true, text: "Saved." });
loadAiStatus(token, { fresh: true }).catch(() => {});
} catch (e) { setMsg({ ok: false, text: errorMessage(e) || "Could not save." }); }
setBusy(false);
};
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
const s = usage.status;
const dayTokens = (d: { inputTokens: number; outputTokens: number }) => d.inputTokens + d.outputTokens;
const maxDay = Math.max(1, ...usage.days.map(dayTokens));
const hasTokens = s.usedInputTokens != null && s.usedOutputTokens != null;
const hasCap = s.capInputTokens != null && s.capOutputTokens != null && s.capInputTokens > 0;
return (
<div className="space-y-6">
<div>
<h2 className="flex items-center gap-2 text-lg font-semibold"><Sparkles className="h-5 w-5 text-violet-600" aria-hidden /> AI helpers</h2>
<p className="mt-1 text-sm text-gray-600">
One-click helpers for supervisors and admins: drafting events and messages, improving text, summarising reports and feedback. A person always checks the suggestion before anything is saved or sent.
</p>
</div>
{!s.enabled ? (
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">
AI helpers aren&apos;t part of this site&apos;s licence, so their buttons are hidden. To add them, ask your provider for a monthly AI allowance.
</div>
) : (
<div className="rounded-lg border p-4">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<span className="text-sm font-medium">This month</span>
<span className="text-sm text-gray-600">{s.usedPercent}% used · renews on {renewsText(s.renewsOn)}</span>
</div>
{hasTokens && (
<p className="mt-1 text-sm text-gray-700">
{tokenText(s.usedInputTokens!)} input and {tokenText(s.usedOutputTokens!)} output tokens used
{hasCap && <> of about {tokenText(s.capInputTokens!)} input and {tokenText(s.capOutputTokens!)} output</>}
</p>
)}
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
</div>
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider&apos;s Hub can&apos;t be reached right now, so AI is unavailable. Everything else works as usual.</p>}
<p className="mt-2 text-xs text-gray-500">
Admins get an email when 80% is used.
{hasCap && " The allowance in tokens is an estimate: it's what you'd get if half went on input (what's sent) and half on output (the answers). Repeated instructions are cached and cost less, so most sites get more input than this."}
</p>
</div>
)}
<div>
<h3 className="mb-2 font-medium">Helpers</h3>
<ul className="divide-y rounded-lg border">
{HELPERS.map(h => (
<li key={h.key} className="flex items-center justify-between gap-3 p-3">
<div>
<label htmlFor={`ai-${h.key}`} className="text-sm font-medium">{h.label}</label>
<p className="text-xs text-gray-500">{h.where}</p>
</div>
<input id={`ai-${h.key}`} type="checkbox" className="h-4 w-4" disabled={busy} checked={usage.settings.helpers[h.key]} onChange={e => save({ [h.key]: e.target.checked })} />
</li>
))}
</ul>
</div>
<form className="flex flex-wrap items-end gap-3" onSubmit={e => { e.preventDefault(); save({}, Math.max(0, parseInt(limit, 10) || 0)); }}>
<div>
<label htmlFor="ai-daily-limit" className="block text-sm font-medium">Most uses per person per day</label>
<input id="ai-daily-limit" type="number" min={0} max={1000} className="mt-1 w-28 rounded-lg border px-3 py-2 text-sm" value={limit} onChange={e => setLimit(e.target.value)} />
<p className="mt-1 text-xs text-gray-500">0 = no limit. Guards against one person using up the month.</p>
</div>
<button className="rounded-lg bg-brand-600 px-3 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-60" disabled={busy}>Save limit</button>
</form>
{msg && <p className={`text-sm ${msg.ok ? "text-green-700" : "text-red-700"}`} role="status">{msg.text}</p>}
{s.enabled && (
<div className="grid gap-6 md:grid-cols-2">
<div>
<h3 className="mb-2 font-medium">By person this month</h3>
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{inOut(p)}</td></tr>)}</tbody>
</table>
)}
</div>
<div>
<h3 className="mb-2 font-medium">By helper this month</h3>
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{inOut(h)}</td></tr>)}</tbody>
</table>
)}
</div>
{usage.days.length > 0 && (
<div className="md:col-span-2">
<h3 className="mb-2 font-medium">Per day</h3>
<div className="flex h-20 items-end gap-1" aria-label="AI tokens per day this month">
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${inOut(d)} tokens`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (dayTokens(d) / maxDay) * 100)}%` }} />)}
</div>
</div>
)}
</div>
)}
<p className="text-xs text-gray-500">
Requests go through your provider&apos;s Hub to Anthropic (Claude) in the United States. Only what a helper needs is sent — never names, contact details, medical or children&apos;s information — and nothing is kept by the provider. Add Anthropic to your operator register (Admin → Privacy) when you start using AI.
</p>
</div>
);
}