Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(ai): streamline model service settings

tianma-ifaaf1885abd74
diff --git a/apps/api/src/ai-routes.test.mjs b/apps/api/src/ai-routes.test.mjs
index 2df3a5e8..8621d40a 100644
--- a/apps/api/src/ai-routes.test.mjs
+++ b/apps/api/src/ai-routes.test.mjs
@@ -83,13 +83,13 @@ const createDatabaseEnvironment = () => {
};
};
-const createApp = ({ currentAuth = auth, demoMode = false } = {}) => {
+const createApp = ({ currentAuth = auth, demoMode = false, testConnection } = {}) => {
const app = new Hono();
app.use("/api/v1/*", async (context, next) => {
context.set("auth", currentAuth);
await next();
});
- registerAiRoutes(app, { isDemoMode: () => demoMode });
+ registerAiRoutes(app, { isDemoMode: () => demoMode, testConnection });
return app;
};
@@ -268,6 +268,59 @@ describe("AI route contracts", () => {
sqlite.close();
});
+ test("tests unsaved connection fields without changing the saved provider", async () => {
+ const testedConnections = [];
+ const app = createApp({
+ testConnection: async (config) => {
+ testedConnections.push(config);
+ return { text: "OK" };
+ },
+ });
+ const { sqlite, environment: databaseEnvironment } = createDatabaseEnvironment();
+ const createResponse = await app.request(
+ "/api/v1/ai/providers",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(validSettings),
+ },
+ databaseEnvironment,
+ );
+ const created = await createResponse.json();
+ const provider = created.providers[0];
+
+ const testResponse = await app.request(
+ `/api/v1/ai/providers/${provider.id}/test`,
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ modelId: "draft-model",
+ provider: "google",
+ baseUrl: "https://draft.example.com/v1/",
+ apiKey: "draft-key",
+ }),
+ },
+ databaseEnvironment,
+ );
+
+ expect(testResponse.status).toBe(200);
+ expect(await testResponse.json()).toEqual({ ok: true, response: "OK" });
+ expect(testedConnections).toEqual([{
+ modelId: "draft-model",
+ provider: "google",
+ baseUrl: "https://draft.example.com/v1",
+ apiKey: "draft-key",
+ }]);
+ expect((await app.request("/api/v1/ai/settings", {}, databaseEnvironment).then((response) => response.json())).providers[0])
+ .toMatchObject({
+ provider: validSettings.provider,
+ baseUrl: validSettings.baseUrl,
+ });
+
+ sqlite.close();
+ });
+
test("reports public demo AI settings as read-only", async () => {
const app = createApp({ demoMode: true });
const { sqlite, environment: databaseEnvironment } = createDatabaseEnvironment();
diff --git a/apps/api/src/ai-routes.ts b/apps/api/src/ai-routes.ts
index 5f1cda6b..6c19f3e2 100644
--- a/apps/api/src/ai-routes.ts
+++ b/apps/api/src/ai-routes.ts
@@ -31,6 +31,7 @@ import { encryptSecret } from "./secret-encryption";
type AiRouteDependencies = {
isDemoMode: (environment: Bindings) => boolean;
+ testConnection?: (config: Parameters<typeof testAiModel>[0]) => Promise<{ text: string }>;
};
const providerErrorMessage = (error: unknown) => {
@@ -257,13 +258,16 @@ export const registerAiRoutes = (app: Hono<AppEnv>, dependencies: AiRouteDepende
if (denied) return denied;
try {
const input = context.req.valid("json");
- const { row, apiKey } = await getSavedProviderApiKey(
- context,
+ const row = await getAiProviderConfig(
+ context.env.storage.db,
+ getWorkspaceId(context),
context.req.param("providerConfigId"),
);
- const result = await testAiModel({
- provider: row.provider,
- baseUrl: row.base_url,
+ if (!row) throw new AppError("ai_provider_not_found", "AI provider not found.", 404);
+ const apiKey = input.apiKey ?? await decryptAiCredential(row.api_key_encrypted, context.env);
+ const result = await (dependencies.testConnection ?? testAiModel)({
+ provider: input.provider ?? row.provider,
+ baseUrl: input.baseUrl ? normalizeAiBaseUrl(input.baseUrl) : row.base_url,
apiKey,
modelId: input.modelId,
});
diff --git a/apps/web/src/components/settings/AiModelCard.tsx b/apps/web/src/components/settings/AiModelCard.tsx
index 72087edc..56955bcc 100644
--- a/apps/web/src/components/settings/AiModelCard.tsx
+++ b/apps/web/src/components/settings/AiModelCard.tsx
@@ -1,13 +1,21 @@
import { useState, type FormEvent, type ReactNode } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AiProvider } from "@edgeever/shared";
-import { ChevronDown, Loader2, Plus, Sparkles, TriangleAlert } from "lucide-react";
+import { ChevronDown, Loader2, Plus, Server, Sparkles, TriangleAlert } from "lucide-react";
import { useTranslation } from "react-i18next";
import { AiProviderCard } from "@/components/settings/AiProviderCard";
import { aiErrorMessage, providerDefaults } from "@/components/settings/ai-provider-options";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { api } from "@/lib/api";
@@ -26,6 +34,14 @@ export const AiModelCard = () => {
const [initialModelId, setInitialModelId] = useState(providerDefaults["openai-compatible"].modelId);
const refresh = () => queryClient.invalidateQueries({ queryKey: ["ai-settings"] });
+ const resetAddForm = () => {
+ setProvider("openai-compatible");
+ setDisplayName(providerDefaults["openai-compatible"].displayName);
+ setBaseUrl(providerDefaults["openai-compatible"].baseUrl);
+ setInitialModelId(providerDefaults["openai-compatible"].modelId);
+ setApiKey("");
+ createMutation.reset();
+ };
const createMutation = useMutation({
mutationFn: () => api.createAiProvider({
provider,
@@ -36,8 +52,8 @@ export const AiModelCard = () => {
...(initialModelId.trim() ? { initialModelId: initialModelId.trim() } : {}),
}),
onSuccess: async () => {
- setApiKey("");
setShowAdd(false);
+ setApiKey("");
await refresh();
},
});
@@ -54,14 +70,9 @@ export const AiModelCard = () => {
if (!baseUrl || baseUrl === previous.baseUrl) setBaseUrl(defaults.baseUrl);
if (!initialModelId || initialModelId === previous.modelId) setInitialModelId(defaults.modelId);
};
-
- const resetAddForm = () => {
- setProvider("openai-compatible");
- setDisplayName(providerDefaults["openai-compatible"].displayName);
- setBaseUrl(providerDefaults["openai-compatible"].baseUrl);
- setInitialModelId(providerDefaults["openai-compatible"].modelId);
- setApiKey("");
- createMutation.reset();
+ const handleAddDialogChange = (open: boolean) => {
+ setShowAdd(open);
+ if (!open) resetAddForm();
};
const settings = settingsQuery.data;
@@ -70,7 +81,7 @@ export const AiModelCard = () => {
item.models.map((model) => ({ ...model, providerName: item.displayName, providerEnabled: item.isEnabled }))) ?? [];
const defaultModelAvailable = !settings?.defaultModelId
|| allModels.some((model) => model.id === settings.defaultModelId && model.providerEnabled);
- const error = createMutation.error ?? defaultMutation.error ?? settingsQuery.error;
+ const error = defaultMutation.error ?? settingsQuery.error;
return (
<Collapsible open={expanded} onOpenChange={setExpanded} asChild>
@@ -90,7 +101,7 @@ export const AiModelCard = () => {
</CollapsibleTrigger>
</CardHeader>
<CollapsibleContent asChild>
- <CardContent className="grid gap-4 p-4 pt-0 sm:px-5 sm:pb-5">
+ <CardContent className="grid gap-5 p-4 pt-0 sm:px-5 sm:pb-5">
{settingsQuery.isLoading ? (
<p className="flex items-center gap-2 text-sm text-slate-500"><Loader2 className="h-4 w-4 animate-spin" />{t("common.loading")}</p>
) : (
@@ -101,66 +112,115 @@ export const AiModelCard = () => {
</p>
) : null}
- <Field label={t("aiModel.defaultModel")}>
- <Select
- value={settings?.defaultModelId ?? "none"}
- onValueChange={(value) => defaultMutation.mutate(value === "none" ? null : value)}
- disabled={readOnly || defaultMutation.isPending}
- >
- <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="none">{t("aiModel.noDefaultModel")}</SelectItem>
- {allModels.map((model) => (
- <SelectItem key={model.id} value={model.id} disabled={!model.providerEnabled}>
- {model.providerName} · {model.displayName}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- {!defaultModelAvailable ? (
- <p className="flex items-center gap-2 text-xs text-amber-700"><TriangleAlert className="h-4 w-4" />{t("aiModel.defaultUnavailable")}</p>
- ) : null}
-
- <div className="grid gap-3">
- {settings?.providers.map((item) => (
- <AiProviderCard key={item.id} provider={item} readOnly={readOnly} onChanged={refresh} />
- ))}
- {!settings?.providers.length ? <p className="rounded-lg border border-dashed p-5 text-center text-sm text-slate-500">{t("aiModel.noProviders")}</p> : null}
- </div>
+ <section className="grid gap-3 rounded-lg bg-slate-50/80 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(16rem,1.25fr)] sm:items-center">
+ <div>
+ <h3 className="text-sm font-semibold text-slate-900">{t("aiModel.defaultSettingsTitle")}</h3>
+ <p className="mt-1 text-xs leading-5 text-slate-500">{t("aiModel.defaultModelHint")}</p>
+ </div>
+ <Field label={t("aiModel.defaultModel")}>
+ <Select
+ value={settings?.defaultModelId ?? "none"}
+ onValueChange={(value) => defaultMutation.mutate(value === "none" ? null : value)}
+ disabled={readOnly || defaultMutation.isPending}
+ >
+ <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">{t("aiModel.noDefaultModel")}</SelectItem>
+ {allModels.map((model) => (
+ <SelectItem key={model.id} value={model.id} disabled={!model.providerEnabled}>
+ {model.displayName} · {model.providerName}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ {!defaultModelAvailable ? (
+ <p className="flex items-center gap-2 text-xs text-amber-700 sm:col-start-2"><TriangleAlert className="h-4 w-4 shrink-0" />{t("aiModel.defaultUnavailable")}</p>
+ ) : null}
+ </section>
- {showAdd ? (
- <form className="grid gap-4 rounded-lg border bg-slate-50/60 p-4" onSubmit={(event: FormEvent) => { event.preventDefault(); createMutation.mutate(); }}>
- <h3 className="text-sm font-semibold text-slate-900">{t("aiModel.addProvider")}</h3>
- <div className="grid gap-4 sm:grid-cols-2">
- <Field label={t("aiModel.provider")}>
- <Select value={provider} onValueChange={(value) => handleProviderChange(value as AiProvider)}>
- <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="openai-compatible">{t("aiModel.providers.openai-compatible")}</SelectItem>
- <SelectItem value="anthropic">{t("aiModel.providers.anthropic")}</SelectItem>
- <SelectItem value="google">{t("aiModel.providers.google")}</SelectItem>
- </SelectContent>
- </Select>
- </Field>
- <Field label={t("aiModel.displayName")}><Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={80} /></Field>
- <Field label={t("aiModel.baseUrl")}><Input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} required inputMode="url" /></Field>
- <Field label={t("aiModel.initialModelId")}><Input value={initialModelId} onChange={(event) => setInitialModelId(event.target.value)} /></Field>
- <div className="sm:col-span-2"><Field label={t("aiModel.apiKey")}><Input type="password" value={apiKey} onChange={(event) => setApiKey(event.target.value)} required autoComplete="new-password" /></Field></div>
- </div>
- {createMutation.isError ? <p className="text-xs font-medium text-rose-600" role="alert">{aiErrorMessage(createMutation.error, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}</p> : null}
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={() => { setShowAdd(false); resetAddForm(); }}>{t("common.cancel")}</Button>
- <Button type="submit" disabled={readOnly || createMutation.isPending || !settings?.encryptionConfigured}>
- {createMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("aiModel.createProvider")}
- </Button>
+ <section className="grid gap-3">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <h3 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
+ <Server className="h-4 w-4 text-slate-500" />{t("aiModel.servicesTitle")}
+ </h3>
+ <p className="mt-1 text-xs text-slate-500">
+ {t("aiModel.serviceCount", { count: settings?.providers.length ?? 0 })}
+ </p>
</div>
- </form>
- ) : (
- <Button type="button" variant="outline" className="justify-self-start" disabled={readOnly} onClick={() => setShowAdd(true)}><Plus className="h-4 w-4" />{t("aiModel.addProvider")}</Button>
- )}
+ <Button type="button" variant="outline" size="sm" disabled={readOnly} onClick={() => setShowAdd(true)}>
+ <Plus className="h-4 w-4" />{t("aiModel.addProvider")}
+ </Button>
+ </div>
+
+ <div className="grid gap-3">
+ {settings?.providers.map((item) => (
+ <AiProviderCard
+ key={item.id}
+ provider={item}
+ defaultModelId={settings.defaultModelId}
+ readOnly={readOnly}
+ onChanged={refresh}
+ />
+ ))}
+ {!settings?.providers.length ? (
+ <p className="rounded-lg border border-dashed p-5 text-center text-sm text-slate-500">{t("aiModel.noProviders")}</p>
+ ) : null}
+ </div>
+ </section>
+
+ <Dialog open={showAdd} onOpenChange={handleAddDialogChange}>
+ <DialogContent className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-2xl">
+ <form className="grid gap-5" onSubmit={(event: FormEvent) => { event.preventDefault(); createMutation.mutate(); }}>
+ <DialogHeader>
+ <DialogTitle>{t("aiModel.addProvider")}</DialogTitle>
+ <DialogDescription>{t("aiModel.addProviderDescription")}</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <Field label={t("aiModel.displayName")}>
+ <Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={80} />
+ </Field>
+ <Field label={t("aiModel.provider")}>
+ <Select value={provider} onValueChange={(value) => handleProviderChange(value as AiProvider)}>
+ <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="openai-compatible">{t("aiModel.providers.openai-compatible")}</SelectItem>
+ <SelectItem value="anthropic">{t("aiModel.providers.anthropic")}</SelectItem>
+ <SelectItem value="google">{t("aiModel.providers.google")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+ <div className="sm:col-span-2">
+ <Field label={t("aiModel.baseUrl")}><Input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} required inputMode="url" /></Field>
+ </div>
+ <div className="sm:col-span-2">
+ <Field label={t("aiModel.apiKey")} hint={t("aiModel.apiKeyCreateHint")}>
+ <Input type="password" value={apiKey} onChange={(event) => setApiKey(event.target.value)} required autoComplete="new-password" />
+ </Field>
+ </div>
+ <div className="sm:col-span-2">
+ <Field label={t("aiModel.initialModelId")} hint={t("aiModel.initialModelIdHint")}>
+ <Input value={initialModelId} onChange={(event) => setInitialModelId(event.target.value)} />
+ </Field>
+ </div>
+ </div>
+ {createMutation.isError ? (
+ <p className="text-xs font-medium text-rose-600" role="alert">
+ {aiErrorMessage(createMutation.error, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}
+ </p>
+ ) : null}
+ <DialogFooter className="gap-2 sm:space-x-0">
+ <Button type="button" variant="outline" onClick={() => handleAddDialogChange(false)}>{t("common.cancel")}</Button>
+ <Button type="submit" variant="solid" disabled={readOnly || createMutation.isPending || !settings?.encryptionConfigured}>
+ {createMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("aiModel.createProvider")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
- {error && !createMutation.isError ? <p className="text-xs font-medium text-rose-600" role="alert">{aiErrorMessage(error, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}</p> : null}
+ {error ? <p className="text-xs font-medium text-rose-600" role="alert">{aiErrorMessage(error, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}</p> : null}
</>
)}
</CardContent>
diff --git a/apps/web/src/components/settings/AiProviderCard.tsx b/apps/web/src/components/settings/AiProviderCard.tsx
index 5645d1db..186f2fe0 100644
--- a/apps/web/src/components/settings/AiProviderCard.tsx
+++ b/apps/web/src/components/settings/AiProviderCard.tsx
@@ -1,17 +1,33 @@
import { useEffect, useId, useState, type FormEvent, type ReactNode } from "react";
import { useMutation } from "@tanstack/react-query";
-import type { AiDiscoveredModel, AiProvider, AiProviderConfig } from "@edgeever/shared";
-import { CheckCircle2, Loader2, Plus, Search, Trash2 } from "lucide-react";
+import type { AiDiscoveredModel, AiModelConfig, AiProvider, AiProviderConfig } from "@edgeever/shared";
+import { CheckCircle2, Loader2, MoreHorizontal, Pencil, Plus, Search, Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { aiErrorMessage, providerDefaults } from "@/components/settings/ai-provider-options";
import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { api } from "@/lib/api";
-export const AiProviderCard = ({ provider: saved, readOnly, onChanged }: {
+export const AiProviderCard = ({ provider: saved, defaultModelId, readOnly, onChanged }: {
provider: AiProviderConfig;
+ defaultModelId: string | null;
readOnly: boolean;
onChanged: () => Promise<unknown>;
}) => {
@@ -23,6 +39,8 @@ export const AiProviderCard = ({ provider: saved, readOnly, onChanged }: {
const [apiKey, setApiKey] = useState("");
const [modelId, setModelId] = useState("");
const [discoveredModels, setDiscoveredModels] = useState<AiDiscoveredModel[]>([]);
+ const [showConnection, setShowConnection] = useState(false);
+ const [showAddModel, setShowAddModel] = useState(false);
useEffect(() => {
setProvider(saved.provider);
@@ -30,19 +48,37 @@ export const AiProviderCard = ({ provider: saved, readOnly, onChanged }: {
setBaseUrl(saved.baseUrl);
}, [saved.baseUrl, saved.displayName, saved.provider]);
- const updateMutation = useMutation({
- mutationFn: (isEnabled: boolean = saved.isEnabled) => api.updateAiProvider(saved.id, {
+ const saveMutation = useMutation({
+ mutationFn: () => api.updateAiProvider(saved.id, {
provider,
displayName,
baseUrl,
- isEnabled,
+ isEnabled: saved.isEnabled,
...(apiKey ? { apiKey } : {}),
}),
- onSuccess: async () => { setApiKey(""); await onChanged(); },
+ onSuccess: async () => {
+ setApiKey("");
+ setShowConnection(false);
+ await onChanged();
+ },
+ });
+ const toggleMutation = useMutation({
+ mutationFn: (isEnabled: boolean) => api.updateAiProvider(saved.id, {
+ provider: saved.provider,
+ displayName: saved.displayName,
+ baseUrl: saved.baseUrl,
+ isEnabled,
+ }),
+ onSuccess: onChanged,
});
const deleteMutation = useMutation({ mutationFn: () => api.deleteAiProvider(saved.id), onSuccess: onChanged });
const testMutation = useMutation({
- mutationFn: () => api.testAiProvider(saved.id, { modelId: saved.models[0]?.modelId ?? "" }),
+ mutationFn: () => api.testAiProvider(saved.id, {
+ modelId: saved.models[0]?.modelId ?? "",
+ provider,
+ baseUrl,
+ ...(apiKey ? { apiKey } : {}),
+ }),
});
const discoverMutation = useMutation({
mutationFn: () => api.discoverAiProviderModels(saved.id),
@@ -53,16 +89,29 @@ export const AiProviderCard = ({ provider: saved, readOnly, onChanged }: {
const discovered = discoveredModels.find((item) => item.modelId === modelId.trim());
return api.addAiModel(saved.id, { modelId: modelId.trim(), ...(discovered ? { displayName: discovered.displayName } : {}) });
},
- onSuccess: async () => { setModelId(""); await onChanged(); },
+ onSuccess: async () => {
+ setModelId("");
+ setShowAddModel(false);
+ await onChanged();
+ },
});
const deleteModelMutation = useMutation({
mutationFn: (modelConfigId: string) => api.deleteAiModel(saved.id, modelConfigId),
onSuccess: onChanged,
});
- const mutations = [updateMutation, deleteMutation, testMutation, discoverMutation, addModelMutation, deleteModelMutation];
- const mutationError = mutations.find((item) => item.isError)?.error;
- const isBusy = mutations.some((item) => item.isPending);
+ const connectionBusy = saveMutation.isPending || testMutation.isPending;
+ const modelBusy = discoverMutation.isPending || addModelMutation.isPending || deleteModelMutation.isPending;
+ const cardBusy = toggleMutation.isPending || deleteMutation.isPending || modelBusy;
+ const connectionDirty = provider !== saved.provider
+ || displayName.trim() !== saved.displayName
+ || baseUrl.trim() !== saved.baseUrl
+ || Boolean(apiKey);
+ const connectionError = saveMutation.error ?? testMutation.error;
+ const cardError = toggleMutation.error ?? deleteMutation.error ?? discoverMutation.error ?? addModelMutation.error ?? deleteModelMutation.error;
+ const providerLabel = t(`aiModel.providers.${saved.provider}`);
+ const showProviderLabel = saved.displayName.trim().toLocaleLowerCase() !== providerLabel.trim().toLocaleLowerCase();
+
const handleProviderChange = (next: AiProvider) => {
const previous = providerDefaults[provider];
const defaults = providerDefaults[next];
@@ -70,95 +119,256 @@ export const AiProviderCard = ({ provider: saved, readOnly, onChanged }: {
if (!displayName || displayName === previous.displayName) setDisplayName(defaults.displayName);
if (!baseUrl || baseUrl === previous.baseUrl) setBaseUrl(defaults.baseUrl);
};
-
- const submit = (event: FormEvent) => { event.preventDefault(); updateMutation.mutate(saved.isEnabled); };
+ const resetConnectionForm = () => {
+ setProvider(saved.provider);
+ setDisplayName(saved.displayName);
+ setBaseUrl(saved.baseUrl);
+ setApiKey("");
+ saveMutation.reset();
+ testMutation.reset();
+ };
+ const handleConnectionChange = (open: boolean) => {
+ setShowConnection(open);
+ if (!open) resetConnectionForm();
+ };
+ const openConnection = () => {
+ resetConnectionForm();
+ setShowConnection(true);
+ };
+ const handleAddModelChange = (open: boolean) => {
+ setShowAddModel(open);
+ if (!open) {
+ setModelId("");
+ discoverMutation.reset();
+ addModelMutation.reset();
+ }
+ };
+ const submit = (event: FormEvent) => {
+ event.preventDefault();
+ saveMutation.mutate();
+ };
const deleteProvider = () => {
if (window.confirm(t("aiModel.deleteProviderConfirm", { name: saved.displayName }))) deleteMutation.mutate();
};
+ const deleteModel = (model: AiModelConfig) => {
+ if (window.confirm(t("aiModel.deleteModelConfirm", { name: model.displayName }))) deleteModelMutation.mutate(model.id);
+ };
return (
- <section className="grid gap-4 rounded-lg border p-4">
- <div className="flex items-start justify-between gap-4">
+ <section className="overflow-hidden rounded-lg border bg-white">
+ <div className="flex items-start justify-between gap-3 p-4">
<div className="min-w-0">
<h3 className="truncate text-sm font-semibold text-slate-900">{saved.displayName}</h3>
- <p className="mt-0.5 truncate text-xs text-slate-500">{saved.baseUrl}</p>
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-slate-500">
+ {showProviderLabel ? <span className="rounded bg-slate-100 px-1.5 py-0.5 font-medium text-slate-600">{providerLabel}</span> : null}
+ <span className="max-w-full truncate">{formatBaseUrl(saved.baseUrl)}</span>
+ <span aria-hidden="true">·</span>
+ <span>{t("aiModel.modelCount", { count: saved.models.length })}</span>
+ </div>
</div>
<div className="flex shrink-0 items-center gap-2">
- <span className="hidden text-xs text-slate-500 sm:inline">{t("aiModel.serviceEnabled")}</span>
+ <span className="hidden text-xs text-slate-500 sm:inline">
+ {saved.isEnabled ? t("aiModel.serviceEnabledStatus") : t("aiModel.serviceDisabledStatus")}
+ </span>
<Switch
checked={saved.isEnabled}
- disabled={readOnly || updateMutation.isPending}
+ disabled={readOnly || toggleMutation.isPending}
aria-label={t("aiModel.serviceEnabled")}
- onCheckedChange={(checked) => updateMutation.mutate(checked)}
+ onCheckedChange={(checked) => toggleMutation.mutate(checked)}
/>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="button" variant="ghost" size="icon" disabled={cardBusy}>
+ <MoreHorizontal className="h-4 w-4" />
+ <span className="sr-only">{t("aiModel.serviceActions")}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem disabled={readOnly} onSelect={openConnection}>
+ <Pencil className="mr-2 h-4 w-4" />{t("aiModel.editConnection")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem className="text-rose-600 focus:text-rose-700" disabled={readOnly} onSelect={deleteProvider}>
+ <Trash2 className="mr-2 h-4 w-4" />{t("common.delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
</div>
- <form className="grid gap-4" onSubmit={submit}>
- <div className="grid gap-4 sm:grid-cols-2">
- <Field label={t("aiModel.provider")}>
- <Select value={provider} onValueChange={(value) => handleProviderChange(value as AiProvider)}>
- <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
- <SelectContent>
- <SelectItem value="openai-compatible">{t("aiModel.providers.openai-compatible")}</SelectItem>
- <SelectItem value="anthropic">{t("aiModel.providers.anthropic")}</SelectItem>
- <SelectItem value="google">{t("aiModel.providers.google")}</SelectItem>
- </SelectContent>
- </Select>
- </Field>
- <Field label={t("aiModel.displayName")}><Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={80} /></Field>
- <Field label={t("aiModel.baseUrl")}><Input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} required inputMode="url" /></Field>
- <Field label={t("aiModel.apiKey")}>
- <Input type="password" value={apiKey} onChange={(event) => setApiKey(event.target.value)} autoComplete="new-password" placeholder="••••••••••••" />
- </Field>
- </div>
- <div className="flex flex-wrap justify-end gap-2">
- <Button type="button" variant="ghost" className="mr-auto text-rose-600 hover:text-rose-700" disabled={readOnly || isBusy} onClick={deleteProvider}><Trash2 className="h-4 w-4" />{t("common.delete")}</Button>
- <Button type="button" variant="outline" disabled={isBusy || !saved.hasApiKey || saved.models.length === 0} onClick={() => testMutation.mutate()}>
- {testMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("aiModel.test")}
+ <div className="grid gap-3 border-t bg-slate-50/40 p-4">
+ <div className="flex items-center justify-between gap-3">
+ <h4 className="text-sm font-semibold text-slate-900">{t("aiModel.modelsTitle")}</h4>
+ <Button type="button" variant="outline" size="sm" disabled={readOnly} onClick={() => setShowAddModel(true)}>
+ <Plus className="h-4 w-4" />{t("aiModel.addModel")}
</Button>
- <Button type="submit" disabled={readOnly || isBusy}>{updateMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("common.save")}</Button>
</div>
- </form>
- <div className="grid gap-3 border-t pt-4">
- <div>
- <h4 className="text-sm font-semibold text-slate-900">{t("aiModel.modelsTitle")}</h4>
- <p className="mt-0.5 text-xs text-slate-500">{t("aiModel.modelsHint")}</p>
- </div>
{saved.models.length ? (
- <div className="grid gap-2">
+ <div className="divide-y overflow-hidden rounded-md border bg-white">
{saved.models.map((model) => (
- <div key={model.id} className="flex min-w-0 items-center justify-between gap-3 rounded-md bg-slate-50 px-3 py-2">
- <div className="min-w-0"><p className="truncate text-sm text-slate-800">{model.displayName}</p><p className="truncate text-xs text-slate-500">{model.modelId}</p></div>
- <Button type="button" variant="ghost" size="icon" className="h-8 w-8 shrink-0 text-slate-500" disabled={readOnly || deleteModelMutation.isPending} onClick={() => deleteModelMutation.mutate(model.id)} aria-label={t("aiModel.removeModel")}><Trash2 className="h-4 w-4" /></Button>
+ <div key={model.id} className="group flex min-w-0 items-center justify-between gap-3 px-3 py-2.5">
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <p className="truncate text-sm text-slate-800">{model.displayName}</p>
+ {model.id === defaultModelId ? (
+ <span className="shrink-0 rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-700">
+ {t("aiModel.defaultBadge")}
+ </span>
+ ) : null}
+ </div>
+ {model.modelId !== model.displayName ? <p className="mt-0.5 truncate text-xs text-slate-500">{model.modelId}</p> : null}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 shrink-0 text-slate-400 hover:text-rose-600"
+ disabled={readOnly || deleteModelMutation.isPending}
+ onClick={() => deleteModel(model)}
+ aria-label={t("aiModel.removeModel")}
+ title={t("aiModel.removeModel")}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
</div>
))}
</div>
- ) : <p className="text-xs text-slate-500">{t("aiModel.noModels")}</p>}
- <div className="flex flex-col gap-2 sm:flex-row">
- <div className="min-w-0 flex-1">
- <Input list={datalistId} value={modelId} onChange={(event) => setModelId(event.target.value)} placeholder={t("aiModel.modelIdPlaceholder")} />
- <datalist id={datalistId}>{discoveredModels.map((model) => <option key={model.modelId} value={model.modelId}>{model.displayName}</option>)}</datalist>
- </div>
- <Button type="button" variant="outline" disabled={isBusy || !saved.hasApiKey} onClick={() => discoverMutation.mutate()}>
- {discoverMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}{t("aiModel.discoverModels")}
- </Button>
- <Button type="button" disabled={readOnly || isBusy || !modelId.trim()} onClick={() => addModelMutation.mutate()}>
- {addModelMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}{t("aiModel.addModel")}
- </Button>
- </div>
- {discoverMutation.isSuccess ? <p className="text-xs text-emerald-700">{t("aiModel.discoveryComplete", { count: discoveredModels.length })}</p> : null}
+ ) : (
+ <p className="rounded-md border border-dashed bg-white p-4 text-center text-xs text-slate-500">{t("aiModel.noModels")}</p>
+ )}
+
+ {cardError ? (
+ <p className="text-xs font-medium text-rose-600" role="alert">
+ {aiErrorMessage(cardError, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}
+ </p>
+ ) : null}
</div>
- {testMutation.isSuccess || updateMutation.isSuccess ? (
- <p className="flex items-center gap-1.5 text-xs font-medium text-emerald-700"><CheckCircle2 className="h-4 w-4" />{testMutation.isSuccess ? t("aiModel.testSucceeded") : t("aiModel.saved")}</p>
- ) : null}
- {mutationError ? <p className="text-xs font-medium text-rose-600" role="alert">{aiErrorMessage(mutationError, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}</p> : null}
+ <Dialog open={showConnection} onOpenChange={handleConnectionChange}>
+ <DialogContent className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-2xl">
+ <form className="grid gap-5" onSubmit={submit}>
+ <DialogHeader>
+ <DialogTitle>{t("aiModel.editConnection")}</DialogTitle>
+ <DialogDescription>{t("aiModel.connectionDescription", { name: saved.displayName })}</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <Field label={t("aiModel.displayName")}>
+ <Input value={displayName} onChange={(event) => setDisplayName(event.target.value)} required maxLength={80} disabled={readOnly} />
+ </Field>
+ <Field label={t("aiModel.provider")}>
+ <Select value={provider} onValueChange={(value) => handleProviderChange(value as AiProvider)} disabled={readOnly}>
+ <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="openai-compatible">{t("aiModel.providers.openai-compatible")}</SelectItem>
+ <SelectItem value="anthropic">{t("aiModel.providers.anthropic")}</SelectItem>
+ <SelectItem value="google">{t("aiModel.providers.google")}</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+ <div className="sm:col-span-2">
+ <Field label={t("aiModel.baseUrl")}>
+ <Input value={baseUrl} onChange={(event) => setBaseUrl(event.target.value)} required inputMode="url" disabled={readOnly} />
+ </Field>
+ </div>
+ <div className="sm:col-span-2">
+ <Field label={t("aiModel.apiKey")} hint={t("aiModel.apiKeySavedHint")}>
+ <Input
+ type="password"
+ value={apiKey}
+ onChange={(event) => setApiKey(event.target.value)}
+ autoComplete="new-password"
+ placeholder={saved.hasApiKey ? t("aiModel.apiKeyStoredPlaceholder") : undefined}
+ disabled={readOnly}
+ />
+ </Field>
+ </div>
+ </div>
+ {testMutation.isSuccess ? (
+ <p className="flex items-center gap-1.5 text-xs font-medium text-emerald-700">
+ <CheckCircle2 className="h-4 w-4" />{t("aiModel.testSucceeded")}
+ </p>
+ ) : null}
+ {connectionError ? (
+ <p className="text-xs font-medium text-rose-600" role="alert">
+ {aiErrorMessage(connectionError, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}
+ </p>
+ ) : null}
+ <DialogFooter className="gap-2 sm:space-x-0">
+ <Button type="button" variant="outline" onClick={() => handleConnectionChange(false)}>{t("common.cancel")}</Button>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={connectionBusy || !baseUrl.trim() || (!saved.hasApiKey && !apiKey) || saved.models.length === 0}
+ onClick={() => testMutation.mutate()}
+ >
+ {testMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("aiModel.test")}
+ </Button>
+ <Button type="submit" variant="solid" disabled={readOnly || connectionBusy || !connectionDirty || !displayName.trim() || !baseUrl.trim()}>
+ {saveMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}{t("common.save")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog open={showAddModel} onOpenChange={handleAddModelChange}>
+ <DialogContent>
+ <form className="grid gap-5" onSubmit={(event: FormEvent) => { event.preventDefault(); addModelMutation.mutate(); }}>
+ <DialogHeader>
+ <DialogTitle>{t("aiModel.addModel")}</DialogTitle>
+ <DialogDescription>{t("aiModel.addModelDescription")}</DialogDescription>
+ </DialogHeader>
+ <Field label={t("aiModel.modelId")} hint={discoverMutation.isSuccess ? t("aiModel.discoveryComplete", { count: discoveredModels.length }) : undefined}>
+ <Input
+ list={datalistId}
+ value={modelId}
+ onChange={(event) => setModelId(event.target.value)}
+ placeholder={t("aiModel.modelIdPlaceholder")}
+ autoFocus
+ />
+ <datalist id={datalistId}>
+ {discoveredModels.map((model) => <option key={model.modelId} value={model.modelId}>{model.displayName}</option>)}
+ </datalist>
+ </Field>
+ {discoverMutation.error || addModelMutation.error ? (
+ <p className="text-xs font-medium text-rose-600" role="alert">
+ {aiErrorMessage(discoverMutation.error ?? addModelMutation.error, t("aiModel.failed"), t("aiModel.encryptionKeyMissing"))}
+ </p>
+ ) : null}
+ <DialogFooter className="gap-2 sm:space-x-0 sm:justify-between">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={modelBusy || !saved.hasApiKey}
+ onClick={() => discoverMutation.mutate()}
+ >
+ {discoverMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}{t("aiModel.discoverModels")}
+ </Button>
+ <div className="flex flex-col-reverse gap-2 sm:flex-row">
+ <Button type="button" variant="outline" onClick={() => handleAddModelChange(false)}>{t("common.cancel")}</Button>
+ <Button type="submit" variant="solid" disabled={readOnly || modelBusy || !modelId.trim()}>
+ {addModelMutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}{t("aiModel.addModel")}
+ </Button>
+ </div>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
</section>
);
};
+const formatBaseUrl = (baseUrl: string) => {
+ try {
+ return new URL(baseUrl).host;
+ } catch {
+ return baseUrl;
+ }
+};
+
const Field = ({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) => (
- <label className="grid gap-1.5 text-sm font-medium text-slate-700">{label}{children}{hint ? <span className="text-xs font-normal leading-4 text-slate-500">{hint}</span> : null}</label>
+ <label className="grid gap-1.5 text-sm font-medium text-slate-700">
+ {label}{children}{hint ? <span className="text-xs font-normal leading-4 text-slate-500">{hint}</span> : null}
+ </label>
);
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 91e90b0c..69fd06d9 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -469,7 +469,12 @@ export const api = {
method: "DELETE",
}),
- testAiProvider: (providerConfigId: string, payload: { modelId: string }) =>
+ testAiProvider: (providerConfigId: string, payload: {
+ modelId: string;
+ provider?: AiProvider;
+ baseUrl?: string;
+ apiKey?: string;
+ }) =>
request<{ ok: true; response: string }>(`/api/v1/ai/providers/${encodeURIComponent(providerConfigId)}/test`, {
method: "POST",
body: JSON.stringify(payload),
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index f2c00b57..2b357a5b 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -283,22 +283,39 @@ export const enUS = {
modelId: "Model ID",
modelIdPlaceholder: "Enter a model ID, or discover models first",
apiKey: "API Key",
+ apiKeyCreateHint: "The credential is encrypted on the EdgeEver server.",
apiKeySavedHint: "The key is encrypted. Leave this blank to keep it unchanged.",
+ apiKeyStoredPlaceholder: "Saved; enter a new key to replace it",
serviceEnabled: "Enable service",
+ serviceEnabledStatus: "Enabled",
+ serviceDisabledStatus: "Disabled",
+ serviceActions: "Service actions",
+ defaultSettingsTitle: "Usage settings",
defaultModel: "Default model for note AI",
+ defaultModelHint: "The model the AI note assistant uses by default.",
noDefaultModel: "No model selected",
defaultUnavailable: "The service for the current default model is disabled. Enable it or choose another model.",
noProviders: "No model services yet. Add OpenAI, OpenRouter, Anthropic, Gemini, or another compatible service to begin.",
+ servicesTitle: "Model services",
+ serviceCount: "Configured: {{count}}",
addProvider: "Add model service",
+ addProviderDescription: "Connect a model API, then discover or add more models after the service is created.",
createProvider: "Add service",
initialModelId: "Initial model ID (optional)",
+ initialModelIdHint: "Leave this blank to discover available models after creating the service.",
deleteProviderConfirm: "Delete “{{name}}” and all of its models?",
- modelsTitle: "Models in this service",
+ editConnection: "Edit connection",
+ connectionDescription: "Change the endpoint and credential used by “{{name}}”. Testing uses the current form without saving it.",
+ modelsTitle: "Available models",
+ modelCount: "Models: {{count}}",
modelsHint: "One Base URL can contain multiple models. For example, one OpenRouter service can provide models from several vendors.",
noModels: "No models added yet. Discover available models or enter a model ID directly.",
discoverModels: "Discover models",
discoveryComplete: "Found {{count}} available models.",
addModel: "Add model",
+ addModelDescription: "Enter a model ID directly, or discover models available from this service first.",
+ defaultBadge: "Default",
+ deleteModelConfirm: "Remove the model “{{name}}”?",
removeModel: "Remove model",
test: "Test connection",
testSucceeded: "The model endpoint responded successfully.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index aefe29c6..ca65930d 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -283,22 +283,39 @@ export const zhCN = {
modelId: "模型 ID",
modelIdPlaceholder: "输入模型 ID,或先发现模型",
apiKey: "API Key",
+ apiKeyCreateHint: "凭据将由 EdgeEver 服务端加密保存。",
apiKeySavedHint: "密钥已加密保存;留空表示保持不变。",
+ apiKeyStoredPlaceholder: "已保存;输入新密钥可替换",
serviceEnabled: "启用服务",
+ serviceEnabledStatus: "已启用",
+ serviceDisabledStatus: "已停用",
+ serviceActions: "服务操作",
+ defaultSettingsTitle: "使用设置",
defaultModel: "笔记 AI 默认模型",
+ defaultModelHint: "AI 笔记助手处理内容时优先使用的模型。",
noDefaultModel: "未选择模型",
defaultUnavailable: "当前默认模型所在的服务已禁用,请启用该服务或选择其他模型。",
noProviders: "还没有模型服务。添加 OpenAI、OpenRouter、Anthropic、Gemini 或其他兼容服务即可开始。",
+ servicesTitle: "模型服务",
+ serviceCount: "{{count}} 个服务",
addProvider: "添加模型服务",
+ addProviderDescription: "连接一个模型 API;创建后可以继续发现或添加更多模型。",
createProvider: "添加服务",
initialModelId: "首个模型 ID(可选)",
+ initialModelIdHint: "可以留空,创建服务后再发现可用模型。",
deleteProviderConfirm: "确定删除“{{name}}”及其全部模型吗?",
- modelsTitle: "服务中的模型",
+ editConnection: "编辑连接",
+ connectionDescription: "修改“{{name}}”使用的接口和凭据。测试会使用当前表单内容,不会自动保存。",
+ modelsTitle: "可用模型",
+ modelCount: "{{count}} 个模型",
modelsHint: "同一个 Base URL 可以添加多个模型;例如一个 OpenRouter 服务可同时使用多个厂商模型。",
noModels: "尚未添加模型。可以自动发现,也可以直接输入模型 ID。",
discoverModels: "发现模型",
discoveryComplete: "发现了 {{count}} 个可选模型。",
addModel: "添加模型",
+ addModelDescription: "直接输入模型 ID,或先从此服务发现可用模型。",
+ defaultBadge: "默认",
+ deleteModelConfirm: "确定移除模型“{{name}}”吗?",
removeModel: "移除模型",
test: "测试连接",
testSucceeded: "模型服务已成功响应。",
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index 771ccebb..5bc4a4ec 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -189,6 +189,9 @@ export const AiProviderConfigUpdateSchema = AiProviderConfigFieldsSchema.extend(
export const AiProviderConnectionTestSchema = z.object({
modelId: z.string().trim().min(1).max(200),
+ provider: AiProviderSchema.optional(),
+ baseUrl: AiBaseUrlSchema.optional(),
+ apiKey: z.string().min(1).max(4096).optional(),
});
export const AiModelConfigCreateSchema = z.object({