Files
PocketVeto/frontend/app/settings/page.tsx
Jack Levy defc2c116d fix(admin): LLM provider/model switching now reads DB overrides correctly
- get_llm_provider() now accepts provider + model args so DB overrides
  propagate through to all provider constructors (was always reading
  env vars, ignoring the admin UI selection)
- /test-llm replaced with lightweight ping (max_tokens=20) instead of
  running a full bill analysis; shows model name + reply, no truncation
- /api/settings/llm-models endpoint fetches available models live from
  each provider's API (OpenAI, Anthropic REST, Gemini, Ollama)
- Admin UI model picker dynamically populated from provider API;
  falls back to manual text input on error; Custom model name option kept
- Default Gemini model updated: gemini-1.5-pro → gemini-2.0-flash

Co-Authored-By: Jack Levy
2026-03-01 04:03:51 -05:00

611 lines
26 KiB
TypeScript

"use client";
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
Settings,
Cpu,
RefreshCw,
CheckCircle,
XCircle,
Play,
Users,
Trash2,
ShieldCheck,
ShieldOff,
FileText,
Brain,
BarChart3,
Bell,
Copy,
Rss,
} from "lucide-react";
import { settingsAPI, adminAPI, notificationsAPI, type AdminUser, type LLMModel } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
const LLM_PROVIDERS = [
{ value: "openai", label: "OpenAI", hint: "Requires OPENAI_API_KEY in .env" },
{ value: "anthropic", label: "Anthropic (Claude)", hint: "Requires ANTHROPIC_API_KEY in .env" },
{ value: "gemini", label: "Google Gemini", hint: "Requires GEMINI_API_KEY in .env" },
{ value: "ollama", label: "Ollama (Local)", hint: "Requires Ollama running on host" },
];
export default function SettingsPage() {
const qc = useQueryClient();
const currentUser = useAuthStore((s) => s.user);
const { data: settings, isLoading: settingsLoading } = useQuery({
queryKey: ["settings"],
queryFn: () => settingsAPI.get(),
});
const { data: stats } = useQuery({
queryKey: ["admin-stats"],
queryFn: () => adminAPI.getStats(),
enabled: !!currentUser?.is_admin,
refetchInterval: 30_000,
});
const { data: users, isLoading: usersLoading } = useQuery({
queryKey: ["admin-users"],
queryFn: () => adminAPI.listUsers(),
enabled: !!currentUser?.is_admin,
});
const updateSetting = useMutation({
mutationFn: ({ key, value }: { key: string; value: string }) => settingsAPI.update(key, value),
onSuccess: () => qc.invalidateQueries({ queryKey: ["settings"] }),
});
const deleteUser = useMutation({
mutationFn: (id: number) => adminAPI.deleteUser(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
});
const toggleAdmin = useMutation({
mutationFn: (id: number) => adminAPI.toggleAdmin(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
});
const { data: notifSettings, refetch: refetchNotif } = useQuery({
queryKey: ["notification-settings"],
queryFn: () => notificationsAPI.getSettings(),
});
const updateNotif = useMutation({
mutationFn: (data: Parameters<typeof notificationsAPI.updateSettings>[0]) =>
notificationsAPI.updateSettings(data),
onSuccess: () => refetchNotif(),
});
const resetRss = useMutation({
mutationFn: () => notificationsAPI.resetRssToken(),
onSuccess: () => refetchNotif(),
});
const [ntfyUrl, setNtfyUrl] = useState("");
const [ntfyToken, setNtfyToken] = useState("");
const [notifSaved, setNotifSaved] = useState(false);
const [copied, setCopied] = useState(false);
// Live model list from provider API
const { data: modelsData, isFetching: modelsFetching, refetch: refetchModels } = useQuery({
queryKey: ["llm-models", settings?.llm_provider],
queryFn: () => settingsAPI.listModels(settings!.llm_provider),
enabled: !!currentUser?.is_admin && !!settings?.llm_provider,
staleTime: 5 * 60 * 1000,
retry: false,
});
const liveModels: LLMModel[] = modelsData?.models ?? [];
const modelsError: string | undefined = modelsData?.error;
// Model picker state
const [showCustomModel, setShowCustomModel] = useState(false);
const [customModel, setCustomModel] = useState("");
useEffect(() => {
if (!settings || modelsFetching) return;
const inList = liveModels.some((m) => m.id === settings.llm_model);
if (!inList && settings.llm_model) {
setShowCustomModel(true);
setCustomModel(settings.llm_model);
} else {
setShowCustomModel(false);
setCustomModel("");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [settings?.llm_provider, settings?.llm_model, modelsFetching]);
const [testResult, setTestResult] = useState<{
status: string;
detail?: string;
reply?: string;
provider?: string;
model?: string;
} | null>(null);
const [testing, setTesting] = useState(false);
const [taskIds, setTaskIds] = useState<Record<string, string>>({});
const [confirmDelete, setConfirmDelete] = useState<number | null>(null);
const testLLM = async () => {
setTesting(true);
setTestResult(null);
try {
const result = await settingsAPI.testLLM();
setTestResult(result);
} catch (e: unknown) {
setTestResult({ status: "error", detail: e instanceof Error ? e.message : String(e) });
} finally {
setTesting(false);
}
};
const trigger = async (name: string, fn: () => Promise<{ task_id: string }>) => {
const result = await fn();
setTaskIds((prev) => ({ ...prev, [name]: result.task_id }));
};
if (settingsLoading) return <div className="text-center py-20 text-muted-foreground">Loading...</div>;
if (!currentUser?.is_admin) {
return <div className="text-center py-20 text-muted-foreground">Admin access required.</div>;
}
const pct = stats && stats.total_bills > 0
? Math.round((stats.briefs_generated / stats.total_bills) * 100)
: 0;
return (
<div className="space-y-8 max-w-2xl">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Settings className="w-5 h-5" /> Admin
</h1>
<p className="text-muted-foreground text-sm mt-1">Manage users, LLM provider, and system settings</p>
</div>
{/* Analysis Status */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<BarChart3 className="w-4 h-4" /> Analysis Status
<span className="text-xs text-muted-foreground font-normal ml-auto">refreshes every 30s</span>
</h2>
{stats ? (
<>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="bg-muted/50 rounded-lg p-3 text-center">
<FileText className="w-4 h-4 mx-auto mb-1 text-muted-foreground" />
<div className="text-xl font-bold">{stats.total_bills.toLocaleString()}</div>
<div className="text-xs text-muted-foreground">Total Bills</div>
</div>
<div className="bg-muted/50 rounded-lg p-3 text-center">
<FileText className="w-4 h-4 mx-auto mb-1 text-blue-500" />
<div className="text-xl font-bold">{stats.docs_fetched.toLocaleString()}</div>
<div className="text-xs text-muted-foreground">Docs Fetched</div>
</div>
<div className="bg-muted/50 rounded-lg p-3 text-center">
<Brain className="w-4 h-4 mx-auto mb-1 text-green-500" />
<div className="text-xl font-bold">{stats.briefs_generated.toLocaleString()}</div>
<div className="text-xs text-muted-foreground">Briefs Generated</div>
</div>
</div>
{/* Progress bar */}
<div className="space-y-1">
<div className="flex justify-between text-xs text-muted-foreground">
<span>{stats.full_briefs} full · {stats.amendment_briefs} amendments</span>
<span>{pct}% analyzed · {stats.remaining.toLocaleString()} remaining</span>
</div>
<div className="h-2 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-green-500 rounded-full transition-all duration-500"
style={{ width: `${pct}%` }}
/>
</div>
{stats.uncited_briefs > 0 && (
<p className="text-xs text-amber-600 dark:text-amber-400">
{stats.uncited_briefs.toLocaleString()} brief{stats.uncited_briefs !== 1 ? "s" : ""} missing citations run Backfill Citations to fix
</p>
)}
</div>
</>
) : (
<p className="text-sm text-muted-foreground">Loading stats...</p>
)}
</section>
{/* User Management */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<Users className="w-4 h-4" /> Users
</h2>
{usersLoading ? (
<p className="text-sm text-muted-foreground">Loading users...</p>
) : (
<div className="divide-y divide-border">
{(users ?? []).map((u: AdminUser) => (
<div key={u.id} className="flex items-center justify-between py-3 gap-4">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate">{u.email}</span>
{u.is_admin && (
<span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded font-medium">
admin
</span>
)}
{u.id === currentUser.id && (
<span className="text-xs text-muted-foreground">(you)</span>
)}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{u.follow_count} follow{u.follow_count !== 1 ? "s" : ""} ·{" "}
joined {new Date(u.created_at).toLocaleDateString()}
</div>
</div>
{u.id !== currentUser.id && (
<div className="flex items-center gap-2 shrink-0">
<button
onClick={() => toggleAdmin.mutate(u.id)}
disabled={toggleAdmin.isPending}
title={u.is_admin ? "Remove admin" : "Make admin"}
className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
>
{u.is_admin ? <ShieldOff className="w-4 h-4" /> : <ShieldCheck className="w-4 h-4" />}
</button>
{confirmDelete === u.id ? (
<div className="flex items-center gap-1">
<button
onClick={() => { deleteUser.mutate(u.id); setConfirmDelete(null); }}
className="text-xs px-2 py-1 bg-destructive text-destructive-foreground rounded hover:bg-destructive/90"
>
Confirm
</button>
<button
onClick={() => setConfirmDelete(null)}
className="text-xs px-2 py-1 bg-muted rounded hover:bg-accent"
>
Cancel
</button>
</div>
) : (
<button
onClick={() => setConfirmDelete(u.id)}
title="Delete user"
className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-accent transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
)}
</div>
)}
</div>
))}
</div>
)}
</section>
{/* LLM Provider */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<Cpu className="w-4 h-4" /> LLM Provider
</h2>
<div className="space-y-2">
{LLM_PROVIDERS.map(({ value, label, hint }) => (
<label key={value} className="flex items-start gap-3 cursor-pointer">
<input
type="radio"
name="provider"
value={value}
checked={settings?.llm_provider === value}
onChange={() => {
updateSetting.mutate({ key: "llm_provider", value });
setShowCustomModel(false);
setCustomModel("");
}}
className="mt-0.5"
/>
<div>
<div className="text-sm font-medium">{label}</div>
<div className="text-xs text-muted-foreground">{hint}</div>
</div>
</label>
))}
</div>
{/* Model picker — live from provider API */}
<div className="space-y-2 pt-3 border-t border-border">
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Model</label>
{modelsFetching && <span className="text-xs text-muted-foreground">Loading models</span>}
{modelsError && !modelsFetching && (
<span className="text-xs text-amber-600 dark:text-amber-400">{modelsError}</span>
)}
{!modelsFetching && liveModels.length > 0 && (
<button onClick={() => refetchModels()} className="text-xs text-muted-foreground hover:text-foreground transition-colors">
Refresh
</button>
)}
</div>
{liveModels.length > 0 ? (
<select
value={showCustomModel ? "__custom__" : (settings?.llm_model ?? "")}
onChange={(e) => {
if (e.target.value === "__custom__") {
setShowCustomModel(true);
setCustomModel(settings?.llm_model ?? "");
} else {
setShowCustomModel(false);
setCustomModel("");
updateSetting.mutate({ key: "llm_model", value: e.target.value });
}
}}
className="w-full px-3 py-1.5 text-sm bg-background border border-border rounded-md"
>
{liveModels.map((m) => (
<option key={m.id} value={m.id}>{m.name !== m.id ? `${m.name} (${m.id})` : m.id}</option>
))}
<option value="__custom__">Custom model name</option>
</select>
) : (
!modelsFetching && (
<p className="text-xs text-muted-foreground">
{modelsError ? "Could not fetch models — enter a model name manually below." : "No models found."}
</p>
)
)}
{(showCustomModel || (liveModels.length === 0 && !modelsFetching)) && (
<div className="flex gap-2">
<input
type="text"
placeholder="e.g. gpt-4o or gemini-2.0-flash"
value={customModel}
onChange={(e) => setCustomModel(e.target.value)}
className="flex-1 px-3 py-1.5 text-sm bg-background border border-border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
/>
<button
onClick={() => {
if (customModel.trim()) updateSetting.mutate({ key: "llm_model", value: customModel.trim() });
}}
disabled={!customModel.trim() || updateSetting.isPending}
className="px-3 py-1.5 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50"
>
Save
</button>
</div>
)}
<p className="text-xs text-muted-foreground">
Active: <strong>{settings?.llm_provider}</strong> / <strong>{settings?.llm_model}</strong>
</p>
</div>
<div className="flex items-center gap-3 pt-2 border-t border-border">
<button
onClick={testLLM}
disabled={testing}
className="flex items-center gap-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 transition-colors"
>
<Play className="w-3.5 h-3.5" />
{testing ? "Testing..." : "Test Connection"}
</button>
{testResult && (
<div className="flex items-center gap-2 text-sm">
{testResult.status === "ok" ? (
<>
<CheckCircle className="w-4 h-4 text-green-500" />
<span className="text-green-600 dark:text-green-400">
{testResult.model} {testResult.reply}
</span>
</>
) : (
<>
<XCircle className="w-4 h-4 text-red-500" />
<span className="text-red-600 dark:text-red-400">{testResult.detail}</span>
</>
)}
</div>
)}
</div>
</section>
{/* Data Sources */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<RefreshCw className="w-4 h-4" /> Data Sources
</h2>
<div className="space-y-3 text-sm">
<div className="flex items-center justify-between">
<div>
<div className="font-medium">Congress.gov Poll Interval</div>
<div className="text-xs text-muted-foreground">How often to check for new bills</div>
</div>
<select
value={settings?.congress_poll_interval_minutes}
onChange={(e) => updateSetting.mutate({ key: "congress_poll_interval_minutes", value: e.target.value })}
className="px-3 py-1.5 text-sm bg-background border border-border rounded-md"
>
<option value="15">Every 15 min</option>
<option value="30">Every 30 min</option>
<option value="60">Every hour</option>
<option value="360">Every 6 hours</option>
</select>
</div>
<div className="flex items-center justify-between py-2 border-t border-border">
<div>
<div className="font-medium">NewsAPI.org</div>
<div className="text-xs text-muted-foreground">100 requests/day free tier</div>
</div>
<span className={`text-xs font-medium ${settings?.newsapi_enabled ? "text-green-500" : "text-muted-foreground"}`}>
{settings?.newsapi_enabled ? "Configured" : "Not configured"}
</span>
</div>
<div className="flex items-center justify-between py-2 border-t border-border">
<div>
<div className="font-medium">Google Trends</div>
<div className="text-xs text-muted-foreground">Zeitgeist scoring via pytrends</div>
</div>
<span className={`text-xs font-medium ${settings?.pytrends_enabled ? "text-green-500" : "text-muted-foreground"}`}>
{settings?.pytrends_enabled ? "Enabled" : "Disabled"}
</span>
</div>
</div>
</section>
{/* Notifications */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<Bell className="w-4 h-4" /> Notifications
</h2>
{/* ntfy */}
<div className="space-y-3">
<div>
<label className="text-sm font-medium">ntfy Topic URL</label>
<p className="text-xs text-muted-foreground mb-1.5">
Your ntfy topic use <a href="https://ntfy.sh" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">ntfy.sh</a> (public) or your self-hosted server.
e.g. <code className="bg-muted px-1 rounded text-xs">https://ntfy.sh/your-topic</code>
</p>
<input
type="url"
placeholder="https://ntfy.sh/your-topic"
defaultValue={notifSettings?.ntfy_topic_url ?? ""}
onChange={(e) => setNtfyUrl(e.target.value)}
className="w-full px-3 py-2 text-sm bg-background border border-border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div>
<label className="text-sm font-medium">ntfy Auth Token <span className="text-muted-foreground font-normal">(optional)</span></label>
<p className="text-xs text-muted-foreground mb-1.5">Required only for private/self-hosted topics with access control.</p>
<input
type="password"
placeholder="tk_..."
defaultValue={notifSettings?.ntfy_token ?? ""}
onChange={(e) => setNtfyToken(e.target.value)}
className="w-full px-3 py-2 text-sm bg-background border border-border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div className="flex items-center gap-3 pt-1">
<button
onClick={() => {
updateNotif.mutate({
ntfy_topic_url: ntfyUrl || notifSettings?.ntfy_topic_url || "",
ntfy_token: ntfyToken || notifSettings?.ntfy_token || "",
ntfy_enabled: true,
}, {
onSuccess: () => { setNotifSaved(true); setTimeout(() => setNotifSaved(false), 2000); }
});
}}
disabled={updateNotif.isPending}
className="flex items-center gap-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 transition-colors"
>
{notifSaved ? <CheckCircle className="w-3.5 h-3.5" /> : <Bell className="w-3.5 h-3.5" />}
{notifSaved ? "Saved!" : "Save & Enable"}
</button>
{notifSettings?.ntfy_enabled && (
<button
onClick={() => updateNotif.mutate({ ntfy_enabled: false })}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Disable
</button>
)}
{notifSettings?.ntfy_enabled && (
<span className="flex items-center gap-1 text-xs text-green-600 dark:text-green-400">
<CheckCircle className="w-3 h-3" /> ntfy active
</span>
)}
</div>
</div>
{/* RSS */}
<div className="pt-3 border-t border-border space-y-2">
<div className="flex items-center gap-2">
<Rss className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">RSS Feed</span>
</div>
{notifSettings?.rss_token ? (
<div className="space-y-2">
<div className="flex items-center gap-2">
<code className="flex-1 text-xs bg-muted px-2 py-1.5 rounded truncate">
{`${window.location.origin}/api/notifications/feed/${notifSettings.rss_token}.xml`}
</code>
<button
onClick={() => {
navigator.clipboard.writeText(
`${window.location.origin}/api/notifications/feed/${notifSettings.rss_token}.xml`
);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}}
className="shrink-0 p-1.5 rounded hover:bg-accent transition-colors"
title="Copy RSS URL"
>
{copied ? <CheckCircle className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4 text-muted-foreground" />}
</button>
</div>
<button
onClick={() => resetRss.mutate()}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Regenerate URL (invalidates old link)
</button>
</div>
) : (
<p className="text-xs text-muted-foreground">
Save your ntfy settings above to generate your personal RSS feed URL.
</p>
)}
</div>
</section>
{/* Manual Controls */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold">Manual Controls</h2>
<div className="flex flex-wrap gap-3">
<button
onClick={() => trigger("poll", adminAPI.triggerPoll)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Trigger Poll
</button>
<button
onClick={() => trigger("members", adminAPI.triggerMemberSync)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Sync Members
</button>
<button
onClick={() => trigger("trends", adminAPI.triggerTrendScores)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Calculate Trends
</button>
<button
onClick={() => trigger("sponsors", adminAPI.backfillSponsors)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Backfill Sponsors
</button>
<button
onClick={() => trigger("citations", adminAPI.backfillCitations)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-amber-100 text-amber-800 hover:bg-amber-200 dark:bg-amber-900/30 dark:text-amber-300 dark:hover:bg-amber-900/50 rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Backfill Citations
</button>
<button
onClick={() => trigger("actions", adminAPI.triggerFetchActions)}
className="flex items-center gap-2 px-4 py-2 text-sm bg-muted hover:bg-accent rounded-md transition-colors"
>
<RefreshCw className="w-3.5 h-3.5" /> Fetch Bill Actions
</button>
</div>
{Object.entries(taskIds).map(([name, id]) => (
<p key={name} className="text-xs text-muted-foreground">{name}: task {id} queued</p>
))}
</section>
</div>
);
}