AiSettingsForm.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. "use client";
  2. import { useState, useTransition, useEffect, useCallback } from "react";
  3. import { useTranslations } from "next-intl";
  4. import { useRouter } from "next/navigation";
  5. import { toast } from "sonner";
  6. import { Input } from "@/components/ui/input";
  7. import { Button } from "@/components/ui/button";
  8. import { Label } from "@/components/ui/label";
  9. import { Switch } from "@/components/ui/switch";
  10. import { Badge } from "@/components/ui/badge";
  11. import { AppCard } from "@/components/app-card";
  12. import {
  13. Select,
  14. SelectContent,
  15. SelectItem,
  16. SelectTrigger,
  17. SelectValue,
  18. } from "@/components/ui/select";
  19. import { Info, Loader2, Sparkles, Zap } from "lucide-react";
  20. import {
  21. AI_KEYS,
  22. AI_PROVIDERS,
  23. OPENAI_FALLBACK_MODELS,
  24. ANTHROPIC_FALLBACK_MODELS,
  25. type AiProvider,
  26. type AiModel,
  27. } from "../Schema/aiSettingsSchema";
  28. import { setAiSettings, fetchAiModels } from "../Actions/aiSettingsActions";
  29. import { aiTestConnection } from "../Actions/aiActions";
  30. import {
  31. ReadOnlyBanner,
  32. SaveButton,
  33. ReadOnlyWrapper,
  34. } from "@/app/(authenticated)/settings/read-only-guard";
  35. const COST_COLORS: Record<AiModel["cost"], string> = {
  36. high: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
  37. medium: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
  38. low: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
  39. };
  40. export function AiSettingsForm({
  41. initial,
  42. }: {
  43. initial: Record<string, string>;
  44. }) {
  45. const t = useTranslations("settings");
  46. const router = useRouter();
  47. const [isPending, startTransition] = useTransition();
  48. const [isTesting, setIsTesting] = useState(false);
  49. const hasConfig = !!initial[AI_KEYS.AI_API_KEY];
  50. const [enabled, setEnabled] = useState(
  51. initial[AI_KEYS.AI_ENABLED] === "true" || false,
  52. );
  53. const [provider, setProvider] = useState<AiProvider>(
  54. (initial[AI_KEYS.AI_PROVIDER] as AiProvider) || "openai",
  55. );
  56. const [apiKey, setApiKey] = useState(initial[AI_KEYS.AI_API_KEY] || "");
  57. const [model, setModel] = useState(
  58. initial[AI_KEYS.AI_MODEL] || "gpt-4o-mini",
  59. );
  60. const [models, setModels] = useState<AiModel[]>(
  61. provider === "anthropic" ? ANTHROPIC_FALLBACK_MODELS : OPENAI_FALLBACK_MODELS,
  62. );
  63. const [fetchingModels, setFetchingModels] = useState(false);
  64. const loadModels = useCallback(async (p: AiProvider) => {
  65. setFetchingModels(true);
  66. try {
  67. const result = await fetchAiModels(p);
  68. if (result.success && result.data && result.data.length > 0) {
  69. setModels(result.data);
  70. } else {
  71. setModels(p === "anthropic" ? ANTHROPIC_FALLBACK_MODELS : OPENAI_FALLBACK_MODELS);
  72. }
  73. } catch {
  74. setModels(p === "anthropic" ? ANTHROPIC_FALLBACK_MODELS : OPENAI_FALLBACK_MODELS);
  75. } finally {
  76. setFetchingModels(false);
  77. }
  78. }, []);
  79. // Fetch models on mount if API key is configured (hasConfig means key exists in DB)
  80. useEffect(() => {
  81. if (hasConfig) {
  82. loadModels(provider);
  83. }
  84. // eslint-disable-next-line react-hooks/exhaustive-deps
  85. }, []);
  86. const handleProviderChange = (value: string) => {
  87. const p = value as AiProvider;
  88. setProvider(p);
  89. const fallback = p === "anthropic" ? ANTHROPIC_FALLBACK_MODELS : OPENAI_FALLBACK_MODELS;
  90. setModels(fallback);
  91. setModel(fallback[0].id);
  92. if (hasConfig) {
  93. loadModels(p);
  94. }
  95. };
  96. const handleApiKeyBlur = () => {
  97. // After saving a new key, models can be refreshed
  98. // But we don't send the key to the server from here — it reads from DB
  99. };
  100. const handleSave = () => {
  101. startTransition(async () => {
  102. const data: Record<string, string> = {
  103. [AI_KEYS.AI_ENABLED]: enabled ? "true" : "false",
  104. [AI_KEYS.AI_PROVIDER]: provider,
  105. [AI_KEYS.AI_API_KEY]: apiKey,
  106. [AI_KEYS.AI_MODEL]: model,
  107. };
  108. const result = await setAiSettings(data);
  109. if (result.success) {
  110. toast.success(t("ai.saved"));
  111. router.refresh();
  112. } else {
  113. toast.error(result.error ?? t("ai.failedSave"));
  114. }
  115. });
  116. };
  117. const handleTestConnection = async () => {
  118. setIsTesting(true);
  119. try {
  120. const result = await aiTestConnection();
  121. if (result.success && result.data) {
  122. toast.success(t("ai.testSuccess"));
  123. } else {
  124. toast.error(result.error ?? t("ai.testFailed"));
  125. }
  126. } catch (err) {
  127. toast.error(
  128. err instanceof Error ? err.message : t("ai.testFailed"),
  129. );
  130. } finally {
  131. setIsTesting(false);
  132. }
  133. };
  134. const canTest = enabled && apiKey && model;
  135. return (
  136. <div className="space-y-6">
  137. <ReadOnlyBanner />
  138. <ReadOnlyWrapper>
  139. <AppCard
  140. icon={Sparkles}
  141. title={t("ai.title")}
  142. description={t("ai.description")}
  143. action={
  144. <a
  145. href="https://torqvoice.com/docs/integrations/ai"
  146. target="_blank"
  147. rel="noopener noreferrer"
  148. className="text-[11px] text-muted-foreground transition-colors hover:text-foreground"
  149. >
  150. {t("ai.readMore")} →
  151. </a>
  152. }
  153. contentClassName="space-y-6"
  154. >
  155. <div className="flex items-center justify-between">
  156. <div className="space-y-0.5">
  157. <Label htmlFor="enable-ai">{t("ai.enableLabel")}</Label>
  158. <p className="text-xs text-muted-foreground">
  159. {t("ai.enableHint")}
  160. </p>
  161. </div>
  162. <Switch
  163. id="enable-ai"
  164. checked={enabled}
  165. onCheckedChange={setEnabled}
  166. />
  167. </div>
  168. {!enabled && (
  169. <div className="flex items-start gap-3 rounded-lg border bg-muted/50 p-4">
  170. <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
  171. <p className="text-sm text-muted-foreground">
  172. {t("ai.disabledInfo")}
  173. </p>
  174. </div>
  175. )}
  176. {enabled && (
  177. <>
  178. {/* Provider selection */}
  179. <div className="space-y-2">
  180. <Label>{t("ai.provider")}</Label>
  181. <div className="flex flex-wrap gap-2">
  182. {AI_PROVIDERS.map((p) => (
  183. <Button
  184. key={p}
  185. type="button"
  186. variant={provider === p ? "default" : "outline"}
  187. onClick={() => handleProviderChange(p)}
  188. className="flex-1"
  189. >
  190. {p === "openai" ? "OpenAI" : "Anthropic"}
  191. </Button>
  192. ))}
  193. </div>
  194. </div>
  195. {/* API Key */}
  196. <div className="space-y-2">
  197. <Label htmlFor="ai-api-key">{t("ai.apiKey")}</Label>
  198. <Input
  199. id="ai-api-key"
  200. type="password"
  201. placeholder={
  202. provider === "openai"
  203. ? "sk-••••••••••••••••••••••••••••••••"
  204. : "sk-ant-••••••••••••••••••••••••••"
  205. }
  206. value={apiKey}
  207. onChange={(e) => setApiKey(e.target.value)}
  208. onBlur={handleApiKeyBlur}
  209. />
  210. <p className="text-xs text-muted-foreground">
  211. {t("ai.apiKeyHint", {
  212. provider: provider === "openai" ? "OpenAI" : "Anthropic",
  213. })}
  214. </p>
  215. </div>
  216. {/* Model selection */}
  217. <div className="space-y-2">
  218. <div className="flex items-center gap-2">
  219. <Label htmlFor="ai-model">{t("ai.model")}</Label>
  220. {fetchingModels && (
  221. <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
  222. )}
  223. </div>
  224. <Select value={model} onValueChange={setModel}>
  225. <SelectTrigger>
  226. <SelectValue />
  227. </SelectTrigger>
  228. <SelectContent>
  229. {models.map((m) => (
  230. <SelectItem key={m.id} value={m.id}>
  231. <span className="flex items-center gap-2">
  232. {m.label}
  233. <Badge
  234. variant="outline"
  235. className={`ml-1 text-[10px] px-1.5 py-0 font-medium ${COST_COLORS[m.cost]}`}
  236. >
  237. {t(`ai.cost.${m.cost}`)}
  238. </Badge>
  239. </span>
  240. </SelectItem>
  241. ))}
  242. </SelectContent>
  243. </Select>
  244. </div>
  245. {/* Test connection */}
  246. {hasConfig && (
  247. <div className="pt-2">
  248. <Button
  249. type="button"
  250. variant="outline"
  251. onClick={handleTestConnection}
  252. disabled={!canTest || isTesting}
  253. >
  254. {isTesting ? (
  255. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  256. ) : (
  257. <Zap className="mr-2 h-4 w-4" />
  258. )}
  259. {t("ai.testConnection")}
  260. </Button>
  261. </div>
  262. )}
  263. {/* Features info */}
  264. <div className="rounded-lg border bg-muted/30 p-4 space-y-2">
  265. <p className="text-sm font-medium">{t("ai.featuresTitle")}</p>
  266. <ul className="text-sm text-muted-foreground space-y-1">
  267. <li>• {t("ai.featureServiceNotes")}</li>
  268. <li>• {t("ai.featureHistorySummary")}</li>
  269. </ul>
  270. </div>
  271. </>
  272. )}
  273. </AppCard>
  274. <SaveButton>
  275. <div className="flex justify-end">
  276. <Button onClick={handleSave} disabled={isPending}>
  277. {isPending && (
  278. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  279. )}
  280. {t("ai.saveSettings")}
  281. </Button>
  282. </div>
  283. </SaveButton>
  284. </ReadOnlyWrapper>
  285. </div>
  286. );
  287. }