fix(merge): 本地整合 - 保留主分支交互与样式并排除不安全用户删除
This commit is contained in:
@@ -2,6 +2,7 @@ import { ConfigProvider, Dropdown } from "antd";
|
||||
import { Tooltip } from "@/components/ui/base/tooltip";
|
||||
import type { MenuProps } from "antd";
|
||||
import {
|
||||
Activity,
|
||||
ArrowLeft,
|
||||
BarChart3,
|
||||
BellRing,
|
||||
@@ -89,6 +90,7 @@ const adminNavigation: Array<{ label: string; items: AdminNavigationItem[] }> =
|
||||
{ path: "/admin/settings/features", label: "功能开放", description: "工作台、插件与模型能力", icon: <ToggleLeft className="size-4" /> },
|
||||
{ path: "/admin/settings/drawing-engine", label: "绘图工具", description: "画布绘图节点默认引擎", icon: <Paintbrush className="size-4" /> },
|
||||
{ path: "/admin/settings/runtime-policy", label: "资源与策略", description: "配额、并发、频控与超时", icon: <Settings2 className="size-4" /> },
|
||||
{ path: "/admin/settings/system-performance", label: "系统性能", description: "主机、数据库与缓存状态", icon: <Activity className="size-4" /> },
|
||||
{ path: "/admin/settings/access", label: "登录与注册", description: "账号创建与第三方登录", icon: <ShieldCheck className="size-4" /> },
|
||||
{ path: "/admin/settings/email", label: "邮件服务", description: "注册验证码与 SMTP", icon: <Mail className="size-4" /> },
|
||||
{ path: "/admin/settings/storage", label: "存储服务", description: "对象存储与资源存储", icon: <HardDrive className="size-4" /> },
|
||||
|
||||
@@ -7,15 +7,17 @@ import { PaginationBar } from "@/components/layout/workspace-page";
|
||||
import { ModelIcon } from "@/components/model-picker";
|
||||
import { modelProtocolDefinition, modelProtocolLabel, type ModelProtocol } from "@/lib/model-protocols";
|
||||
import { fetchPluginProviderCatalog } from "@/services/api/plugin-catalog";
|
||||
import { deleteAdminChannelModel, fetchAdminChannelModels, importAdminChannelModels, listAdminChannelModels, type ChannelModel, type ChannelModelPriceTier } from "@/services/api/wallet";
|
||||
import { deleteAdminChannelModel, deleteAdminChannelModels, fetchAdminChannelModels, importAdminChannelModels, listAdminChannelModels, type ChannelModel, type ChannelModelPriceTier } from "@/services/api/wallet";
|
||||
import type { ModelChannel } from "@/stores/use-config-store";
|
||||
import { ChannelModelEditor } from "./channel-model-editor";
|
||||
import { AdminPageFrame } from "./admin-shell";
|
||||
import { AdminDataTable, AdminFilterChip, AdminStatusBadge } from "./admin-ui";
|
||||
import { AdminBatchBar, AdminDataTable, AdminFilterChip, AdminStatusBadge } from "./admin-ui";
|
||||
|
||||
export function ChannelModelManager({ channel, onClose, onChanged }: { channel: ModelChannel; onClose: () => void; onChanged: () => void | Promise<void> }) {
|
||||
const { message } = App.useApp();
|
||||
const { message, modal } = App.useApp();
|
||||
const [items, setItems] = useState<ChannelModel[]>([]);
|
||||
const [selectedModelIds, setSelectedModelIds] = useState<string[]>([]);
|
||||
const [deletingSelected, setDeletingSelected] = useState(false);
|
||||
const [editing, setEditing] = useState<ChannelModel | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [fetching, setFetching] = useState(false);
|
||||
@@ -48,7 +50,10 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
if (!channel) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
setItems((await listAdminChannelModels(channel.id)).models);
|
||||
const models = (await listAdminChannelModels(channel.id)).models;
|
||||
const availableIDs = new Set(models.map((item) => item.id));
|
||||
setItems(models);
|
||||
setSelectedModelIds((current) => current.filter((id) => availableIDs.has(id)));
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "读取渠道模型失败");
|
||||
} finally {
|
||||
@@ -61,6 +66,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
void loadProtocols();
|
||||
setEditing(null);
|
||||
setEditorOpen(false);
|
||||
setSelectedModelIds([]);
|
||||
resetFetchPreview();
|
||||
setKeyword("");
|
||||
setCapability("all");
|
||||
@@ -139,6 +145,32 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
}
|
||||
};
|
||||
|
||||
const confirmBatchRemove = () => {
|
||||
if (!selectedModelIds.length) return;
|
||||
const count = selectedModelIds.length;
|
||||
modal.confirm({
|
||||
title: `删除已选的 ${count} 个模型?`,
|
||||
content: "删除后模型不再显示,且不能在页面恢复。只要其中任一模型仍被前台供应线路或进行中任务使用,本次就不会删除任何模型。",
|
||||
okText: "批量删除",
|
||||
cancelText: "取消",
|
||||
okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
setDeletingSelected(true);
|
||||
try {
|
||||
const result = await deleteAdminChannelModels(channel.id, selectedModelIds);
|
||||
setSelectedModelIds([]);
|
||||
setPage(1);
|
||||
await reload();
|
||||
await onChanged();
|
||||
message.success(`已删除 ${result.deleted} 个模型`);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "批量删除模型失败");
|
||||
} finally {
|
||||
setDeletingSelected(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
const columns: ColumnsType<ChannelModel> = [
|
||||
{
|
||||
title: "模型",
|
||||
@@ -178,11 +210,11 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
width: 180,
|
||||
render: (_, item) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => startEdit(item)}>
|
||||
<Button size="small" disabled={deletingSelected} onClick={() => startEdit(item)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm title="删除模型" description="已被前台供应线路或进行中任务使用的模型不能删除;删除后模型不再显示,且不能在页面恢复。" okText="删除" cancelText="取消" onConfirm={() => void remove(item)}>
|
||||
<Button size="small" danger title="删除模型" aria-label="删除模型" icon={<Trash2 className="size-3.5" />} />
|
||||
<Button size="small" danger disabled={deletingSelected} title="删除模型" aria-label="删除模型" icon={<Trash2 className="size-3.5" />} />
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
@@ -201,6 +233,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
const existingFetchModelKeys = new Set(items.map((item) => normalizeFetchModelKey(item.modelKey)));
|
||||
const selectedNewFetchModels = selectedFetchModels.filter((name) => !existingFetchModelKeys.has(normalizeFetchModelKey(name)));
|
||||
const selectedExistingFetchCount = selectedFetchModels.length - selectedNewFetchModels.length;
|
||||
const allFetchModelsSelected = fetchPreviewModels.length > 0 && fetchPreviewModels.every((name) => selectedFetchModels.includes(name));
|
||||
const fetchModelOptions = fetchPreviewModels.map((name) => {
|
||||
const alreadyExists = existingFetchModelKeys.has(normalizeFetchModelKey(name));
|
||||
return {
|
||||
@@ -315,11 +348,27 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
setStatus("all");
|
||||
setPage(1);
|
||||
}}
|
||||
batchActions={
|
||||
<AdminBatchBar count={selectedModelIds.length} onClear={() => setSelectedModelIds([])}>
|
||||
<Button danger size="small" icon={<Trash2 className="size-3.5" />} loading={deletingSelected} onClick={confirmBatchRemove}>
|
||||
批量删除
|
||||
</Button>
|
||||
</AdminBatchBar>
|
||||
}
|
||||
table={{
|
||||
className: "app-data-table",
|
||||
rowKey: "id",
|
||||
size: "small",
|
||||
loading,
|
||||
rowSelection: {
|
||||
selectedRowKeys: selectedModelIds,
|
||||
preserveSelectedRowKeys: true,
|
||||
onChange: (keys) => {
|
||||
const next = keys.map(String);
|
||||
if (next.length > 100) message.warning("单次最多选择 100 个模型");
|
||||
setSelectedModelIds(next.slice(0, 100));
|
||||
},
|
||||
},
|
||||
columns,
|
||||
dataSource: pagedItems,
|
||||
pagination: false,
|
||||
@@ -357,9 +406,28 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
|
||||
]}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<p className="m-0 text-sm text-foreground/65">上游共返回 {fetchPreviewModels.length} 个模型。默认已全选,请取消本次不需要拉入的模型;已存在的模型不会重复导入。</p>
|
||||
<p className="m-0 text-sm text-foreground/65">上游共返回 {fetchPreviewModels.length} 个模型。默认已全选,可批量全选或取消全选;已存在的模型不会重复导入。</p>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border/70 bg-muted/25 px-3 py-2">
|
||||
<span className="text-sm font-medium text-foreground/70" aria-live="polite">
|
||||
已选择 {selectedFetchModels.length} / {fetchPreviewModels.length} 个模型
|
||||
</span>
|
||||
<Space size={4}>
|
||||
<Button size="small" disabled={importing || allFetchModelsSelected} onClick={() => setSelectedFetchModels(fetchPreviewModels)}>
|
||||
全选
|
||||
</Button>
|
||||
<Button size="small" disabled={importing || selectedFetchModels.length === 0} onClick={() => setSelectedFetchModels([])}>
|
||||
取消全选
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<div className="max-h-[min(60vh,520px)] overflow-y-auto rounded-md border border-border/70 p-3">
|
||||
<Checkbox.Group className="channel-model-import-picker grid w-full grid-cols-1 gap-2 sm:grid-cols-2" value={selectedFetchModels} options={fetchModelOptions} onChange={(values) => setSelectedFetchModels(values as string[])} />
|
||||
<Checkbox.Group
|
||||
className="channel-model-import-picker grid w-full grid-cols-1 gap-2 sm:grid-cols-2"
|
||||
value={selectedFetchModels}
|
||||
options={fetchModelOptions}
|
||||
disabled={importing}
|
||||
onChange={(values) => setSelectedFetchModels(values as string[])}
|
||||
/>
|
||||
</div>
|
||||
<div className="text-xs text-foreground/50">
|
||||
{selectedNewFetchModels.length > 0 ? `将导入 ${selectedNewFetchModels.length} 个新模型` : "当前勾选的模型均已存在"}
|
||||
|
||||
@@ -32,6 +32,7 @@ export default function AppearanceSettingsPage() {
|
||||
const [brandSlug, setBrandSlug] = useState("");
|
||||
const [authHeroTitle, setAuthHeroTitle] = useState("");
|
||||
const [authHeroDescription, setAuthHeroDescription] = useState("");
|
||||
const [authVideoAutoplay, setAuthVideoAutoplay] = useState(true);
|
||||
const [logoFrameEnabled, setLogoFrameEnabled] = useState(true);
|
||||
const [skinId, setSkinId] = useState("classic");
|
||||
const [skinThemes, setSkinThemes] = useState<SkinDefinition[]>([DEFAULT_CLASSIC_SKIN]);
|
||||
@@ -62,6 +63,7 @@ export default function AppearanceSettingsPage() {
|
||||
brandSlug.trim().toLocaleLowerCase() !== setting?.brandSlug ||
|
||||
normalizeDraftCopy(authHeroTitle) !== setting?.authHeroTitle ||
|
||||
normalizeDraftCopy(authHeroDescription) !== setting?.authHeroDescription ||
|
||||
authVideoAutoplay !== setting?.authVideoAutoplay ||
|
||||
logoFrameEnabled !== setting?.logoFrameEnabled ||
|
||||
skinId !== setting?.skinId ||
|
||||
JSON.stringify(skinThemes) !== JSON.stringify(setting?.skinThemes) ||
|
||||
@@ -81,6 +83,7 @@ export default function AppearanceSettingsPage() {
|
||||
setBrandSlug(value.brandSlug);
|
||||
setAuthHeroTitle(value.authHeroTitle);
|
||||
setAuthHeroDescription(value.authHeroDescription);
|
||||
setAuthVideoAutoplay(value.authVideoAutoplay);
|
||||
setLogoFrameEnabled(value.logoFrameEnabled);
|
||||
const themes = value.skinThemes.map((theme) => normalizeSkinDefinition(theme));
|
||||
setSkinThemes(themes.length ? themes : [cloneSkinDefinition(DEFAULT_CLASSIC_SKIN)]);
|
||||
@@ -190,6 +193,7 @@ export default function AppearanceSettingsPage() {
|
||||
setBrandSlug(setting.brandSlug);
|
||||
setAuthHeroTitle(setting.authHeroTitle);
|
||||
setAuthHeroDescription(setting.authHeroDescription);
|
||||
setAuthVideoAutoplay(setting.authVideoAutoplay);
|
||||
setLogoFrameEnabled(setting.logoFrameEnabled);
|
||||
setSkinId(setting.skinId);
|
||||
setSkinThemes(setting.skinThemes.map((theme) => cloneSkinDefinition(theme)));
|
||||
@@ -325,6 +329,7 @@ export default function AppearanceSettingsPage() {
|
||||
logoFrameEnabled,
|
||||
authVideoResourceId: ids.video,
|
||||
authVideoPosterResourceId: ids.poster,
|
||||
authVideoAutoplay,
|
||||
skinId,
|
||||
skinThemes,
|
||||
seoTitle: nextSeoTitle,
|
||||
@@ -548,6 +553,16 @@ export default function AppearanceSettingsPage() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<div className="admin-appearance-media-list">
|
||||
<div className="admin-appearance-video-autoplay-option">
|
||||
<span className="admin-appearance-video-autoplay-copy">
|
||||
<strong>登录页视频自动播放</strong>
|
||||
<small>默认开启并静音循环播放;访客启用“减少动态效果”时仍尊重其系统偏好。</small>
|
||||
</span>
|
||||
<span className="admin-appearance-video-autoplay-control">
|
||||
<span>{authVideoAutoplay ? "已开启" : "已关闭"}</span>
|
||||
<Switch checked={authVideoAutoplay} disabled={saving || refreshing || restoring} aria-label="登录页视频自动播放" onChange={setAuthVideoAutoplay} />
|
||||
</span>
|
||||
</div>
|
||||
<AssetPicker
|
||||
slot="video"
|
||||
title="品牌视频"
|
||||
@@ -581,7 +596,7 @@ export default function AppearanceSettingsPage() {
|
||||
<AdminStatusBadge label={dirty ? "未保存" : "线上版本"} tone={dirty ? "warning" : "success"} />
|
||||
</div>
|
||||
<div className="admin-appearance-preview-stage">
|
||||
<video key={previews.video} src={previews.video} poster={previews.poster || undefined} muted loop playsInline autoPlay preload="metadata" />
|
||||
<video key={`${previews.video}-${authVideoAutoplay}`} src={previews.video} poster={previews.poster || undefined} muted loop playsInline autoPlay={authVideoAutoplay} preload="metadata" />
|
||||
<span className="admin-appearance-preview-shade" />
|
||||
<span className="admin-appearance-preview-brand">
|
||||
<img src={previews.logoDark} alt="" />
|
||||
|
||||
215
web/src/pages/admin/settings/system-performance-page.tsx
Normal file
215
web/src/pages/admin/settings/system-performance-page.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
import { App, Button, Progress, Skeleton, Switch } from "antd";
|
||||
import { Activity, AlertTriangle, Cpu, Database, Gauge, HardDrive, MemoryStick, RefreshCw, Server, ShieldCheck, Trash2, Wifi } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import { clearRuntimeCache, getSystemPerformance, type SystemPerformance } from "@/services/api/system-performance";
|
||||
import { AdminPageFrame } from "../components/admin-shell";
|
||||
import { AdminStatusBadge, SettingsSectionCard } from "../components/admin-ui";
|
||||
|
||||
const refreshIntervalMs = 15_000;
|
||||
|
||||
function formatBytes(value?: number) {
|
||||
if (!value || value < 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1);
|
||||
const amount = value / 1024 ** index;
|
||||
return `${amount >= 100 || index === 0 ? amount.toFixed(0) : amount.toFixed(1)} ${units[index]}`;
|
||||
}
|
||||
|
||||
function formatDuration(seconds?: number) {
|
||||
if (!seconds) return "不足 1 分钟";
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
return [days ? `${days} 天` : "", hours ? `${hours} 小时` : "", minutes ? `${minutes} 分钟` : ""].filter(Boolean).slice(0, 2).join(" ") || "不足 1 分钟";
|
||||
}
|
||||
|
||||
function formatNumber(value?: number) {
|
||||
return new Intl.NumberFormat("zh-CN").format(value || 0);
|
||||
}
|
||||
|
||||
function metricTone(value: number) {
|
||||
if (value >= 90) return "exception" as const;
|
||||
if (value >= 75) return "active" as const;
|
||||
return "normal" as const;
|
||||
}
|
||||
|
||||
function FactGrid({ children }: { children: ReactNode }) {
|
||||
return <dl className="admin-performance-facts">{children}</dl>;
|
||||
}
|
||||
|
||||
function Fact({ label, value, mono = false }: { label: string; value: ReactNode; mono?: boolean }) {
|
||||
return <><dt>{label}</dt><dd className={mono ? "admin-monospace" : undefined}>{value}</dd></>;
|
||||
}
|
||||
|
||||
function PerformanceKpi({ icon, label, value, detail, percent }: { icon: ReactNode; label: string; value: string; detail: string; percent?: number }) {
|
||||
return (
|
||||
<article className="admin-performance-kpi">
|
||||
<div className="admin-performance-kpi-heading"><span>{icon}</span><p>{label}</p></div>
|
||||
<strong>{value}</strong>
|
||||
<p>{detail}</p>
|
||||
{percent !== undefined ? <Progress percent={Math.min(100, Math.max(0, percent))} status={metricTone(percent)} showInfo={false} size="small" /> : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SystemPerformancePage() {
|
||||
const { message, modal } = App.useApp();
|
||||
const [data, setData] = useState<SystemPerformance | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
const [loadError, setLoadError] = useState("");
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
const load = useCallback(async (initial = false) => {
|
||||
if (initial) setLoading(true);
|
||||
else setRefreshing(true);
|
||||
try {
|
||||
const next = await getSystemPerformance();
|
||||
if (!mountedRef.current) return;
|
||||
setData(next);
|
||||
setLoadError("");
|
||||
} catch (error) {
|
||||
if (!mountedRef.current) return;
|
||||
setLoadError(error instanceof Error ? error.message : "读取系统性能失败");
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
void load(true);
|
||||
return () => { mountedRef.current = false; };
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoRefresh) return;
|
||||
const timer = window.setInterval(() => void load(false), refreshIntervalMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [autoRefresh, load]);
|
||||
|
||||
const requestClear = () => {
|
||||
modal.confirm({
|
||||
title: "清理运行时缓存?",
|
||||
width: 560,
|
||||
icon: <AlertTriangle className="size-5 text-warning" />,
|
||||
content: (
|
||||
<div className="admin-performance-confirm">
|
||||
<p>将重置请求频控计数、渠道失败/熔断状态、线路临时禁用状态和本进程只读缓存。</p>
|
||||
<p><strong>不会删除</strong>用户、任务、素材、模型配置和数据库数据,也不会触碰正在使用的并发租约。</p>
|
||||
<p>清理后短时间内上游线路会重新探测,请避开流量高峰频繁操作。</p>
|
||||
</div>
|
||||
),
|
||||
okText: "确认清理",
|
||||
okButtonProps: { danger: true, loading: clearing },
|
||||
cancelText: "取消",
|
||||
onOk: async () => {
|
||||
setClearing(true);
|
||||
try {
|
||||
const result = await clearRuntimeCache();
|
||||
message.success(`已清理 ${result.deletedKeys} 个 Redis/本地键、${result.memoryEntries} 个内存缓存项`);
|
||||
await load(false);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "清理运行时缓存失败");
|
||||
throw error;
|
||||
} finally {
|
||||
setClearing(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <AdminPageFrame title="系统性能" description="服务器、数据库与运行时缓存状态。" scroll><div className="admin-settings-stack admin-system-performance"><Skeleton active paragraph={{ rows: 14 }} /></div></AdminPageFrame>;
|
||||
}
|
||||
|
||||
const memoryPercent = data?.memory.systemAvailable ? data.memory.usagePercent : undefined;
|
||||
const databaseConnections = data?.database.postgres?.connections ?? data?.database.pool.openConnections ?? 0;
|
||||
const databaseLimit = data?.database.postgres?.maxConnections || data?.database.pool.maxOpenConnections || 0;
|
||||
const databasePercent = databaseLimit ? databaseConnections / databaseLimit * 100 : undefined;
|
||||
const redisPoolRequests = (data?.redis.pool.hits || 0) + (data?.redis.pool.misses || 0);
|
||||
const redisPoolHitRate = redisPoolRequests ? (data?.redis.pool.hits || 0) / redisPoolRequests * 100 : 0;
|
||||
|
||||
return (
|
||||
<AdminPageFrame
|
||||
title="系统性能"
|
||||
description="紧凑查看主机、数据库、Redis 和安全运行时缓存;敏感连接信息不会在此展示。"
|
||||
scroll
|
||||
actions={<><label className="admin-performance-auto"><Switch size="small" checked={autoRefresh} onChange={setAutoRefresh} /><span>15 秒刷新</span></label><Button icon={<RefreshCw className="size-4" />} loading={refreshing} onClick={() => void load(false)}>刷新</Button></>}
|
||||
>
|
||||
<div className="admin-settings-stack admin-system-performance">
|
||||
{loadError ? <div className="admin-performance-alert"><AlertTriangle className="size-4" /><span>{loadError}</span><Button size="small" onClick={() => void load(false)}>重试</Button></div> : null}
|
||||
<div className="admin-performance-statusbar">
|
||||
<div><AdminStatusBadge label={data?.status === "healthy" ? "系统运行正常" : "部分服务降级"} tone={data?.status === "healthy" ? "success" : "warning"} /><span>采集于 {data ? new Date(data.collectedAt).toLocaleString("zh-CN", { hour12: false }) : "--"}</span></div>
|
||||
<span>进程已运行 {formatDuration(data?.host.uptimeSeconds)}</span>
|
||||
</div>
|
||||
|
||||
<section className="admin-performance-kpis" aria-label="核心性能指标">
|
||||
<PerformanceKpi icon={<MemoryStick className="size-4" />} label={memoryPercent !== undefined ? "系统内存" : "进程堆内存"} value={memoryPercent !== undefined ? `${memoryPercent.toFixed(1)}%` : formatBytes(data?.memory.heapAllocBytes)} detail={memoryPercent !== undefined ? `${formatBytes(data?.memory.usedBytes)} / ${formatBytes(data?.memory.totalBytes)}` : `Go 已保留 ${formatBytes(data?.memory.heapSysBytes)}`} percent={memoryPercent} />
|
||||
<PerformanceKpi icon={<HardDrive className="size-4" />} label="数据磁盘" value={data?.disk.available ? `${data.disk.usagePercent.toFixed(1)}%` : "不可用"} detail={data?.disk.available ? `${formatBytes(data.disk.usedBytes)} / ${formatBytes(data.disk.totalBytes)}` : "无法读取文件系统指标"} percent={data?.disk.available ? data.disk.usagePercent : undefined} />
|
||||
<PerformanceKpi icon={<Database className="size-4" />} label={data?.database.driver === "postgres" ? "PostgreSQL 连接" : "数据库连接"} value={`${databaseConnections}${databaseLimit ? ` / ${databaseLimit}` : ""}`} detail={`${data?.database.driver || "--"} · ${data?.database.latencyMs || 0} ms`} percent={databasePercent} />
|
||||
<PerformanceKpi icon={<Wifi className="size-4" />} label="Redis" value={data?.redis.connected ? formatBytes(data.redis.usedMemoryBytes) : data?.redis.mode === "local" ? "本地模式" : "连接异常"} detail={data?.redis.connected ? `${formatNumber(data.redis.keys)} keys · ${formatNumber(data.redis.opsPerSecond)} ops/s` : data?.redis.statusMessage || "未连接"} />
|
||||
</section>
|
||||
|
||||
<div className="admin-performance-grid">
|
||||
<SettingsSectionCard layout="stacked" icon={<Server className="size-4" />} title="服务器与进程" description="操作系统、运行时和当前进程快照。" status={{ label: data?.disk.writable ? "数据目录可写" : "数据目录不可写", color: data?.disk.writable ? "success" : "error" }}>
|
||||
<FactGrid>
|
||||
<Fact label="主机" value={data?.host.hostname || "未识别"} mono />
|
||||
<Fact label="系统" value={`${data?.host.os || "--"} / ${data?.host.arch || "--"}`} />
|
||||
<Fact label="CPU" value={`${data?.host.cpuCores || 0} 逻辑核 · GOMAXPROCS ${data?.host.gomaxprocs || 0}`} />
|
||||
<Fact label="负载 1/5/15" value={data?.host.loadAverageAvailable ? data.host.loadAverage.map((value) => value.toFixed(2)).join(" / ") : "当前平台未提供"} mono />
|
||||
<Fact label="进程" value={`PID ${data?.host.processId || 0} · ${formatNumber(data?.host.goroutines)} goroutines`} />
|
||||
<Fact label="任务" value={`${formatNumber(data?.host.activeWorkerTasks)} 个 Worker 正在执行`} />
|
||||
<Fact label="构建" value={`${data?.build.version || "dev"} · ${data?.build.goVersion || "--"}`} />
|
||||
<Fact label="提交" value={(data?.build.commit || "unknown").slice(0, 12)} mono />
|
||||
</FactGrid>
|
||||
<div className="admin-performance-submetrics">
|
||||
<div><span>Heap Alloc</span><strong>{formatBytes(data?.memory.heapAllocBytes)}</strong></div>
|
||||
<div><span>Go Sys</span><strong>{formatBytes(data?.memory.sysBytes)}</strong></div>
|
||||
<div><span>Heap Objects</span><strong>{formatNumber(data?.memory.heapObjects)}</strong></div>
|
||||
<div><span>GC 次数</span><strong>{formatNumber(data?.memory.gcCount)}</strong></div>
|
||||
</div>
|
||||
</SettingsSectionCard>
|
||||
|
||||
<div className="admin-performance-side-stack">
|
||||
<SettingsSectionCard layout="stacked" icon={<Database className="size-4" />} title="数据库" description="连接池、结构版本与数据库内部统计。" status={{ label: data?.database.connected ? "连接正常" : "连接异常", color: data?.database.connected ? "success" : "error" }}>
|
||||
<FactGrid>
|
||||
<Fact label="驱动" value={data?.database.driver === "postgres" ? "PostgreSQL" : data?.database.driver || "未知"} />
|
||||
<Fact label="结构版本" value={`${data?.database.schema.current || 0} / ${data?.database.schema.expected || 0} ${data?.database.schema.ready ? "(已就绪)" : "(待检查)"}`} />
|
||||
<Fact label="数据库大小" value={formatBytes(data?.database.databaseBytes)} />
|
||||
<Fact label="连接池" value={`${data?.database.pool.inUse || 0} 使用中 · ${data?.database.pool.idle || 0} 空闲 · ${data?.database.pool.waitCount || 0} 次等待`} />
|
||||
{data?.database.postgres ? <><Fact label="版本" value={data.database.postgres.serverVersion || "未知"} mono /><Fact label="缓存命中" value={`${(data.database.postgres.cacheHitRate || 0).toFixed(2)}%`} /><Fact label="事务 / 回滚" value={`${formatNumber(data.database.postgres.transactions)} / ${formatNumber(data.database.postgres.rollbacks)}`} /><Fact label="临时文件 / 死锁" value={`${formatNumber(data.database.postgres.tempFiles)} / ${formatNumber(data.database.postgres.deadlocks)}`} /></> : <Fact label="PostgreSQL 指标" value="当前使用 SQLite,不适用" />}
|
||||
</FactGrid>
|
||||
</SettingsSectionCard>
|
||||
|
||||
<SettingsSectionCard layout="stacked" icon={<Activity className="size-4" />} title="Redis" description="内存、客户端、命中率与连接池。" status={{ label: data?.redis.connected ? "连接正常" : data?.redis.mode === "local" ? "本地降级" : "连接异常", color: data?.redis.connected ? "success" : data?.redis.mode === "local" ? "warning" : "error" }}>
|
||||
<FactGrid>
|
||||
<Fact label="模式 / 版本" value={data?.redis.connected ? `Redis ${data.redis.version || "未知"}` : data?.redis.statusMessage || "未配置"} />
|
||||
<Fact label="运行时间" value={data?.redis.connected ? formatDuration(data.redis.uptimeSeconds) : "--"} />
|
||||
<Fact label="内存峰值" value={data?.redis.connected ? formatBytes(data.redis.peakMemoryBytes) : "--"} />
|
||||
<Fact label="淘汰策略" value={data?.redis.maxMemoryPolicy || "未配置"} mono />
|
||||
<Fact label="客户端" value={`${formatNumber(data?.redis.clients)} 连接 · ${formatNumber(data?.redis.blockedClients)} 阻塞`} />
|
||||
<Fact label="Key 命中率" value={`${(data?.redis.hitRate || 0).toFixed(2)}%`} />
|
||||
<Fact label="客户端池命中" value={`${redisPoolHitRate.toFixed(2)}% · ${formatNumber(data?.redis.pool.totalConnections)} 连接`} />
|
||||
<Fact label="超时 / 淘汰" value={`${formatNumber(data?.redis.pool.timeouts)} / ${formatNumber(data?.redis.evictedKeys)}`} />
|
||||
</FactGrid>
|
||||
</SettingsSectionCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingsSectionCard layout="stacked" icon={<ShieldCheck className="size-4" />} title="缓存维护" description="只清理可安全重建的运行时状态,保留业务数据与活动并发租约。" status={<AdminStatusBadge label="白名单清理" tone="success" />} footer={<><span className="admin-performance-cache-note"><Gauge className="size-3.5" />清理后频控与线路健康状态会重新计算</span><Button danger icon={<Trash2 className="size-4" />} loading={clearing} onClick={requestClear}>清理运行时缓存</Button></>}>
|
||||
<div className="admin-performance-cache-groups">
|
||||
{(data?.redis.cacheGroups || []).map((group) => <div key={group.id}><span>{group.label}</span><strong>{formatNumber(group.keys)}</strong><small>keys</small></div>)}
|
||||
</div>
|
||||
<div className="admin-performance-safety"><strong>始终保留</strong><span>用户与任务数据</span><span>素材和模型配置</span><span>活动并发租约</span><span>跨实例目录版本</span></div>
|
||||
</SettingsSectionCard>
|
||||
</div>
|
||||
</AdminPageFrame>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import { Eye, Pencil, Power, Trash2 } from "lucide-react";
|
||||
import { Eye, Pencil, Power } from "lucide-react";
|
||||
|
||||
import { formatCredits } from "@/constant/credits";
|
||||
import { IdentityProviderBadge } from "@/components/layout/identity-provider-badge";
|
||||
@@ -24,14 +24,12 @@ export function createUserColumns({
|
||||
onView,
|
||||
onEdit,
|
||||
onToggleStatus,
|
||||
onPurge,
|
||||
}: {
|
||||
actorId?: string;
|
||||
visibleColumns: Set<UserColumnKey>;
|
||||
onView: (user: AdminUser) => void;
|
||||
onEdit: (user: AdminUser) => void;
|
||||
onToggleStatus: (user: AdminUser) => Promise<void>;
|
||||
onPurge: (user: AdminUser) => void;
|
||||
}): ColumnsType<AdminUser> {
|
||||
const columns: Array<ColumnsType<AdminUser>[number] & { key: UserColumnKey }> = [
|
||||
{
|
||||
@@ -81,19 +79,6 @@ export function createUserColumns({
|
||||
},
|
||||
onClick: () => onToggleStatus(user),
|
||||
},
|
||||
{
|
||||
key: "purge",
|
||||
label: "删除用户",
|
||||
icon: <Trash2 className="size-3.5" />,
|
||||
danger: true,
|
||||
disabled: user.id === actorId,
|
||||
confirm: {
|
||||
title: "彻底删除这个用户?",
|
||||
description: "该账号及其全部关联数据将被永久移除且不可恢复。停用可保留数据,仅当账号无资金流水和创作内容时才允许删除。",
|
||||
okText: "彻底删除",
|
||||
},
|
||||
onClick: () => onPurge(user),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { PaginationBar } from "@/components/layout/workspace-page";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { bulkDisableAdminUsers, deleteAdminUser, listAdminUsers, purgeAdminUser, updateAdminUser, type AdminUser, type LocalUser } from "@/services/api/auth";
|
||||
import { bulkDisableAdminUsers, deleteAdminUser, listAdminUsers, updateAdminUser, type AdminUser, type LocalUser } from "@/services/api/auth";
|
||||
import { useUserStore } from "@/stores/use-user-store";
|
||||
import { AdminBatchBar, AdminDataTable, AdminTableEmpty } from "../components/admin-ui";
|
||||
import { useTableUrlState } from "../lib/use-table-url-state";
|
||||
@@ -102,27 +102,13 @@ export default function UsersPanel({ onUserChanged }: { onUserChanged?: (user: L
|
||||
}
|
||||
}, [message, replaceUser]);
|
||||
|
||||
const purgeUser = useCallback(async (user: AdminUser) => {
|
||||
try {
|
||||
await purgeAdminUser(user.id);
|
||||
setUsers((items) => items.filter((item) => item.id !== user.id));
|
||||
setTotal((value) => Math.max(0, value - 1));
|
||||
setSelectedUserIds((ids) => ids.filter((id) => id !== user.id));
|
||||
if (detailUserId === user.id) setDetailUserId(null);
|
||||
message.success(`用户 ${user.displayName || user.username} 已彻底删除`);
|
||||
} catch (error) {
|
||||
message.error(error instanceof Error ? error.message : "删除用户失败");
|
||||
}
|
||||
}, [detailUserId, message]);
|
||||
|
||||
const columns = useMemo(() => createUserColumns({
|
||||
actorId: actor?.id,
|
||||
visibleColumns,
|
||||
onView: (user) => setDetailUserId(user.id),
|
||||
onEdit: (user) => { setCreateUserOpen(false); setEditingUser(user); },
|
||||
onToggleStatus: toggleStatus,
|
||||
onPurge: purgeUser,
|
||||
}), [actor?.id, purgeUser, toggleStatus, visibleColumns]);
|
||||
}), [actor?.id, toggleStatus, visibleColumns]);
|
||||
|
||||
const resetFilters = () => update({ filter: "", role: "all", status: "all", page: 1 });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user