"use client";
import { useEffect, useMemo, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowDown,
ArrowUp,
Loader2,
PlusCircle,
RefreshCw,
RotateCcw,
Save,
Sparkles,
Trash2,
X,
} from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { PasswordInput } from "@/components/settings/password-input";
import { useAuth } from "@/hooks/use-auth";
import { formatDateTime } from "@/lib/format";
import { useTranslations } from "@/lib/i18n/context";
interface InsightsSettings {
codexStatus: string;
codexConnectedAt: string | null;
hasAdminKey: boolean;
/** True when the operator has set `CODEX_OAUTH_CLIENT_ID` on this
* instance. The UI hides the "Connect with ChatGPT" button when
* false to avoid the v1.4.2 dead-end where the click bounced the
* user to chatgpt.com without any OAuth flow. */
codexOauthConfigured?: boolean;
privacyMode: string;
lastInsightAt: string | null;
}
interface UserAIProvider {
provider: string | null;
model: string | null;
baseUrl: string | null;
hasAnthropicKey: boolean;
anthropicKeyPreview: string | null;
hasLocalKey: boolean;
hasOpenaiKey: boolean;
openaiKeyPreview: string | null;
}
/**
* v1.4.16 phase B2 — provider tags exposed to the UI. Mirrors
* `PROVIDER_CHAIN_TYPES` server-side; kept as a const-array here to
* avoid pulling a server-only module into the client bundle.
*/
const PROVIDER_TYPES = [
"codex",
"openai",
"anthropic",
"local",
"admin-openai",
] as const;
type ProviderType = (typeof PROVIDER_TYPES)[number];
interface ChainEntry {
providerType: ProviderType;
enabled: boolean;
}
interface ProviderChainData {
activeProvider: ProviderType | null;
cachedActiveProvider: ProviderType | null;
configuredChain: { providerType: ProviderType; available: boolean }[];
}
const DEFAULT_CHAIN: readonly ChainEntry[] = [
{ providerType: "codex", enabled: true },
{ providerType: "openai", enabled: true },
{ providerType: "anthropic", enabled: true },
{ providerType: "local", enabled: true },
{ providerType: "admin-openai", enabled: true },
];
/**
* OpenAI model presets — the wire-up keeps users out of the freetext
* box for the common case. The `__custom__` sentinel surfaces a
* freetext input so power users can target preview models or
* fine-tunes (e.g. `gpt-5`, which is admitted via the env override on
* the Codex backend but not yet a documented OpenAI model id).
*/
const OPENAI_MODEL_PRESETS = [
"gpt-4o",
"gpt-4o-mini",
"gpt-4-turbo",
] as const;
const ANTHROPIC_MODEL_PRESETS = [
"claude-sonnet-4-6",
"claude-opus-4-7",
"claude-haiku-4-5",
"claude-3-5-sonnet-latest",
] as const;
const LOCAL_MODEL_PRESETS = [
"llama3.1:8b",
"llama3.1:70b",
"mistral",
"qwen2.5",
] as const;
const CUSTOM_MODEL_SENTINEL = "__custom__";
/**
* Map UI provider tag → the `aiProvider` enum understood by the
* legacy single-result `resolveProvider()` resolver. `codex` and
* `admin-openai` aren't user-level provider columns (they're handled
* by Codex OAuth + admin-key fallback), so they map to null and the
* legacy column is left blank.
*/
function uiToLegacyProviderEnum(p: ProviderType): string | null {
switch (p) {
case "openai":
return "OPENAI";
case "anthropic":
return "ANTHROPIC";
case "local":
return "LOCAL";
case "codex":
case "admin-openai":
default:
return null;
}
}
export function AiSection() {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
return (
{t("settings.sections.ai.title")}
{t("settings.sections.ai.description")}
);
}
/**
* The single dropdown-driven configuration card. Replaces the
* v1.4.15-vintage two-card layout (Codex connect at the top, personal
* provider form at the bottom) per Marc's
* `feedback_settings_no_split.md`: one provider Select, one matching
* form below, one fallback-chain card at the bottom.
*
* The active-provider Select is URL-synced via `?provider=…` so deep
* links to a specific config form work, the SSR test can drive the
* branch deterministically, and a refresh keeps the user on the form
* they were editing.
*/
function AiInsightsCard({ isAuthenticated }: { isAuthenticated: boolean }) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const { data: insightsSettings } = useQuery({
queryKey: ["insights", "settings"],
queryFn: async () => {
const res = await fetch("/api/insights/settings");
if (!res.ok) return null;
const json = await res.json();
return json.data as InsightsSettings;
},
enabled: isAuthenticated,
});
const { data: userProvider } = useQuery({
queryKey: ["user", "ai-provider"],
queryFn: async () => {
const res = await fetch("/api/user/ai-provider");
if (!res.ok) return null;
const json = await res.json();
return json.data as UserAIProvider;
},
enabled: isAuthenticated,
});
const { data: chainData } = useQuery({
queryKey: ["insights", "provider-chain"],
queryFn: async () => {
const res = await fetch("/api/insights/provider-chain");
if (!res.ok) return null;
const json = await res.json();
return json.data as ProviderChainData;
},
enabled: isAuthenticated,
});
// The Select is URL-driven so the SSR test can pick the branch and
// a deep link works. Default = `?provider=…` query param when the
// user navigated here intentionally, else the chain's active entry,
// else "codex". The seed-on-data-arrival pattern below avoids
// setState-in-effect (lint rule `react-hooks/set-state-in-effect`)
// by reading the resolved value at render time and consulting a
// `seededFor` marker so we only re-seed when the relevant inputs
// actually changed.
const queryProvider = searchParams?.get("provider") ?? null;
const [selectedProvider, setSelectedProvider] = useState(() =>
isProviderType(queryProvider) ? queryProvider : "codex",
);
const seedKey = `${queryProvider ?? ""}|${chainData?.activeProvider ?? ""}`;
const [seededFor, setSeededFor] = useState(seedKey);
if (seedKey !== seededFor) {
setSeededFor(seedKey);
if (isProviderType(queryProvider)) {
setSelectedProvider(queryProvider);
} else if (chainData?.activeProvider) {
setSelectedProvider(chainData.activeProvider);
}
}
function pickProvider(next: ProviderType) {
setSelectedProvider(next);
if (typeof window === "undefined") return;
const params = new URLSearchParams(searchParams?.toString() ?? "");
params.set("provider", next);
router.replace(`${pathname}?${params.toString()}`);
}
return (