feat: 全局设置系统 — settings 表、CRUD 路由、主题偏好持久化
This commit is contained in:
@@ -20,4 +20,5 @@ export {
|
||||
listModels,
|
||||
updateModel,
|
||||
} from "./models";
|
||||
export { conversations, messages, projects, schemaMigrations } from "./schema";
|
||||
export { conversations, messages, projects, schemaMigrations, settings } from "./schema";
|
||||
export { getSettings, updateSettings } from "./settings";
|
||||
|
||||
@@ -86,3 +86,8 @@ export const schemaMigrations = sqliteTable("schema_migrations", {
|
||||
checksum: text("checksum").notNull(),
|
||||
id: text("id").primaryKey(),
|
||||
});
|
||||
|
||||
export const settings = sqliteTable("settings", {
|
||||
...baseColumns,
|
||||
data: text("data").notNull().default("{}"),
|
||||
});
|
||||
|
||||
72
src/server/db/settings.ts
Normal file
72
src/server/db/settings.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type Database from "bun:sqlite";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import type { SettingsData } from "../../shared/api";
|
||||
import type { Logger } from "../logger";
|
||||
|
||||
import { notDeleted, timestamp, wrap } from "./connection";
|
||||
import { settings } from "./schema";
|
||||
|
||||
const SETTINGS_ID = "default";
|
||||
|
||||
export function getSettings(raw: Database): SettingsData {
|
||||
const db = wrap(raw);
|
||||
const row = db
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.id, SETTINGS_ID), notDeleted(settings)))
|
||||
.get();
|
||||
|
||||
if (!row) {
|
||||
return { theme: "system" };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(row.data) as Partial<SettingsData>;
|
||||
return {
|
||||
theme: parsed.theme === "dark" || parsed.theme === "light" || parsed.theme === "system" ? parsed.theme : "system",
|
||||
};
|
||||
} catch {
|
||||
return { theme: "system" };
|
||||
}
|
||||
}
|
||||
|
||||
export function updateSettings(raw: Database, data: Partial<SettingsData>, _logger: Logger): SettingsData {
|
||||
const db = wrap(raw);
|
||||
const existing = db
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(and(eq(settings.id, SETTINGS_ID), notDeleted(settings)))
|
||||
.get();
|
||||
|
||||
let currentData: SettingsData = { theme: "system" };
|
||||
if (existing) {
|
||||
try {
|
||||
currentData = JSON.parse(existing.data) as SettingsData;
|
||||
} catch {
|
||||
// 解析失败时使用默认值
|
||||
}
|
||||
}
|
||||
|
||||
const merged: SettingsData = { ...currentData, ...data };
|
||||
|
||||
if (existing) {
|
||||
db.update(settings)
|
||||
.set({ data: JSON.stringify(merged), updatedAt: timestamp() })
|
||||
.where(eq(settings.id, SETTINGS_ID))
|
||||
.run();
|
||||
} else {
|
||||
const now = timestamp();
|
||||
db.insert(settings)
|
||||
.values({
|
||||
createdAt: now,
|
||||
data: JSON.stringify(merged),
|
||||
id: SETTINGS_ID,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
38
src/server/routes/settings.ts
Normal file
38
src/server/routes/settings.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type Database from "bun:sqlite";
|
||||
|
||||
import type { RuntimeMode, SettingsData } from "../../shared/api";
|
||||
import type { Logger } from "../logger";
|
||||
|
||||
import { getSettings, updateSettings } from "../db/settings";
|
||||
import { createApiError, jsonResponse } from "../helpers";
|
||||
|
||||
export function handleGetSettings(_req: Request, db: Database, mode: RuntimeMode, _logger: Logger): Response {
|
||||
const data = getSettings(db);
|
||||
return jsonResponse(data, { mode });
|
||||
}
|
||||
|
||||
export async function handleUpdateSettings(
|
||||
req: Request,
|
||||
db: Database,
|
||||
mode: RuntimeMode,
|
||||
logger: Logger,
|
||||
): Promise<Response> {
|
||||
let body: Partial<SettingsData>;
|
||||
try {
|
||||
body = (await req.json()) as Partial<SettingsData>;
|
||||
} catch {
|
||||
return jsonResponse(createApiError("Invalid JSON body", 400), { mode, status: 400 });
|
||||
}
|
||||
|
||||
if (body.theme !== undefined && typeof body.theme !== "string") {
|
||||
return jsonResponse(createApiError("theme must be a string", 400), { mode, status: 400 });
|
||||
}
|
||||
|
||||
if (body.theme !== undefined && body.theme !== "dark" && body.theme !== "light" && body.theme !== "system") {
|
||||
return jsonResponse(createApiError("theme 仅支持 dark、light、system", 400), { mode, status: 400 });
|
||||
}
|
||||
|
||||
const result = updateSettings(db, body, logger);
|
||||
logger.info({ data: result }, "设置已更新");
|
||||
return jsonResponse(result, { mode });
|
||||
}
|
||||
@@ -330,6 +330,24 @@ export function startServer(options: StartServerOptions) {
|
||||
logger,
|
||||
),
|
||||
},
|
||||
"/api/settings": {
|
||||
GET: withErrorHandler(
|
||||
async (req) => {
|
||||
const { handleGetSettings } = await import("./routes/settings");
|
||||
return handleGetSettings(req, db, mode, logger);
|
||||
},
|
||||
mode,
|
||||
logger,
|
||||
),
|
||||
PUT: withErrorHandler(
|
||||
async (req) => {
|
||||
const { handleUpdateSettings } = await import("./routes/settings");
|
||||
return handleUpdateSettings(req, db, mode, logger);
|
||||
},
|
||||
mode,
|
||||
logger,
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -237,11 +237,17 @@ export type ProviderType = "anthropic" | "openai" | "openai-compatible";
|
||||
|
||||
export type RuntimeMode = "development" | "production" | "test";
|
||||
|
||||
export interface SettingsData {
|
||||
theme: ThemePreference;
|
||||
}
|
||||
|
||||
export interface TestModelRequest {
|
||||
externalId: string;
|
||||
providerId: string;
|
||||
}
|
||||
|
||||
export type ThemePreference = "dark" | "light" | "system";
|
||||
|
||||
export interface UpdateModelRequest {
|
||||
capabilities?: ModelCapability[];
|
||||
contextLength?: null | number;
|
||||
|
||||
38
src/web/features/settings/index.tsx
Normal file
38
src/web/features/settings/index.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { Card, Segmented } from "antd";
|
||||
|
||||
import { useSettings } from "../../shared/hooks/use-settings";
|
||||
import { parseThemePreference, useThemePreference } from "../../shared/hooks/use-theme-preference";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{ label: "系统", value: "system" },
|
||||
{ label: "明亮", value: "light" },
|
||||
{ label: "黑暗", value: "dark" },
|
||||
] as const;
|
||||
|
||||
export function SettingsPage() {
|
||||
const { preference, setPreference } = useThemePreference();
|
||||
const { isUpdating, updateSettings } = useSettings();
|
||||
|
||||
const handleThemeChange = (value: string) => {
|
||||
const theme = parseThemePreference(value);
|
||||
updateSettings(
|
||||
{ theme },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setPreference(theme);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card extra={isUpdating ? "保存中..." : undefined} title="主题" type="inner">
|
||||
<Segmented
|
||||
block
|
||||
onChange={(value) => handleThemeChange(value)}
|
||||
options={THEME_OPTIONS.map((option) => ({ label: option.label, value: option.value }))}
|
||||
value={preference}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
import { ApiOutlined, CloudServerOutlined, DashboardOutlined, FolderOutlined, RobotOutlined } from "@ant-design/icons";
|
||||
import {
|
||||
ApiOutlined,
|
||||
CloudServerOutlined,
|
||||
DashboardOutlined,
|
||||
FolderOutlined,
|
||||
RobotOutlined,
|
||||
SettingOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import { createElement } from "react";
|
||||
|
||||
import type { MenuItemConfig } from "../../menu";
|
||||
@@ -16,4 +23,5 @@ export const ADMIN_MENU_ITEMS: readonly MenuItemConfig[] = [
|
||||
path: "",
|
||||
value: "model-management",
|
||||
},
|
||||
{ icon: createElement(SettingOutlined), label: "设置", path: "/settings", value: "settings" },
|
||||
] as const;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ModelListPage } from "./features/models/ModelListPage";
|
||||
import { ProviderListPage } from "./features/models/ProviderListPage";
|
||||
import { NotFoundPage } from "./features/not-found";
|
||||
import { ProjectsPage } from "./features/projects";
|
||||
import { SettingsPage } from "./features/settings";
|
||||
import { AdminConsoleLayout } from "./layouts/admin-layout/AdminConsoleLayout";
|
||||
import { WorkbenchProjectGate } from "./layouts/workbench-layout/WorkbenchProjectGate";
|
||||
import { RouteError } from "./shared/components/RouteError";
|
||||
@@ -19,6 +20,7 @@ export function AppRoutes() {
|
||||
<Route element={<ProjectsPage />} path="/projects" />
|
||||
<Route element={<ModelListPage />} path="/models" />
|
||||
<Route element={<ProviderListPage />} path="/models/providers" />
|
||||
<Route element={<SettingsPage />} path="/settings" />
|
||||
</Route>
|
||||
<Route element={<WorkbenchProjectGate />} errorElement={<RouteError />} path="/workbench/:projectId">
|
||||
<Route element={<ChatPage />} path="" />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
|
||||
import { XProvider } from "@ant-design/x";
|
||||
import zhCN_X from "@ant-design/x/locale/zh_CN";
|
||||
import { App as AntApp, Layout, Segmented } from "antd";
|
||||
import { App as AntApp, Layout } from "antd";
|
||||
import zhCN from "antd/locale/zh_CN";
|
||||
import { useMemo } from "react";
|
||||
|
||||
@@ -17,14 +17,8 @@ import { ConsoleOutlet } from "./ConsoleOutlet";
|
||||
|
||||
const { Content, Header, Sider } = Layout;
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{ label: "系统", value: "system" },
|
||||
{ label: "明亮", value: "light" },
|
||||
{ label: "黑暗", value: "dark" },
|
||||
] as const;
|
||||
|
||||
export function ConsoleShell({ headerExtra, menuItems, title }: ConsoleShellProps) {
|
||||
const { effectiveTheme, preference: themePreference, setPreference: setThemePreference } = useThemePreference();
|
||||
const { effectiveTheme } = useThemePreference();
|
||||
const { collapsed, setCollapsed } = useSidebarCollapsed();
|
||||
const { data: meta } = useMeta();
|
||||
|
||||
@@ -43,14 +37,7 @@ export function ConsoleShell({ headerExtra, menuItems, title }: ConsoleShellProp
|
||||
<span className="app-console-title">{title}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="app-header-right">
|
||||
{headerExtra}
|
||||
<Segmented
|
||||
onChange={(value) => setThemePreference(value)}
|
||||
options={THEME_OPTIONS.map((option) => ({ label: option.label, value: option.value }))}
|
||||
value={themePreference}
|
||||
/>
|
||||
</div>
|
||||
<div className="app-header-right">{headerExtra}</div>
|
||||
</Header>
|
||||
<Layout>
|
||||
<Sider
|
||||
|
||||
44
src/web/shared/hooks/use-settings.ts
Normal file
44
src/web/shared/hooks/use-settings.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import type { SettingsData } from "../../../shared/api";
|
||||
|
||||
export function useSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery({
|
||||
queryFn: fetchSettings,
|
||||
queryKey: ["settings"],
|
||||
staleTime: 60000,
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: updateSettings,
|
||||
onSuccess: (data) => {
|
||||
queryClient.setQueryData(["settings"], data);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
data: query.data,
|
||||
error: query.error,
|
||||
isLoading: query.isLoading,
|
||||
isUpdating: mutation.isPending,
|
||||
updateSettings: mutation.mutate,
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchSettings(): Promise<SettingsData> {
|
||||
const response = await fetch("/api/settings");
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.json() as Promise<SettingsData>;
|
||||
}
|
||||
|
||||
async function updateSettings(data: Partial<SettingsData>): Promise<SettingsData> {
|
||||
const response = await fetch("/api/settings", {
|
||||
body: JSON.stringify(data),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
method: "PUT",
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.json() as Promise<SettingsData>;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import type { SettingsData } from "../../../shared/api";
|
||||
|
||||
export type EffectiveTheme = "dark" | "light";
|
||||
export type ThemePreference = "dark" | "light" | "system";
|
||||
|
||||
@@ -38,6 +40,27 @@ export function useThemePreference() {
|
||||
const [systemPrefersDark, setSystemPrefersDark] = useState(() => getSystemPrefersDark());
|
||||
const effectiveTheme = resolveEffectiveTheme(preference, systemPrefersDark);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch("/api/settings")
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json() as Promise<SettingsData>;
|
||||
})
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
const apiTheme = parseThemePreference(data.theme);
|
||||
setPreferenceState((prev) => (prev !== apiTheme ? apiTheme : prev));
|
||||
writeThemePreference(apiTheme);
|
||||
})
|
||||
.catch(() => {
|
||||
// API 不可用时维持 localStorage 缓存值
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQueryList = window.matchMedia(THEME_MEDIA_QUERY);
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export function buildThemeConfig(effectiveTheme: EffectiveTheme) {
|
||||
Layout: {
|
||||
bodyBg: isDark ? "#0a0a0a" : "transparent",
|
||||
headerBg: "transparent",
|
||||
siderBg: isDark ? "#0a0a0a" : "#ffffff",
|
||||
siderBg: isDark ? "#141414" : "#ffffff",
|
||||
triggerBg: isDark ? "#141414" : "#ffffff",
|
||||
},
|
||||
Menu: {
|
||||
|
||||
@@ -65,6 +65,7 @@ body {
|
||||
color: var(--ant-color-text-secondary);
|
||||
font-size: var(--ant-font-size);
|
||||
font-weight: 400;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.app-unavailable {
|
||||
|
||||
Reference in New Issue
Block a user