fix(merge): 本地整合 - 保留主分支交互与样式并排除不安全用户删除
This commit is contained in:
commit
14adaa1e99
100 files changed
+4845
-865
No files matched your search
@@ -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="" />
|
||||
|
||||
@@ -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 });
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { motion, useReducedMotion } from "motion/react";
|
||||
import { ConfigProvider, Tabs } from "antd";
|
||||
import { ArrowLeft, Play } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, Outlet, useLocation, useNavigate } from "react-router";
|
||||
|
||||
import { BrandLogo } from "@/components/brand/brand-logo";
|
||||
@@ -51,17 +51,33 @@ export function AuthScene() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const reducedMotion = useReducedMotion();
|
||||
const [videoActive, setVideoActive] = useState(false);
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const [manualVideoActive, setManualVideoActive] = useState(false);
|
||||
const [videoPlaying, setVideoPlaying] = useState(false);
|
||||
const [failedPosterURL, setFailedPosterURL] = useState("");
|
||||
const recovery = location.pathname === "/forgot-password";
|
||||
const activeTab = location.pathname === "/register" ? "register" : "login";
|
||||
const copy = recovery ? authCopy.recovery : activeTab === "register" ? authCopy.register : authCopy.login;
|
||||
const automaticVideoActive = appearance.authVideoAutoplay && !reducedMotion;
|
||||
const videoActive = Boolean(appearance.authVideoUrl && (automaticVideoActive || manualVideoActive));
|
||||
|
||||
useEffect(() => {
|
||||
setManualVideoActive(false);
|
||||
setVideoPlaying(false);
|
||||
}, [appearance.authVideoUrl, appearance.authVideoAutoplay]);
|
||||
|
||||
const playVideo = () => {
|
||||
setManualVideoActive(true);
|
||||
requestAnimationFrame(() => {
|
||||
void videoRef.current?.play().catch(() => setVideoPlaying(false));
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="auth-scene h-dvh min-h-0 overflow-y-auto text-white lg:overflow-hidden">
|
||||
<div className="grid min-h-full lg:h-full lg:grid-cols-[minmax(0,1.32fr)_minmax(520px,1fr)]">
|
||||
<section className="relative min-h-[250px] overflow-hidden sm:min-h-[320px] lg:min-h-0" aria-label={`${appearance.brandName}品牌影片`}>
|
||||
{videoActive && appearance.authVideoUrl ? <video className="absolute inset-0 size-full object-cover" src={appearance.authVideoUrl} poster={appearance.authVideoPosterUrl || undefined} autoPlay={!reducedMotion} muted loop playsInline preload="metadata" /> : appearance.authVideoPosterUrl && failedPosterURL !== appearance.authVideoPosterUrl ? <img className="absolute inset-0 size-full object-cover" src={appearance.authVideoPosterUrl} alt="" decoding="async" onError={() => setFailedPosterURL(appearance.authVideoPosterUrl)} /> : null}
|
||||
{videoActive && appearance.authVideoUrl ? <video ref={videoRef} className="absolute inset-0 size-full object-cover" src={appearance.authVideoUrl} poster={appearance.authVideoPosterUrl || undefined} autoPlay muted loop playsInline preload="metadata" onPlay={() => setVideoPlaying(true)} onPause={() => setVideoPlaying(false)} /> : appearance.authVideoPosterUrl && failedPosterURL !== appearance.authVideoPosterUrl ? <img className="absolute inset-0 size-full object-cover" src={appearance.authVideoPosterUrl} alt="" decoding="async" onError={() => setFailedPosterURL(appearance.authVideoPosterUrl)} /> : null}
|
||||
<div aria-hidden className="absolute inset-0 bg-[linear-gradient(180deg,rgba(4,5,8,.58),transparent_42%,rgba(4,5,8,.74))]" />
|
||||
<div aria-hidden className="auth-scene-video-blend absolute inset-y-0 right-0 hidden w-[clamp(120px,14vw,240px)] lg:block" />
|
||||
<div className="absolute inset-x-0 top-0 flex items-center justify-between gap-4 p-5 sm:p-7 lg:p-9">
|
||||
@@ -69,9 +85,9 @@ export function AuthScene() {
|
||||
<BrandLogo theme="dark" className="size-7" alt="" fallback={<span className="size-7 bg-current" style={{ mask: "url(/logo.svg) center / contain no-repeat", WebkitMask: "url(/logo.svg) center / contain no-repeat" }} />} />
|
||||
{appearance.brandName}
|
||||
</Link>
|
||||
<button type="button" className="inline-flex items-center gap-2 rounded-full border border-white/16 bg-black/20 px-3 py-1.5 text-[var(--fs-label)] text-white/76 backdrop-blur-xl transition hover:bg-black/35 disabled:cursor-default" onClick={() => setVideoActive(true)} disabled={videoActive || !appearance.authVideoUrl} aria-pressed={videoActive}>
|
||||
<button type="button" className="inline-flex items-center gap-2 rounded-full border border-white/16 bg-black/20 px-3 py-1.5 text-[var(--fs-label)] text-white/76 backdrop-blur-xl transition hover:bg-black/35 disabled:cursor-default" onClick={playVideo} disabled={videoPlaying || !appearance.authVideoUrl} aria-pressed={videoPlaying}>
|
||||
<Play className="size-3 fill-current" />
|
||||
{videoActive ? "创作正在发生" : "播放品牌影片"}
|
||||
{videoPlaying ? "创作正在发生" : "播放品牌影片"}
|
||||
</button>
|
||||
</div>
|
||||
<motion.div
|
||||
|
||||
@@ -52,7 +52,6 @@ export async function executeImageGeneration({
|
||||
const isConfigNode = sourceNode?.type === CanvasNodeType.Config;
|
||||
const isImageNode = sourceNode?.type === CanvasNodeType.Image;
|
||||
const reuseSourceNode = canGenerateImageInPlace(sourceNode);
|
||||
const directCopiedBatch = count > 1 && isImageNode && Boolean(sourceNode?.metadata?.content) && reuseSourceNode;
|
||||
// 已有图片生成新结果并保留旧版本;参考图只来自入边,避免把旧结果误当成自身输入。
|
||||
const referenceImages = generationContext.referenceImages;
|
||||
const generationType = referenceImages.length ? ("edit" as const) : ("generation" as const);
|
||||
@@ -69,10 +68,10 @@ export async function executeImageGeneration({
|
||||
const parentPosition = sourceNode?.position || { x: 0, y: 0 };
|
||||
const parentWidth = sourceNode?.width || parentConfig.width;
|
||||
const parentHeight = sourceNode?.height || parentConfig.height;
|
||||
const rootId = reuseSourceNode || directCopiedBatch ? nodeId : nanoid();
|
||||
const rootId = reuseSourceNode ? nodeId : nanoid();
|
||||
const childIds = count > 1 ? Array.from({ length: count }, () => nanoid()) : [];
|
||||
const targetIds = count > 1 ? childIds : [rootId];
|
||||
registerPendingNodeIds(reuseSourceNode || directCopiedBatch ? childIds : [rootId, ...childIds]);
|
||||
registerPendingNodeIds(reuseSourceNode ? childIds : [rootId, ...childIds]);
|
||||
const rootWidth = outputNodeSize.width;
|
||||
const rootHeight = outputNodeSize.height;
|
||||
const preferredPosition = {
|
||||
@@ -102,7 +101,7 @@ export async function executeImageGeneration({
|
||||
...generationMetadata,
|
||||
...styleMetadata,
|
||||
...skillMetadata,
|
||||
imageBatchExpanded: count > 1 ? true : undefined,
|
||||
imageBatchExpanded: count > 1 ? false : undefined,
|
||||
generationErrorCode: undefined,
|
||||
resourceReloadAvailable: undefined,
|
||||
failedPromptFingerprint: undefined,
|
||||
@@ -119,7 +118,7 @@ export async function executeImageGeneration({
|
||||
...canvasGenerationPromptMetadata(prompt, effectivePrompt),
|
||||
status: NODE_STATUS_LOADING,
|
||||
size: generationConfig.size,
|
||||
batchRootId: count > 1 && !directCopiedBatch ? rootId : undefined,
|
||||
batchRootId: rootId,
|
||||
...generationMetadata,
|
||||
...styleMetadata,
|
||||
...skillMetadata,
|
||||
@@ -128,9 +127,7 @@ export async function executeImageGeneration({
|
||||
failedPromptFingerprint: undefined,
|
||||
},
|
||||
}));
|
||||
const batchConnections = directCopiedBatch
|
||||
? childIds.map((childId) => ({ id: nanoid(), fromNodeId: nodeId, toNodeId: childId }))
|
||||
: [...(reuseSourceNode ? [] : [{ id: nanoid(), fromNodeId: nodeId, toNodeId: rootId }]), ...childIds.map((childId) => ({ id: nanoid(), fromNodeId: rootId, toNodeId: childId }))];
|
||||
const batchConnections = [...(reuseSourceNode ? [] : [{ id: nanoid(), fromNodeId: nodeId, toNodeId: rootId }]), ...childIds.map((childId) => ({ id: nanoid(), fromNodeId: rootId, toNodeId: childId }))];
|
||||
|
||||
const nextNodes: CanvasNodeData[] = [
|
||||
...canvasNodes.map((node) => {
|
||||
@@ -147,7 +144,7 @@ export async function executeImageGeneration({
|
||||
metadata: { ...node.metadata, content: prompt, richText: undefined, prompt, composerContent: prompt, status: NODE_STATUS_SUCCESS, fontSize: 14, errorDetails: undefined },
|
||||
};
|
||||
}),
|
||||
...(reuseSourceNode || directCopiedBatch ? [] : [rootNode]),
|
||||
...(reuseSourceNode ? [] : [rootNode]),
|
||||
...childNodes,
|
||||
];
|
||||
|
||||
@@ -164,7 +161,7 @@ export async function executeImageGeneration({
|
||||
setDialogNodeId(nodeId);
|
||||
|
||||
targetIds.forEach((targetId) => startGenerationRequest(targetId, nodeId, nodeId, controller));
|
||||
if (count > 1 && !directCopiedBatch) startGenerationRequest(rootId, nodeId, nodeId, controller);
|
||||
if (count > 1) startGenerationRequest(rootId, nodeId, nodeId, controller);
|
||||
let hasSuccess = false;
|
||||
let hasFailure = false;
|
||||
let failureCount = 0;
|
||||
@@ -197,7 +194,7 @@ export async function executeImageGeneration({
|
||||
consumeTask: (task) => applyGenerationTaskResult(targetId, task),
|
||||
},
|
||||
);
|
||||
if (targetId !== rootId && !directCopiedBatch) {
|
||||
if (targetId !== rootId) {
|
||||
setNodes((current) => {
|
||||
const child = current.find((node) => node.id === targetId);
|
||||
const root = current.find((node) => node.id === rootId);
|
||||
@@ -254,7 +251,7 @@ export async function executeImageGeneration({
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (count > 1 && !directCopiedBatch) finishGenerationRequest(rootId, controller);
|
||||
if (count > 1) finishGenerationRequest(rootId, controller);
|
||||
if (controller.signal.aborted) {
|
||||
setNodes((current) => current.map((node) => (node.id === nodeId && isConfigNode && node.metadata?.status === NODE_STATUS_LOADING ? { ...node, metadata: { ...node.metadata, status: NODE_STATUS_IDLE, errorDetails: undefined } } : node)));
|
||||
return;
|
||||
@@ -272,7 +269,7 @@ export async function executeImageGeneration({
|
||||
},
|
||||
};
|
||||
}
|
||||
if (node.id === rootId && (reuseSourceNode || !directCopiedBatch)) {
|
||||
if (node.id === rootId) {
|
||||
return {
|
||||
...node,
|
||||
metadata: {
|
||||
|
||||
@@ -90,6 +90,13 @@ export const CanvasProjectWorldLayers = memo(function CanvasProjectWorldLayers(p
|
||||
...props.visibleNodes.filter(isFrameNode),
|
||||
...sortCanvasNodesByStackOrder(props.visibleNodes.filter((node) => !isFrameNode(node)), props.nodeStackOrder),
|
||||
], [props.nodeStackOrder, props.visibleNodes]);
|
||||
const batchPreviews = useMemo(() => new Map(props.visibleNodes.filter((node) => node.metadata?.isBatchRoot).map((node) => [
|
||||
node.id,
|
||||
(node.metadata?.batchChildIds || []).filter((id) => id !== node.metadata?.primaryImageId)
|
||||
.map((id) => props.nodeById.get(id))
|
||||
.filter((child): child is CanvasNodeData => Boolean(child && child.metadata?.batchRootId === node.id))
|
||||
.slice(0, 5),
|
||||
])), [props.visibleNodes, props.nodeById]);
|
||||
const framePreviewNodes = (node: CanvasNodeData) => {
|
||||
const assetFolderId = node.metadata?.folder?.assetFolderId;
|
||||
if (assetFolderId) return props.linkedFolderPreviewNodesById.get(assetFolderId) || EMPTY_CANVAS_NODES;
|
||||
@@ -155,8 +162,9 @@ export const CanvasProjectWorldLayers = memo(function CanvasProjectWorldLayers(p
|
||||
forceInputVisible={Boolean(props.batchConnectionPreview)}
|
||||
batchCount={props.batchChildCountById.get(node.id) || 0}
|
||||
batchExpanded={Boolean(node.metadata?.imageBatchExpanded)}
|
||||
batchPreviewNodes={batchPreviews.get(node.id)}
|
||||
batchClosing={Boolean(node.metadata?.batchRootId && props.collapsingBatchIds.has(node.metadata.batchRootId))}
|
||||
batchOpening={props.openingBatchIds.has(node.id)}
|
||||
batchOpening={props.openingBatchIds.has(node.metadata?.batchRootId || node.id)}
|
||||
batchRecovering={props.collapsingBatchIds.has(node.id)}
|
||||
batchPrimary={Boolean(node.metadata?.batchRootId && props.nodeById.get(node.metadata.batchRootId)?.metadata?.primaryImageId === node.id)}
|
||||
batchMotion={props.batchMotionById.get(node.id)}
|
||||
|
||||
@@ -70,7 +70,7 @@ import { CanvasVersionCompareModal } from "@/components/canvas/canvas-version-co
|
||||
import { CanvasLocalAgentPanel } from "@/components/canvas/canvas-local-agent-panel";
|
||||
import { useFocusMode } from "@/hooks/use-focus-mode";
|
||||
import { useCanvasAgentStore } from "@/stores/canvas/use-canvas-agent-store";
|
||||
import { getContextResourceNodes, normalizeCanvasNodeMentionTokens, type CanvasResourceReference } from "@/lib/canvas/canvas-resource-references";
|
||||
import { applyCanvasConnectionPromptSync, getContextResourceNodes, normalizeCanvasNodeMentionTokens, type CanvasResourceReference } from "@/lib/canvas/canvas-resource-references";
|
||||
import { CanvasConnectionCreateMenu, CanvasNodePanelOverlay } from "@/components/canvas/canvas-workspace-overlays";
|
||||
import { CanvasOverlayLayerContainer, CanvasOverlayLayerProvider } from "@/components/canvas/canvas-overlay-layer";
|
||||
import { CanvasLeaferGraphicsLayer } from "@/components/canvas/canvas-leafer-graphics-layer";
|
||||
@@ -1036,7 +1036,9 @@ function InfiniteCanvasPage() {
|
||||
setDrawingNodeId(node.id);
|
||||
} else if (node.type === CanvasNodeType.Script) {
|
||||
setDialogNodeId(null);
|
||||
} else if (node.type === CanvasNodeType.Text || node.type === CanvasNodeType.Frame) {
|
||||
} else if (node.type === CanvasNodeType.Text) {
|
||||
setDialogNodeId(node.id);
|
||||
} else if (node.type === CanvasNodeType.Frame) {
|
||||
setDialogNodeId((current) => (current === node.id ? current : null));
|
||||
} else if (node.type === PORTRAIT_CLEARANCE_NODE_TYPE) {
|
||||
setDialogNodeId(null);
|
||||
@@ -1173,20 +1175,28 @@ function InfiniteCanvasPage() {
|
||||
const referenceNodeId = reference.nodeId;
|
||||
if (!referenceNodeId) return;
|
||||
// 生成节点可能通过配置节点接收参考,只移除参考来源边,保留目标到配置节点的主链。
|
||||
const configNodeId = connectionsRef.current.find((connection) => {
|
||||
const previousNodes = nodesRef.current;
|
||||
const previousConnections = connectionsRef.current;
|
||||
const configNodeId = previousConnections.find((connection) => {
|
||||
if (connection.fromNodeId !== targetNodeId) return false;
|
||||
return nodesRef.current.find((node) => node.id === connection.toNodeId)?.type === CanvasNodeType.Config;
|
||||
return previousNodes.find((node) => node.id === connection.toNodeId)?.type === CanvasNodeType.Config;
|
||||
})?.toNodeId;
|
||||
const removedConnectionIds = new Set(
|
||||
connectionsRef.current
|
||||
previousConnections
|
||||
.filter((connection) => connection.fromNodeId === referenceNodeId && (connection.toNodeId === targetNodeId || connection.toNodeId === configNodeId))
|
||||
.map((connection) => connection.id),
|
||||
);
|
||||
if (!removedConnectionIds.size) return;
|
||||
connectionsRef.current = connectionsRef.current.filter((connection) => !removedConnectionIds.has(connection.id));
|
||||
setConnections(connectionsRef.current);
|
||||
const nextConnections = previousConnections.filter((connection) => !removedConnectionIds.has(connection.id));
|
||||
const nextNodes = applyCanvasConnectionPromptSync(previousNodes, previousConnections, previousNodes, nextConnections);
|
||||
if (nextNodes !== previousNodes) {
|
||||
nodesRef.current = nextNodes;
|
||||
setNodes(nextNodes);
|
||||
}
|
||||
connectionsRef.current = nextConnections;
|
||||
setConnections(nextConnections);
|
||||
setSelectedConnectionId((current) => current && removedConnectionIds.has(current) ? null : current);
|
||||
}, [connectionsRef, nodesRef, setConnections, setSelectedConnectionId]);
|
||||
}, [connectionsRef, nodesRef, setConnections, setNodes, setSelectedConnectionId]);
|
||||
|
||||
const handleProjectFolderInsert = useCallback((folderId: string) => {
|
||||
const folder = linkedProjectQuery.data?.assetFolders.find((item) => item.id === folderId);
|
||||
@@ -2453,15 +2463,15 @@ function InfiniteCanvasPage() {
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{angleNode?.metadata?.content && !isCanvasNodeMoving ? (
|
||||
<CanvasNodePanelOverlay
|
||||
node={angleNode}
|
||||
viewport={viewport}
|
||||
containerRef={containerRef}
|
||||
panelWidth={580}
|
||||
panelHeight={350}
|
||||
dragOffset={dragPreview?.nodeIds.has(angleNode.id) ? { x: dragPreview.x, y: dragPreview.y } : null}
|
||||
isDragging={isNodeDragging && Boolean(dragPreview?.nodeIds.has(angleNode.id))}
|
||||
{angleNode?.metadata?.content ? (
|
||||
<Modal
|
||||
open
|
||||
centered
|
||||
title="多角度编辑器"
|
||||
footer={null}
|
||||
width={620}
|
||||
destroyOnHidden
|
||||
onCancel={() => setAngleNodeId(null)}
|
||||
>
|
||||
<CanvasNodeAnglePanel
|
||||
dataUrl={angleNode.metadata.content}
|
||||
@@ -2470,7 +2480,7 @@ function InfiniteCanvasPage() {
|
||||
void generateAngleNode(angleNode, params);
|
||||
}}
|
||||
/>
|
||||
</CanvasNodePanelOverlay>
|
||||
</Modal>
|
||||
) : null}
|
||||
|
||||
{emotionNode?.metadata?.content && !isCanvasNodeMoving ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { App } from "antd";
|
||||
import { saveAs } from "file-saver";
|
||||
@@ -41,6 +41,10 @@ export function useCanvasNodeEditor({
|
||||
const queryClient = useQueryClient();
|
||||
const [collapsingBatchIds, setCollapsingBatchIds] = useState<Set<string>>(new Set());
|
||||
const [openingBatchIds, setOpeningBatchIds] = useState<Set<string>>(new Set());
|
||||
const batchMotionTimers = useRef(new Map<string, number>());
|
||||
useEffect(() => () => {
|
||||
batchMotionTimers.current.forEach((timer) => window.clearTimeout(timer));
|
||||
}, []);
|
||||
|
||||
const handleNodeResize = useCallback((nodeId: string, width: number, height: number, position?: Position) => {
|
||||
setNodes((current) => {
|
||||
@@ -120,16 +124,26 @@ export function useCanvasNodeEditor({
|
||||
}, [setNodes]);
|
||||
|
||||
const toggleBatchExpanded = useCallback((nodeId: string) => {
|
||||
const isExpanded = Boolean(nodesRef.current.find((node) => node.id === nodeId)?.metadata?.imageBatchExpanded);
|
||||
const root = nodesRef.current.find((node) => node.id === nodeId);
|
||||
if (!root?.metadata?.isBatchRoot) return;
|
||||
const isExpanded = Boolean(root.metadata.imageBatchExpanded);
|
||||
window.clearTimeout(batchMotionTimers.current.get(nodeId));
|
||||
const updateMotionState = isExpanded ? setCollapsingBatchIds : setOpeningBatchIds;
|
||||
const clearMotionState = isExpanded ? setOpeningBatchIds : setCollapsingBatchIds;
|
||||
clearMotionState((current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(nodeId);
|
||||
return next;
|
||||
});
|
||||
updateMotionState((current) => new Set(current).add(nodeId));
|
||||
window.setTimeout(() => {
|
||||
batchMotionTimers.current.set(nodeId, window.setTimeout(() => {
|
||||
batchMotionTimers.current.delete(nodeId);
|
||||
updateMotionState((current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(nodeId);
|
||||
return next;
|
||||
});
|
||||
}, isExpanded ? 320 : 260);
|
||||
}, isExpanded ? 320 : 445 + (root.metadata.batchChildIds?.length || 1) * 24));
|
||||
setNodes((current) => current.map((node) => (node.id === nodeId ? { ...node, metadata: { ...node.metadata, imageBatchExpanded: !node.metadata?.imageBatchExpanded } } : node)));
|
||||
}, [nodesRef, setNodes]);
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { nanoid } from "nanoid";
|
||||
import { NODE_DEFAULT_SIZE } from "@/constant/canvas";
|
||||
import { FOLDER_COLLAPSED_HEIGHT, FOLDER_COLLAPSED_WIDTH, FRAME_HEADER_HEIGHT, getFrameChildIds, getFrameChildren, isFrameNode } from "@/lib/canvas/canvas-frame";
|
||||
import { alignCanvasNodes, layoutCanvasAuto, layoutCanvasFlow, layoutCanvasNodes, nextCanvasVersionLabel, type CanvasAlignmentMode } from "@/lib/canvas/canvas-layout";
|
||||
import { applyCanvasConnectionPromptSync } from "@/lib/canvas/canvas-resource-references";
|
||||
import { createCanvasNode, isHiddenBatchChild, removeCanvasNodes } from "@/lib/canvas/canvas-project-domain";
|
||||
import { isolateCopiedNodeMetadata, nextCopiedNodeTitle } from "@/lib/canvas/canvas-node-copy";
|
||||
import { CanvasNodeType, type CanvasConnection, type CanvasFolderStyle, type CanvasFolderTheme, type CanvasNodeData, type CanvasNodeMetadata, type CanvasNodeTypeId, type ContextMenuState, type Position } from "@/types/canvas";
|
||||
@@ -325,20 +326,28 @@ export function useCanvasNodeOperations({
|
||||
|
||||
const deleteNodes = useCallback((ids: Set<string>) => {
|
||||
if (!ids.size) return;
|
||||
const result = removeCanvasNodes(nodesRef.current, ids);
|
||||
const removedNodes = nodesRef.current.filter((node) => result.removedIds.has(node.id));
|
||||
const nextConnections = connectionsRef.current.filter((connection) => !result.removedIds.has(connection.fromNodeId) && !result.removedIds.has(connection.toNodeId));
|
||||
commitNodes(result.nodes);
|
||||
const previousNodes = nodesRef.current;
|
||||
const previousConnections = connectionsRef.current;
|
||||
const result = removeCanvasNodes(previousNodes, ids);
|
||||
const removedNodes = previousNodes.filter((node) => result.removedIds.has(node.id));
|
||||
const nextConnections = previousConnections.filter((connection) => !result.removedIds.has(connection.fromNodeId) && !result.removedIds.has(connection.toNodeId));
|
||||
const nextNodes = applyCanvasConnectionPromptSync(previousNodes, previousConnections, result.nodes, nextConnections);
|
||||
commitNodes(nextNodes);
|
||||
commitConnections(nextConnections);
|
||||
selectNodes(new Set());
|
||||
onNodesDeleted(result.removedIds, result.nodes, removedNodes);
|
||||
onNodesDeleted(result.removedIds, nextNodes, removedNodes);
|
||||
}, [commitConnections, commitNodes, connectionsRef, nodesRef, onNodesDeleted, selectNodes]);
|
||||
|
||||
const deleteConnection = useCallback((connectionId: string) => {
|
||||
commitConnections(connectionsRef.current.filter((connection) => connection.id !== connectionId));
|
||||
const previousNodes = nodesRef.current;
|
||||
const previousConnections = connectionsRef.current;
|
||||
const nextConnections = previousConnections.filter((item) => item.id !== connectionId);
|
||||
const nextNodes = applyCanvasConnectionPromptSync(previousNodes, previousConnections, previousNodes, nextConnections);
|
||||
if (nextNodes !== previousNodes) commitNodes(nextNodes);
|
||||
commitConnections(nextConnections);
|
||||
setSelectedConnectionId((current) => current === connectionId ? null : current);
|
||||
setContextMenu((current) => current?.type === "connection" && current.connectionId === connectionId ? null : current);
|
||||
}, [commitConnections, connectionsRef, setContextMenu, setSelectedConnectionId]);
|
||||
}, [commitConnections, commitNodes, connectionsRef, nodesRef, setContextMenu, setSelectedConnectionId]);
|
||||
|
||||
const duplicateNode = useCallback((nodeId: string, duplicateMode: "variant" | "copy" = "variant") => {
|
||||
const source = nodesRef.current.find((node) => node.id === nodeId);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ImageSizePicker } from "@/components/image-size-picker";
|
||||
import { imageResolutionUsesQuality } from "@/lib/image-size-presets";
|
||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode, type RefObject } from "react";
|
||||
import { App, Button, Drawer, Dropdown, Modal, Popover, Spin } from "antd";
|
||||
import { Tooltip } from "@/components/ui/base/tooltip";
|
||||
@@ -23,7 +25,7 @@ import { formatShotOrdinal } from "@/lib/shot-label";
|
||||
import { generationErrorCode, generationErrorMessage } from "@/lib/generation-error";
|
||||
import { useCopyText } from "@/hooks/use-copy-text";
|
||||
import { useExternalAssetSources } from "@/hooks/use-external-asset-sources";
|
||||
import { buildImageResolutionOptions, formatImageResolutionSize, imageRatioForSize, imageResolutionChoices, imageResolutionOption, imageSizeForResolution, supportsImageResolutionPresets, type ImageResolutionChoice } from "@/lib/image-resolution-tiers";
|
||||
import { buildImageResolutionOptions, formatImageResolutionSize, supportsImageResolutionPresets } from "@/lib/image-resolution-tiers";
|
||||
import { formatVideoResolutionLabel as videoResolutionLabel, VIDEO_RESOLUTION_OPTIONS } from "@/lib/video-generation-options";
|
||||
import { modelCapabilityConfigFor, normalizeImageValue, normalizeVideoValue, videoDurationAllowed, videoDurationOptions, type ImageCapabilityConfig, type VideoCapabilityConfig } from "@/lib/model-capabilities";
|
||||
import { inferVideoOperation, resolveCompatibleModel, mergedImageCapabilityConfig, type ModelRequirements } from "@/lib/model-selection";
|
||||
@@ -1256,14 +1258,15 @@ function MediaResult({ item, onRetryFailure, onCreateVariant }: { item: Creation
|
||||
const assets = useAssetStore((state) => state.assets);
|
||||
const resultUrls = item.resultUrls || [];
|
||||
const resultAssetIds = resultUrls.length ? creationResultAssetIds(assets, { messageId: item.id, taskIds: item.taskIds || [], resultUrls }) : [];
|
||||
const canvasPath = creationCanvasHandoffPath(resultAssetIds) || "/canvas";
|
||||
const canvasHandoffPath = creationCanvasHandoffPath(resultAssetIds, resultUrls.length);
|
||||
const canvasPath = canvasHandoffPath || "/canvas";
|
||||
if (item.status === "pending") return <CreationMediaPending mode={item.mode || "image"} ratio={item.settings?.ratio} />;
|
||||
if ((item.status === "error" || item.status === "cancelled") && !resultUrls.length) return <div className="creation-media-error"><span>{item.status === "cancelled" ? item.content || "已停止" : generationErrorMessage(item.error || "生成失败")}</span><button type="button" onClick={onRetryFailure}><RefreshCw />重新生成</button></div>;
|
||||
if (!resultUrls.length) return <div className="creation-media-empty">没有返回可预览结果 <button type="button" onClick={onRetryFailure}>重试</button></div>;
|
||||
const isVideo = item.mode === "video";
|
||||
return <div className="creation-media-result">
|
||||
{isVideo ? <button type="button" className="creation-video-result" onClick={() => { setPreviewType("video"); setPreviewUrl(resultUrls[0]); }} aria-label="预览生成视频"><video muted preload="metadata" src={resultUrls[0]} /><span><Maximize2 />预览视频</span></button> : <div className="creation-image-result-grid">{resultUrls.map((url) => <button key={url} type="button" className="creation-image-result" onClick={() => { setPreviewType("image"); setPreviewUrl(url); }} aria-label="预览生成图片"><img src={url} alt="生成结果" /><span><Maximize2 /></span></button>)}</div>}
|
||||
<div className="creation-media-actions"><span>{isVideo ? "视频结果" : `${resultUrls.length} 张图片`}</span><Link to={canvasPath}>{resultAssetIds.length ? "添加到画布" : "打开画布"}</Link>{resultUrls.map((url, index) => <a key={`${url}-download`} href={url} download>{resultUrls.length > 1 ? `下载 ${index + 1}` : <><Download />下载</>}</a>)}</div>
|
||||
<div className="creation-media-actions"><span>{isVideo ? "视频结果" : `${resultUrls.length} 张图片`}</span><Link to={canvasPath}>{canvasHandoffPath ? "添加到画布" : "打开画布"}</Link>{resultUrls.map((url, index) => <a key={`${url}-download`} href={url} download>{resultUrls.length > 1 ? `下载 ${index + 1}` : <><Download />下载</>}</a>)}</div>
|
||||
<CreationMediaPreviewModal url={previewUrl} type={previewType} onClose={() => setPreviewUrl("")} />
|
||||
</div>;
|
||||
}
|
||||
@@ -1723,46 +1726,21 @@ function ModePicker({ mode, onModeChange }: { mode: CreationMode; onModeChange:
|
||||
|
||||
function GenerationSettingsMenu(props: ComposerProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [customRatioOpen, setCustomRatioOpen] = useState(!ratioOptions.some((option) => option.value === props.ratio));
|
||||
const activeQualityOptions = props.imageProfile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value.toUpperCase(), description: "模型支持的质量/分辨率" });
|
||||
const qualityLabel = activeQualityOptions.find((item) => item.value === props.quality)?.label || qualityOptions.find((item) => item.value === props.quality)?.label || props.quality || "自动";
|
||||
// 尺寸/比例/分辨率选项取同显示名分组内全部模型的并集,路由模型只决定发送参数。
|
||||
const mergedProfile = mergedImageCapabilityConfig(props.config, props.model || props.config.imageModel);
|
||||
const usesImageResolutionPicker = props.mode === "image" && supportsImageResolutionPresets(mergedProfile.size);
|
||||
const imageResolutionOptions = usesImageResolutionPicker ? buildImageResolutionOptions(mergedProfile.size.values) : [];
|
||||
const activeImageResolution = usesImageResolutionPicker ? imageResolutionOption(imageResolutionOptions, props.ratio) : undefined;
|
||||
const activeImageRatio = activeImageResolution?.ratio || imageRatioForSize(props.ratio) || (props.ratio.includes(":") ? props.ratio : "1:1");
|
||||
const activeImageResolutionChoice: ImageResolutionChoice = activeImageResolution?.tier || "auto";
|
||||
const imageResolutionChoiceOptions = usesImageResolutionPicker ? imageResolutionChoices(mergedProfile.size.values) : [];
|
||||
const imageRatios = usesImageResolutionPicker
|
||||
? Array.from(new Set(imageResolutionOptions.filter((item) => !activeImageResolution || item.tier === activeImageResolution.tier).map((item) => item.ratio)))
|
||||
: mergedProfile.size.values.length ? mergedProfile.size.values : ratioOptions.map((item) => item.value);
|
||||
const ratios = props.mode === "video" ? props.videoProfile.ratios : imageRatios;
|
||||
const ratios = props.videoProfile.ratios;
|
||||
const referenceImageSize = props.mode === "image" && mergedProfile.size.allowCustom ? props.referenceImageSize : undefined;
|
||||
const referenceImageSizeValue = referenceImageSize ? String(referenceImageSize.width) + "x" + String(referenceImageSize.height) : "";
|
||||
const referenceImageSizeLabel = referenceImageSize ? String(referenceImageSize.width) + " × " + String(referenceImageSize.height) : "";
|
||||
const referenceImageSizeRatio = referenceImageSize ? String(referenceImageSize.width) + ":" + String(referenceImageSize.height) : "";
|
||||
const referenceImageSizeSelected = Boolean(referenceImageSizeValue && props.ratio === referenceImageSizeValue);
|
||||
const resolutions = props.mode === "video" ? props.videoProfile.resolutions.map((value) => ({ value: value.replace(/p$/i, ""), label: videoResolutionLabel(value) })) : resolutionOptions;
|
||||
const selectImageRatio = (nextRatio: string) => {
|
||||
if (!usesImageResolutionPicker || activeImageResolutionChoice === "auto") {
|
||||
props.setRatio(nextRatio);
|
||||
return;
|
||||
}
|
||||
props.setRatio(imageSizeForResolution(imageResolutionOptions, activeImageResolutionChoice, nextRatio) || nextRatio);
|
||||
};
|
||||
const selectImageResolution = (choice: ImageResolutionChoice) => {
|
||||
if (choice === "auto") {
|
||||
props.setRatio(mergedProfile.size.values.includes("auto") ? "auto" : activeImageRatio);
|
||||
return;
|
||||
}
|
||||
const nextSize = imageSizeForResolution(imageResolutionOptions, choice, activeImageRatio) || imageResolutionOptions.find((item) => item.tier === choice)?.size;
|
||||
if (nextSize) props.setRatio(nextSize);
|
||||
};
|
||||
const selectReferenceImageSize = () => {
|
||||
if (!referenceImageSizeValue) return;
|
||||
props.setRatio(referenceImageSizeValue);
|
||||
setCustomRatioOpen(false);
|
||||
};
|
||||
const videoResolutionSupported = props.mode === "video" && resolutions.length > 0;
|
||||
const imageSummary = [
|
||||
@@ -1773,10 +1751,11 @@ function GenerationSettingsMenu(props: ComposerProps) {
|
||||
const videoRatioSupported = props.mode === "video" && ratios.length > 0;
|
||||
const summary = props.mode === "video" ? [...(videoRatioSupported ? [props.ratio] : []), ...(videoResolutionSupported ? [videoResolutionLabel(props.videoQuality)] : [])].join(" · ") : imageSummary;
|
||||
const panel = <div className="creation-parameter-menu">
|
||||
{videoRatioSupported || props.mode !== "video" && mergedProfile.size.parameter !== "none" ? <SettingSection title="画幅" value={referenceImageSizeSelected ? referenceImageSizeLabel : props.mode === "image" && usesImageResolutionPicker ? activeImageRatio : props.ratio}><div className="creation-parameter-content"><div className="creation-choice-grid is-ratio">{referenceImageSizeValue ? <button type="button" aria-pressed={referenceImageSizeSelected} aria-label={"使用参考图尺寸 " + referenceImageSizeLabel} title={"使用参考图尺寸 " + referenceImageSizeLabel} className={"creation-reference-size-choice" + (referenceImageSizeSelected ? " is-selected" : "")} onClick={selectReferenceImageSize}><span className="creation-ratio-preview"><span style={ratioPreviewStyle(referenceImageSizeRatio)} /></span><span>参考图</span></button> : null}{ratios.map((value) => { const selected = props.mode === "image" && usesImageResolutionPicker ? value === activeImageRatio : value === props.ratio; return <button key={value} type="button" aria-pressed={selected} className={selected ? "is-selected" : ""} onClick={() => { if (props.mode === "image") selectImageRatio(value); else props.setRatio(value); setCustomRatioOpen(false); }}><span className="creation-ratio-preview"><span style={ratioPreviewStyle(value)} /></span><span>{value}</span></button>; })}</div>{props.mode !== "video" && mergedProfile.size.allowCustom && (customRatioOpen ? <label className="creation-custom-value"><span>宽 x 高</span><input value={props.ratio} onFocus={(event) => event.currentTarget.select()} onChange={(event) => props.setRatio(event.target.value)} placeholder="1920x1080 或 2:1" aria-label="自定义图片尺寸或比例" /></label> : <button type="button" className="creation-custom-trigger" onClick={() => setCustomRatioOpen(true)}><Plus />输入自定义尺寸</button>)}</div></SettingSection> : null}
|
||||
{props.mode === "image" ? <ImageSizePicker profile={mergedProfile} size={props.ratio} quality={props.quality} onChange={(size, quality) => { props.setRatio(size); if (quality) props.setQuality(quality); }} /> : videoRatioSupported ? <SettingSection title="画幅" value={props.ratio}><div className="creation-choice-grid is-ratio">{ratios.map((value) => <button key={value} type="button" aria-pressed={value === props.ratio} className={value === props.ratio ? "is-selected" : ""} onClick={() => props.setRatio(value)}><span className="creation-ratio-preview"><span style={ratioPreviewStyle(value)} /></span><span>{value}</span></button>)}</div></SettingSection> : null}
|
||||
{props.mode === "image" && referenceImageSizeValue ? <button type="button" className="creation-custom-trigger" onClick={selectReferenceImageSize}>使用参考图尺寸 · {referenceImageSizeLabel}</button> : null}
|
||||
{props.mode === "video" ? (videoResolutionSupported ? <SettingSection title="清晰度" value={videoResolutionLabel(props.videoQuality)}><div className="creation-choice-grid is-resolution">{resolutions.map((option) => <button key={option.value} type="button" aria-pressed={option.value === props.videoQuality} className={option.value === props.videoQuality ? "is-selected" : ""} onClick={() => props.setVideoQuality(option.value)}>{option.label}</button>)}</div></SettingSection> : null) : <>
|
||||
{imageResolutionChoiceOptions.length ? <SettingSection title="分辨率" value={activeImageResolutionChoice === "auto" ? "自动" : activeImageResolutionChoice.toUpperCase()}><div className="creation-choice-grid is-resolution">{imageResolutionChoiceOptions.map((choice) => <button key={choice} type="button" aria-pressed={choice === activeImageResolutionChoice} className={choice === activeImageResolutionChoice ? "is-selected" : ""} onClick={() => selectImageResolution(choice)}>{choice === "auto" ? "自动" : choice.toUpperCase()}</button>)}</div></SettingSection> : null}
|
||||
{props.imageProfile.quality.supported ? <SettingSection title={activeQualityOptions.some((item) => item.value === "1k" || item.value === "2k") ? "分辨率" : "图片质量"} value={qualityLabel}><div className="creation-choice-grid is-quality">{activeQualityOptions.map((option) => <button key={option.value} type="button" aria-pressed={option.value === props.quality} className={option.value === props.quality ? "is-selected" : ""} onClick={() => props.setQuality(option.value)}><span>{option.label}</span><small>{option.description}</small></button>)}</div></SettingSection> : null}
|
||||
|
||||
{props.imageProfile.quality.supported && !imageResolutionUsesQuality(mergedProfile) ? <SettingSection title={activeQualityOptions.some((item) => item.value === "1k" || item.value === "2k") ? "分辨率" : "图片质量"} value={qualityLabel}><div className="creation-choice-grid is-quality">{activeQualityOptions.map((option) => <button key={option.value} type="button" aria-pressed={option.value === props.quality} className={option.value === props.quality ? "is-selected" : ""} onClick={() => props.setQuality(option.value)}><span>{option.label}</span><small>{option.description}</small></button>)}</div></SettingSection> : null}
|
||||
{props.imageProfile.maxOutputs > 1 ? <SettingSection title="生成数量" value={`${props.count} 张`}><div className="creation-parameter-content"><div className="creation-choice-grid is-count">{countOptions.filter((option) => Number(option) <= props.imageProfile.maxOutputs).map((option) => <button key={option} type="button" aria-pressed={option === props.count} className={option === props.count ? "is-selected" : ""} onClick={() => props.setCount(option)}>{option}</button>)}</div><label className="creation-custom-value"><span>自定义</span><input inputMode="numeric" pattern="[0-9]*" value={props.count} onChange={(event) => props.setCount(String(Math.max(1, Math.min(props.imageProfile.maxOutputs, Number(event.target.value) || 1))))} aria-label={`生成数量,范围 1 到 ${props.imageProfile.maxOutputs}`} /><em>张</em></label></div></SettingSection> : null}
|
||||
</>}
|
||||
</div>;
|
||||
|
||||
@@ -160,8 +160,8 @@ export default function PluginsPage() {
|
||||
() => [
|
||||
...protocolSectionMeta.map((section) => ({ ...section, plugins: filteredPlugins.filter((plugin) => pluginMatchesCategory(plugin.manifest, section.key)) })),
|
||||
{ key: "other", label: "应用插件", description: "画布、素材与工作流扩展", icon: PlugZap, plugins: filteredPlugins.filter((plugin) => pluginMatchesCategory(plugin.manifest, "other")) },
|
||||
],
|
||||
[filteredPlugins],
|
||||
].filter((section) => categoryFilter === "all" || section.key === categoryFilter),
|
||||
[categoryFilter, filteredPlugins],
|
||||
);
|
||||
|
||||
const selectCategory = (key: string) => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ImageSizePicker } from "@/components/image-size-picker";
|
||||
import { imageResolutionUsesQuality } from "@/lib/image-size-presets";
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { App, Button, Form, Image, Input, InputNumber, Modal, Select } from "antd";
|
||||
@@ -508,20 +510,14 @@ export default function WorkflowProductionWorkbench(props: Props) {
|
||||
? <Select options={videoDurationOptions(videoProfile).map((value) => ({ value, label: `${value} 秒` }))} />
|
||||
: <InputNumber className="w-full" min={generationCapability === "video" ? videoProfile?.duration.min || 1 : 0.5} max={generationCapability === "video" ? videoProfile?.duration.max || 60 : 60} step={generationCapability === "video" ? videoProfile?.duration.step || 1 : 0.5} />}
|
||||
</Form.Item>
|
||||
<Form.Item label={generationCapability === "video" ? "画幅" : "尺寸 / 画幅"}>
|
||||
<Select
|
||||
showSearch
|
||||
value={aspectRatio}
|
||||
onChange={setAspectRatio}
|
||||
options={(generationCapability === "video" ? videoProfile?.ratios || [] : imageProfile?.size.values.filter((value) => value !== "*") || []).map((value) => ({ value, label: value }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
{generationCapability === "video" ? <Form.Item label="画幅"><Select value={aspectRatio} onChange={setAspectRatio} options={(videoProfile?.ratios || []).map((value) => ({value, label:value}))} /></Form.Item> : null}
|
||||
{generationCapability === "video" ? (
|
||||
<Form.Item label="分辨率"><Select value={resolution} onChange={setResolution} options={(videoProfile?.resolutions || []).map((value) => ({ value, label: formatVideoResolutionLabel(value) }))} /></Form.Item>
|
||||
) : imageProfile?.quality.supported ? (
|
||||
) : imageProfile?.quality.supported && !imageResolutionUsesQuality(imageProfile) ? (
|
||||
<Form.Item label="生成画质"><Select value={imageQuality} onChange={setImageQuality} options={imageProfile.quality.values.map((value) => ({ value, label: value.toUpperCase() }))} /></Form.Item>
|
||||
) : <div />}
|
||||
</div>
|
||||
{generationCapability === "image" && imageProfile ? <ImageSizePicker profile={imageProfile} size={aspectRatio} quality={imageQuality} onChange={(size, quality) => { setAspectRatio(size); if (quality) setImageQuality(quality); }} /> : null}
|
||||
</div>
|
||||
<div className="workflow-settings-section">
|
||||
<div className="workflow-settings-section-title">镜头语言</div>
|
||||
|
||||
Reference in new issue
Block a user