feat(*): 创作与运维 - 新增图片尺寸预设和系统性能面板并优化图片组动画

This commit is contained in:
ddCat
2026-09-07 14:03:50 +08:00
parent df94c3bdf1
commit bd639745ac
41 changed files with 2785 additions and 353 deletions

View File

@@ -43,6 +43,7 @@ export type CanvasNodeContentProps = {
textareaRef: RefObject<HTMLTextAreaElement | null>;
isBatchRoot: boolean;
batchCount: number;
batchPreviewNodes?: CanvasNodeData[];
batchExpanded: boolean;
batchOpening: boolean;
batchRecovering: boolean;
@@ -398,13 +399,13 @@ function ImageNodeContent(props: CanvasNodeContentProps) {
: props.node.metadata?.status === "error"
? <ErrorContent node={props.node} theme={props.theme} onRetry={props.onRetry} onReloadResource={props.onReloadResource} />
: <EmptyImageContent {...props} isBatchRoot={false} />;
return <BatchFrame batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} theme={props.theme} onToggleBatch={props.onToggleBatch}>{content}</BatchFrame>;
return <BatchFrame batchPreviewNodes={props.batchPreviewNodes} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} theme={props.theme} onToggleBatch={props.onToggleBatch}>{content}</BatchFrame>;
}
if (!props.node.metadata?.content) return <EmptyImageContent {...props} />;
return <ImageContent node={props.node} theme={props.theme} isBatchRoot={props.isBatchRoot} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} onToggleBatch={props.onToggleBatch} />;
return <ImageContent batchPreviewNodes={props.batchPreviewNodes} node={props.node} theme={props.theme} isBatchRoot={props.isBatchRoot} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} onToggleBatch={props.onToggleBatch} />;
}
function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: CanvasNodeContentProps) {
function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: CanvasNodeContentProps) {
const isCharacterReference = node.metadata?.workflowKind === "character" && node.metadata?.characterView === "multi";
const content = (
<div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color: theme.node.placeholder }}>
@@ -417,7 +418,7 @@ function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded
) : <span className="text-[var(--fs-tiny)] tracking-[0.18em] opacity-50">空图片节点</span>}
</div>
);
if (isBatchRoot) return <BatchFrame batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>{content}</BatchFrame>;
if (isBatchRoot) return <BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>{content}</BatchFrame>;
return content;
}
@@ -571,7 +572,7 @@ function EmptyMediaContent({ icon, label, color }: { icon: ReactNode; label: str
return <div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color }}>{icon}<span className="text-sm">{label}</span></div>;
}
function ImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
function ImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchPreviewNodes" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
const imageContainerRef = useRef<HTMLDivElement>(null);
const nearViewport = useNearViewport(imageContainerRef);
const { url, loading } = useNodeResourceUrl(node, nearViewport);
@@ -615,7 +616,7 @@ function ImageContent({ node, theme, isBatchRoot, batchCount, batchExpanded, bat
};
return (
<BatchFrame batchCount={isBatchRoot ? batchCount : 0} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
<BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={isBatchRoot ? batchCount : 0} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
<div ref={imageContainerRef} className="h-full w-full overflow-hidden rounded-[var(--node-radius)]">
{url ? <img src={url} alt={node.title} loading="lazy" decoding="async" draggable={false} onDragStart={(event) => event.preventDefault()} onLoad={(event) => fitToImage(event.currentTarget)} className={`pointer-events-none block h-full w-full select-none ${node.metadata?.freeResize ? "object-fill" : "object-contain"}`} /> : <div className="grid size-full place-items-center" style={{ color: theme.node.muted }}>{loading ? <LoaderCircle className="size-5 animate-spin" /> : <ImageIcon className="size-5 opacity-45" />}</div>}
</div>
@@ -695,7 +696,14 @@ export function CanvasNodeImageInfo({ node }: { node: CanvasNodeData }) {
return <span className="ml-auto max-w-full shrink-0 truncate rounded-[var(--r-sm)] bg-black/55 px-2 py-1 text-[var(--fs-label)] font-medium leading-none text-white backdrop-blur-sm">{width} x {height}{size ? ` · ${size}` : ""}</span>;
}
function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering, theme, onToggleBatch, children }: { batchCount: number; batchExpanded: boolean; batchOpening: boolean; batchRecovering: boolean; theme: CanvasTheme; onToggleBatch?: () => void; children: ReactNode }) {
function BatchPreviewImage({ node }: { node: CanvasNodeData }) {
const ref = useRef<HTMLDivElement>(null);
const nearViewport = useNearViewport(ref);
const { url } = useNodeResourceUrl(node, nearViewport);
return <div ref={ref} className="h-full w-full overflow-hidden rounded-[inherit]">{url ? <img src={url} alt={`子图预览:${node.title}`} className="h-full w-full object-contain" draggable={false} /> : null}</div>;
}
function BatchFrame({ batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, theme, onToggleBatch, children }: { batchCount: number; batchPreviewNodes?: CanvasNodeData[]; batchExpanded: boolean; batchOpening: boolean; batchRecovering: boolean; theme: CanvasTheme; onToggleBatch?: () => void; children: ReactNode }) {
const isBatchRoot = batchCount > 1;
return (
<div className="group/batch relative h-full w-full overflow-visible" onDoubleClick={isBatchRoot ? (event) => { event.stopPropagation(); onToggleBatch?.(); } : undefined}>
@@ -704,7 +712,7 @@ function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering,
{Array.from({ length: Math.min(batchCount - 1, 5) }).map((_, index) => (
<div
key={index}
className="absolute rounded-[inherit] transition-all duration-300 group-hover/batch:translate-x-2"
className="absolute rounded-[var(--r-lg)] transition-all duration-300 group-hover/batch:translate-x-2"
style={{
inset: 0,
background: theme.node.panel,
@@ -713,7 +721,9 @@ function BatchFrame({ batchCount, batchExpanded, batchOpening, batchRecovering,
transform: batchOpening || batchRecovering ? `translate(${54 + index * 22}px, ${20 + index * 12}px) rotate(${8 + index * 5}deg) scale(.98)` : `translate(${34 + index * 18}px, ${14 + index * 10}px) rotate(${6 + index * 4}deg)`,
zIndex: -index - 1,
}}
/>
>
{batchPreviewNodes?.[index] ? <BatchPreviewImage node={batchPreviewNodes[index]} /> : null}
</div>
))}
</div>
) : null}

View File

@@ -37,6 +37,7 @@ type CanvasNodeProps = {
renderNodeContent?: (node: CanvasNodeData) => ReactNode;
drawingProjectId?: string;
batchCount?: number;
batchPreviewNodes?: CanvasNodeData[];
batchExpanded?: boolean;
batchClosing?: boolean;
batchOpening?: boolean;
@@ -83,6 +84,7 @@ export const CanvasNode = React.memo(function CanvasNode({
renderNodeContent,
drawingProjectId,
batchCount = 0,
batchPreviewNodes,
batchExpanded = false,
batchClosing = false,
batchOpening = false,
@@ -347,8 +349,8 @@ export const CanvasNode = React.memo(function CanvasNode({
"--batch-from-x": `${batchMotion?.x || 0}px`,
"--batch-from-y": `${batchMotion?.y || 0}px`,
"--batch-from-rotate": `${6 + (batchMotion?.index || 0) * 4}deg`,
animation: data.metadata?.batchRootId ? (batchClosing ? `canvas-batch-child-out var(--motion-dur-base-calc) var(--motion-ease-in-out) both` : `canvas-batch-child-in var(--motion-dur-slow-calc) var(--motion-ease-out) both`) : undefined,
animationDelay: data.metadata?.batchRootId ? `${batchClosing ? 0 : 45 + (batchMotion?.index || 0) * 24}ms` : undefined,
animation: isBatchChild && (batchClosing || batchOpening) ? (batchClosing ? `canvas-batch-child-out var(--motion-dur-base-calc) var(--motion-ease-in-out) both` : `canvas-batch-child-in var(--motion-dur-slow-calc) var(--motion-ease-out) both`) : undefined,
animationDelay: isBatchChild && (batchClosing || batchOpening) ? `${batchClosing ? 0 : 45 + (batchMotion?.index || 0) * 24}ms` : undefined,
} as React.CSSProperties
}
>
@@ -363,6 +365,7 @@ export const CanvasNode = React.memo(function CanvasNode({
textareaRef={textareaRef}
isBatchRoot={isBatchRoot}
batchCount={batchCount}
batchPreviewNodes={batchPreviewNodes}
batchExpanded={batchExpanded}
batchOpening={batchOpening}
batchRecovering={batchRecovering}
@@ -494,6 +497,7 @@ function areCanvasNodePropsEqual(previous: CanvasNodeProps, next: CanvasNodeProp
previous.renderNodeContent === next.renderNodeContent &&
previous.drawingProjectId === next.drawingProjectId &&
previous.batchCount === next.batchCount &&
previous.batchPreviewNodes === next.batchPreviewNodes &&
previous.batchExpanded === next.batchExpanded &&
previous.batchClosing === next.batchClosing &&
previous.batchOpening === next.batchOpening &&
@@ -548,7 +552,7 @@ function NodeLockBadge({ theme }: { theme: CanvasTheme }) {
function BatchToggleBadge({ count, expanded, theme, onToggle }: { count: number; expanded: boolean; theme: CanvasTheme; onToggle: () => void }) {
return (
<button type="button" className="canvas-node-tool-button inline-flex h-7 shrink-0 items-center gap-1 rounded-md border px-2 text-[var(--fs-tiny)] font-semibold backdrop-blur-md" style={{ background: `${theme.toolbar.panel}d9`, borderColor: `${theme.toolbar.border}cc`, color: theme.node.text }} aria-label={expanded ? "图片组已展开" : "图片组已收起"} onClick={(event) => { event.stopPropagation(); onToggle(); }} onMouseDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}>
<button type="button" className="canvas-node-tool-button inline-flex h-7 shrink-0 items-center gap-1 rounded-md border px-2 text-[var(--fs-tiny)] font-semibold backdrop-blur-md" style={{ background: `${theme.toolbar.panel}d9`, borderColor: `${theme.toolbar.border}cc`, color: theme.node.text }} aria-expanded={expanded} aria-label={expanded ? "收起图片组" : "展开图片组"} onClick={(event) => { event.stopPropagation(); onToggle(); }} onMouseDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}>
<span className="leading-none" style={{ color: theme.accent.primary }}>{count}</span>
<ChevronRight className={`size-3 opacity-55 transition-transform ${expanded ? "rotate-90" : ""}`} />
</button>

View File

@@ -158,7 +158,7 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
const reducedMotion = useReducedMotion();
const menuRef = useRef<HTMLDivElement>(null);
const { bringToFront, zIndex } = useCanvasOverlayLayer("connection-create-menu", "var(--z-modal-overlay)");
const menuWidth = 248;
const menuWidth = Math.min(288, viewportSize.width - 24);
const menuHeight = canCreateDrawing ? 456 : 412;
const gap = 12;
const initialPosition = getConnectionMenuPosition(pending.position, viewport, viewportSize, menuWidth, menuHeight, gap);
@@ -188,10 +188,10 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
initial={reducedMotion ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.97, rotateX: 2 }}
animate={{ opacity: 1, y: 0, scale: 1, rotateX: 0 }}
transition={{ duration: aceternityMotion.duration.instant, ease: aceternityMotion.easing.enter }}
className="aceternity-floating-panel absolute w-[248px] origin-top-left overflow-hidden rounded-[var(--r-2xl)] border p-2 backdrop-blur-2xl"
className="aceternity-floating-panel absolute origin-top-left overflow-x-hidden overflow-y-auto rounded-[var(--r-2xl)] border p-2 backdrop-blur-2xl"
data-canvas-no-zoom
data-connection-create-menu
style={{ left: initialPosition.left, top: initialPosition.top, zIndex, background: theme.spatial.elevated, borderColor: theme.toolbar.border, color: theme.node.text }}
style={{ width: menuWidth, maxHeight: Math.max(120, viewportSize.height - 84), left: initialPosition.left, top: initialPosition.top, zIndex, background: theme.spatial.elevated, borderColor: theme.toolbar.border, color: theme.node.text }}
onMouseDown={(event) => event.stopPropagation()}
onPointerDownCapture={bringToFront}
onFocusCapture={bringToFront}
@@ -205,7 +205,7 @@ export function CanvasConnectionCreateMenu({ pending, viewport, viewportSize, co
</span>
<button type="button" className="grid size-6 shrink-0 place-items-center rounded-full border opacity-55 transition-opacity hover:opacity-100" style={{ background: theme.spatial.surface, borderColor: theme.toolbar.border }} onClick={onClose} aria-label="关闭连线创建菜单"><X className="size-3" /></button>
</div>
<div className="grid gap-1">
<div className="grid min-w-0 grid-cols-1 gap-1">
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<List className="size-4" />} title="文本生成" disabledReason={getDisabledReason(CanvasNodeType.Text)} onClick={() => onCreate(CanvasNodeType.Text)} />
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<Clapperboard className="size-4" />} title="分镜脚本" disabledReason={getDisabledReason(CanvasNodeType.Script)} onClick={() => onCreate(CanvasNodeType.Script)} />
<ConnectionCreateOption motionEnabled={!reducedMotion} icon={<ImageIcon className="size-4" />} title="图片生成" disabledReason={getDisabledReason(CanvasNodeType.Image)} onClick={() => onCreate(CanvasNodeType.Image)} />
@@ -225,7 +225,7 @@ function ConnectionCreateOption({ motionEnabled, icon, title, description, disab
<span className="grid size-7 shrink-0 place-items-center rounded-[var(--r-md)] opacity-65 transition-opacity group-hover:opacity-100 [&_svg]:size-3.5" style={{ background: theme.toolbar.itemHover }}>{icon}</span>
<span className="min-w-0 flex-1">
<span className="flex items-center gap-2 text-[var(--fs-tiny)] font-semibold leading-4">{title}</span>
{disabledReason || description ? <span className="mt-0.5 block truncate text-[var(--fs-micro)]" style={{ color: theme.node.muted }}>{disabledReason || description}</span> : null}
{disabledReason || description ? <span className="mt-0.5 block whitespace-normal break-words text-[var(--fs-micro)] leading-relaxed" style={{ color: theme.node.muted }}>{disabledReason || description}</span> : null}
</span>
<ChevronRight className="size-3.5 shrink-0 opacity-35 transition-transform group-hover:translate-x-0.5" />
</motion.button>

View File

@@ -1,8 +1,10 @@
import { type ReactNode, useState } from "react";
import { ImageSizePicker } from "./image-size-picker";
import { imageResolutionUsesQuality } from "@/lib/image-size-presets";
import { type ReactNode } from "react";
import { ConfigProvider, Switch } from "antd";
import { type CanvasTheme } from "@/lib/canvas-theme";
import { buildImageResolutionOptions, formatImageResolutionSize, imageRatioForSize, imageResolutionChoices, imageResolutionOption, imageSizeForResolution, supportsImageResolutionPresets, type ImageResolutionChoice } from "@/lib/image-resolution-tiers";
import { buildImageResolutionOptions, formatImageResolutionSize } from "@/lib/image-resolution-tiers";
import { modelCapabilityConfigFor, normalizeImageValue, type ImageCapabilityConfig } from "@/lib/model-capabilities";
import { mergedImageCapabilityConfig } from "@/lib/model-selection";
import { modelOptionName, resolveModelChannel, type AiConfig } from "@/stores/use-config-store";
@@ -14,8 +16,8 @@ const qualityOptions = [
{ value: "low", label: "低" },
{ value: "1k", label: "1K" },
{ value: "2k", label: "2K" },
{ value: "4k", label: "4K" },
];
const DIMENSION_STEP = 16;
type AspectOption = { value: string; label: string; width: number; height: number; icon: string; size?: string };
@@ -50,7 +52,6 @@ type ImageSettingsPanelProps = {
};
export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle = true, showCount = true, className = "w-[304px] space-y-3 rounded-2xl px-1 py-0.5", maxCount = 15, quickCount = 3 }: ImageSettingsPanelProps) {
const [snapDimensionToStep, setSnapDimensionToStep] = useState(true);
const profile = mergedImageCapabilityConfig(config, config.model || config.imageModel);
const normalized = normalizeImageValue(profile, config);
const quality = normalized.quality;
@@ -58,43 +59,8 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
const effectiveMaxCount = Math.min(maxCount, profile.maxOutputs);
const count = Math.max(1, Math.min(effectiveMaxCount, Number(normalized.count)));
const activeSize = normalized.size;
const pixelSizeValues = profile.size.values.filter((value) => value.trim().toLowerCase() !== "auto");
const hasResolutionPresets = supportsImageResolutionPresets(profile.size);
const resolutionOptions = hasResolutionPresets ? buildImageResolutionOptions(pixelSizeValues) : [];
const activeResolution = activeSize === "auto" ? undefined : imageResolutionOption(resolutionOptions, activeSize);
const activeRatio = activeResolution?.ratio || imageRatioForSize(activeSize);
const resolutionChoices = hasResolutionPresets ? imageResolutionChoices(profile.size.values) : [];
// 只有一个分辨率层级时,分辨率切换器没有实际选择意义;更重要的是不能因此把比例列表裁剪成当前层级的 3 个像素尺寸。
// 例如历史 `*` 配置恢复为标准值后,虽然包含 1024x1024/1536x1024/1024x1536,实际仍应展示完整的比例和尺寸选项。
const usesResolutionPicker = resolutionChoices.length > 1;
const availableAspects: AspectOption[] = usesResolutionPicker && activeSize === "auto"
? []
: usesResolutionPicker && activeResolution
? resolutionOptions.filter((item) => item.tier === activeResolution.tier).map((item) => ({ value: item.ratio, label: item.ratio, size: item.size, width: item.width, height: item.height, icon: item.width === item.height ? "square" : item.width > item.height ? "landscape" : "portrait" }))
: imageAspectOptions(profile);
const selectedAspect = availableAspects.find((item) => imageOptionValue(profile, item) === activeSize || item.value === activeSize) || availableAspects.find((item) => item.label === activeRatio);
const dimensions = readSizeDimensions(activeSize, selectedAspect || aspectOptions[0]);
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
const priceTiers = imageModelPriceTiers(config);
const selectAspect = (value: string) => {
const option = availableAspects.find((item) => item.value === value);
onConfigChange("size", option ? imageOptionValue(profile, option) : "auto");
};
const selectResolution = (choice: ImageResolutionChoice) => {
if (choice === "auto") {
onConfigChange("size", "auto");
return;
}
const ratio = activeRatio || availableAspects[0]?.label;
const size = imageSizeForResolution(resolutionOptions, choice, ratio) || resolutionOptions.find((item) => item.tier === choice)?.size;
if (size) onConfigChange("size", size);
};
const updateDimension = (key: "width" | "height", value: number | null) => {
const next = Math.max(1, Math.floor(value || dimensions[key] || 1024));
const width = key === "width" ? next : dimensions.width;
const height = key === "height" ? next : dimensions.height;
onConfigChange("size", `${alignDimension(width, snapDimensionToStep)}x${alignDimension(height, snapDimensionToStep)}`);
};
const activeQualityOptions = profile.quality.values.map((value) => qualityOptions.find((item) => item.value === value) || { value, label: value });
const priceTiers = imageModelPriceTiers(config);
return (
<ImageSettingsTheme theme={theme}>
@@ -108,7 +74,7 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
}}
>
{showTitle ? <div className="text-base font-semibold">图像设置</div> : null}
{profile.quality.supported ? <div className="space-y-2">
{profile.quality.supported && !imageResolutionUsesQuality(profile) ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>{isGrokResolutionQuality(profile) ? "分辨率" : "质量"}</SettingTitle>
<div className={`grid gap-1.5 ${activeQualityOptions.length <= 2 ? "grid-cols-2" : "grid-cols-4"}`}>
{activeQualityOptions.map((item) => (
@@ -133,52 +99,7 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
/>
</span>
</div> : null}
{resolutionChoices.length ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>分辨率</SettingTitle>
<div className={`grid gap-1.5 ${resolutionChoices.length <= 2 ? "grid-cols-2" : resolutionChoices.length === 4 ? "grid-cols-4" : "grid-cols-3"}`}>
{resolutionChoices.map((choice) => (
<OptionPill key={choice} selected={choice === "auto" ? activeSize === "auto" : activeResolution?.tier === choice} theme={theme} onClick={() => selectResolution(choice)}>
{choice === "auto" ? "自动" : choice.toUpperCase()}
</OptionPill>
))}
</div>
</div> : null}
{profile.size.allowCustom ? <div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<SettingTitle color={theme.node.muted}>尺寸</SettingTitle>
<div className="flex items-center gap-2">
<span className="text-xs font-medium" style={{ color: theme.node.muted }}>
16倍数对齐
</span>
<span title="输入完成后自动向上补成 16 的倍数" onMouseDown={(event) => event.stopPropagation()}>
<Switch size="small" checked={snapDimensionToStep} onChange={setSnapDimensionToStep} />
</span>
</div>
</div>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-1.5">
<DimensionInput prefix="W" value={dimensions.width} disabled={activeSize === "auto"} theme={theme} alignToStep={snapDimensionToStep} onChange={(value) => updateDimension("width", value)} />
<span className="text-sm opacity-45">↔</span>
<DimensionInput prefix="H" value={dimensions.height} disabled={activeSize === "auto"} theme={theme} alignToStep={snapDimensionToStep} onChange={(value) => updateDimension("height", value)} />
</div>
</div> : null}
{availableAspects.length ? <div className="space-y-2">
<SettingTitle color={theme.node.muted}>尺寸或比例</SettingTitle>
<div className="grid grid-cols-4 gap-1.5 min-[380px]:grid-cols-5">
{availableAspects.map((item) => (
<button
key={item.value}
type="button"
className="flex h-[52px] cursor-pointer flex-col items-center justify-center gap-0.5 rounded-lg bg-transparent text-[var(--fs-label)] transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1"
style={{ background: selectedAspect?.value === item.value ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }}
onMouseDown={(event) => event.stopPropagation()}
onClick={() => selectAspect(item.value)}
>
<AspectIcon type={item.icon} width={item.width} height={item.height} color={theme.node.text} />
<span className="whitespace-nowrap">{item.label}</span>
</button>
))}
</div>
</div> : null}
<ImageSizePicker profile={profile} size={activeSize} quality={quality} onChange={(size, nextQuality) => { onConfigChange("size", size); if (nextQuality) onConfigChange("quality", nextQuality); }} />
{showCount && effectiveMaxCount > 1 ? (
<div className="space-y-2">
<SettingTitle color={theme.node.muted}>生成张数</SettingTitle>
@@ -197,45 +118,6 @@ export function ImageSettingsPanel({ config, onConfigChange, theme, showTitle =
);
}
function imageOptionAllowed(profile: ImageCapabilityConfig, option: AspectOption) {
if (profile.size.parameter === "none") return false;
if (profile.size.allowCustom && profile.size.values.length === 0) return true;
return [option.value, option.size, option.width && option.height ? `${option.width}x${option.height}` : ""].filter(Boolean).some((value) => profile.size.values.includes(String(value)));
}
// 宽高比选项直接取模型配置 values(与创作页面一致),不在白名单里的比例(如 8:1)也能显示。
function imageAspectOptions(profile: ImageCapabilityConfig): AspectOption[] {
if (profile.size.parameter === "none") return [];
const values = profile.size.values.filter((value) => value.trim().toLowerCase() !== "auto");
if (!values.length) return profile.size.allowCustom ? aspectOptions.filter((item) => item.value !== "auto") : [];
return values.map((value) => {
const known = aspectOptions.find((item) => (item.size || item.value) === value || item.value === value);
if (known) return known;
const parts = ratioParts(value);
return { value, label: value, size: value, width: parts?.width || 0, height: parts?.height || 0, icon: "custom" };
});
}
function ratioParts(value: string) {
const pixel = value.trim().match(/^(\d+)x(\d+)$/i);
if (pixel) {
const divisor = gcd(Number(pixel[1]), Number(pixel[2]));
return { width: Number(pixel[1]) / divisor, height: Number(pixel[2]) / divisor };
}
const ratio = value.trim().match(/^(\d+):(\d+)$/);
if (!ratio) return undefined;
return { width: Number(ratio[1]), height: Number(ratio[2]) };
}
function gcd(a: number, b: number): number {
return b ? gcd(b, a % b) : a;
}
function imageOptionValue(profile: ImageCapabilityConfig, option: AspectOption) {
const candidates = [option.size, option.value, option.width && option.height ? `${option.width}x${option.height}` : ""].filter(Boolean).map(String);
return candidates.find((value) => profile.size.values.includes(value)) || option.size || option.value || "auto";
}
export function ImageSettingsTheme({ theme, children }: { theme: CanvasTheme; children: ReactNode }) {
return (
<ConfigProvider
@@ -250,12 +132,12 @@ export function ImageSettingsTheme({ theme, children }: { theme: CanvasTheme; ch
}
export function imageQualityLabel(value: string) {
return ({ auto: "自动", high: "高", medium: "中", low: "低", "1k": "1K", "2k": "2K" } as Record<string, string>)[value] || value || "默认";
return ({ auto: "自动", high: "高", medium: "中", low: "低", "1k": "1K", "2k": "2K", "4k": "4K" } as Record<string, string>)[value.toLowerCase()] || value || "默认";
}
function isGrokResolutionQuality(profile: ImageCapabilityConfig) {
const values = profile.quality.values.map((item) => item.toLowerCase());
return values.includes("1k") || values.includes("2k");
return values.some((value) => ["1k", "2k", "4k"].includes(value));
}
export function imageSizeLabel(size: string) {
@@ -292,35 +174,6 @@ function OptionPill({ selected, disabled = false, theme, onClick, children }: {
);
}
function DimensionInput({ prefix, value, disabled, theme, alignToStep, onChange }: { prefix: string; value: number; disabled: boolean; theme: CanvasTheme; alignToStep: boolean; onChange: (value: number | null) => void }) {
const commit = (input: HTMLInputElement) => {
const next = alignDimension(Math.max(1, Math.floor(Number(input.value) || value || 1024)), alignToStep);
input.value = String(next);
onChange(next);
};
return (
<label className="flex h-8 overflow-hidden rounded-lg text-xs" style={{ background: theme.toolbar.itemHover, color: theme.node.text, opacity: disabled ? 0.55 : 1 }}>
<span className="grid w-8 place-items-center" style={{ color: theme.node.muted }}>
{prefix}
</span>
<input
type="number"
min={1}
disabled={disabled}
className="min-w-0 flex-1 bg-transparent px-2 outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
defaultValue={value || ""}
key={`${prefix}-${value}`}
onBlur={(event) => commit(event.currentTarget)}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
onMouseDown={(event) => event.stopPropagation()}
/>
</label>
);
}
function CountInput({ value, quickCount, max, theme, onChange }: { value: number; quickCount: number; max: number; theme: CanvasTheme; onChange: (value: number | null) => void }) {
const commit = (input: HTMLInputElement) => {
const next = Math.max(1, Math.min(max, Math.floor(Number(input.value) || 1)));
@@ -349,18 +202,6 @@ function CountInput({ value, quickCount, max, theme, onChange }: { value: number
);
}
function AspectIcon({ type, width, height, color }: { type: string; width: number; height: number; color: string }) {
if (type === "auto") return null;
const ratio = width / Math.max(1, height);
const boxWidth = ratio >= 1 ? 22 : Math.max(9, 22 * ratio);
const boxHeight = ratio >= 1 ? Math.max(9, 22 / ratio) : 22;
return (
<span className="grid h-6 w-8 place-items-center">
<span className="border-2" style={{ width: boxWidth, height: boxHeight, borderColor: color }} />
</span>
);
}
function SettingTitle({ children, color }: { children: string; color: string }) {
return (
<div className="text-xs font-medium" style={{ color }}>
@@ -368,15 +209,3 @@ function SettingTitle({ children, color }: { children: string; color: string })
</div>
);
}
function readSizeDimensions(size: string, fallback: { width: number; height: number }) {
const match = size?.match(/^(\d+)x(\d+)$/);
return {
width: match ? Number(match[1]) : fallback.width,
height: match ? Number(match[2]) : fallback.height,
};
}
function alignDimension(value: number, enabled: boolean) {
return enabled ? Math.ceil(value / DIMENSION_STEP) * DIMENSION_STEP : value;
}

View File

@@ -0,0 +1,264 @@
.image-size-picker,
.image-size-presets-editor {
display: grid;
min-width: 0;
gap: 10px;
width: 100%;
}
.image-size-label {
font-size: var(--fs-label);
font-weight: 600;
}
.image-size-tiers {
display: grid;
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
gap: 6px;
}
.image-size-tiers button,
.image-size-ratios button,
.image-size-auto {
border: 0;
border-radius: var(--r-md);
color: inherit;
background: var(--library-surface);
padding: 8px;
min-width: 0;
cursor: pointer;
}
.image-size-tiers button[aria-pressed="true"],
.image-size-ratios button[aria-pressed="true"],
.image-size-auto[aria-pressed="true"] {
background: var(--library-surface-hover);
box-shadow: inset 0 0 0 1px var(--library-selected-stroke);
}
.image-size-tiers button:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.image-size-picker button:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.image-size-ratios {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(62px, 1fr));
gap: 6px;
}
.image-size-ratios button {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 62px;
font-size: var(--fs-label);
overflow-wrap: anywhere;
}
.image-size-ratio-icon {
display: block;
width: 26px;
border: 1px solid currentColor;
border-radius: 2px;
opacity: 0.6;
}
.image-size-output {
padding: 9px 10px;
border-radius: var(--r-md);
background: var(--library-surface);
font-size: var(--fs-label);
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.image-size-hint,
.image-size-error {
margin: 0;
font-size: var(--fs-label);
line-height: 1.6;
overflow-wrap: anywhere;
}
.image-size-hint {
opacity: 0.6;
}
.image-size-error {
color: var(--destructive);
}
.image-size-custom summary {
cursor: pointer;
font-size: var(--fs-label);
padding: 6px 0;
}
.image-size-custom-input {
display: flex;
min-width: 0;
gap: 6px;
margin-top: 8px;
}
.image-size-custom-input input {
min-width: 0;
}
.image-size-preset-group {
display: grid;
grid-template-columns: 64px minmax(0, 1fr);
min-width: 0;
gap: 16px;
padding: 16px;
border-radius: var(--r-lg);
background: var(--library-surface);
}
.image-size-presets-editor {
container: image-presets / inline-size;
}
.image-size-editor-intro {
margin: 0 0 2px;
color: var(--muted-foreground);
font-size: var(--fs-label);
line-height: 1.6;
}
.image-size-preset-heading {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding-top: 4px;
}
.image-size-preset-heading strong {
font-size: var(--fs-body);
font-variant-numeric: tabular-nums;
}
.image-size-preset-heading > span,
.image-size-defaults-heading > span {
color: var(--muted-foreground);
font-size: var(--fs-label);
}
.image-size-preset-body {
display: grid;
gap: 10px;
min-width: 0;
}
.image-size-preset-options {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 84px), 1fr));
gap: 6px;
}
.image-size-preset-option,
.image-size-default-options button {
min-width: 0;
border: 0;
border-radius: var(--r-md);
background: var(--library-icon-surface);
color: inherit;
font-size: var(--fs-label);
cursor: pointer;
}
.image-size-preset-option {
display: grid;
gap: 5px;
padding: 10px 8px;
text-align: left;
overflow-wrap: anywhere;
}
.image-size-preset-option-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
font-weight: 600;
}
.image-size-preset-option-label svg {
flex: 0 0 auto;
}
.image-size-preset-option small {
color: var(--muted-foreground);
font-size: var(--fs-label);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.image-size-preset-option:hover:not(:disabled),
.image-size-default-options button:hover:not(:disabled) {
background: var(--library-surface-hover);
}
.image-size-presets-editor button[aria-pressed="true"] {
background: var(--library-surface-hover);
box-shadow: inset 0 0 0 1px var(--library-selected-stroke);
}
.image-size-presets-editor button:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.image-size-presets-editor button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.image-size-preset-add {
display: flex;
gap: 8px;
width: min(100%, 304px);
min-width: 0;
}
.image-size-preset-add input {
min-width: 0;
}
.image-size-defaults {
display: grid;
gap: 10px;
padding-block: 6px;
min-width: 0;
}
.image-size-defaults-heading {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 8px;
font-size: var(--fs-label);
}
.image-size-default-options {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.image-size-default-options button {
padding: 7px 10px;
background: var(--library-surface);
overflow-wrap: anywhere;
}
.admin-image-protocol-editor {
container: image-protocol / inline-size;
}
.admin-capability-protocol-grid.admin-image-protocol-grid {
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr);
align-items: start;
gap: 16px;
}
.admin-image-size-card {
grid-column: 1 / -1;
}
.admin-image-size-intro {
display: grid;
grid-template-columns: minmax(0, 320px) minmax(0, 1fr);
align-items: center;
gap: 16px;
margin-bottom: 4px;
}
@container image-presets (max-width: 560px) {
.image-size-preset-group {
grid-template-columns: minmax(0, 1fr);
gap: 10px;
padding: 12px;
}
.image-size-preset-heading {
flex-direction: row;
align-items: baseline;
gap: 8px;
padding-top: 0;
}
}
@container image-protocol (max-width: 640px) {
.admin-capability-protocol-grid.admin-image-protocol-grid,
.admin-image-size-intro {
grid-template-columns: minmax(0, 1fr);
}
.admin-image-size-intro {
gap: 8px;
}
}

View File

@@ -0,0 +1,174 @@
import { useState } from "react";
import "./image-size-picker.css";
import { Input, Button } from "antd";
import type { ImageCapabilityConfig } from "@/lib/model-capabilities";
import { IMAGE_RESOLUTIONS, imagePresetForRatio, imagePresetValue, imageQualityForTier, imageResolutionUsesQuality, imageSizePresets, imageTierAvailable } from "@/lib/image-size-presets";
import { buildImageResolutionOptions, type ImageResolutionOption, type ImageResolutionTier } from "@/lib/image-resolution-tiers";
import { resolveImageRequestSize, validateImageSize } from "@/services/api/image-validation";
export function ImageSizePicker({ profile, size, quality, onChange }: { profile: ImageCapabilityConfig; size: string; quality?: string; onChange: (size: string, quality?: string) => void }) {
const presets = imageSizePresets(profile).filter((preset) => imageTierAvailable(profile, preset.tier));
const visibleTiers = IMAGE_RESOLUTIONS.filter((value) => presets.some((preset) => preset.tier === value));
const [chosenTier, setChosenTier] = useState<ImageResolutionTier>("1k");
const [customPreset, setCustomPreset] = useState<ImageResolutionOption>();
const [custom, setCustom] = useState("");
const [error, setError] = useState("");
const matches = (preset: ImageResolutionOption) =>
imagePresetValue(profile, preset) === size && (profile.size.parameter !== "aspect_ratio" || !imageResolutionUsesQuality(profile) || imageQualityForTier(profile, preset.tier) === (quality || profile.quality.default));
let resolvedLegacySize: string | undefined;
if (profile.size.parameter === "size" && size.includes(":")) {
try {
resolvedLegacySize = resolveImageRequestSize(profile, quality, size)?.value;
} catch {
/* 保留旧值,交由请求校验报告错误。 */
}
}
let restoredCustom: ImageResolutionOption | undefined;
if (profile.size.allowCustom && size !== "auto") {
try {
if (profile.size.parameter === "size") restoredCustom = buildImageResolutionOptions([resolvedLegacySize || size])[0];
else if (profile.size.parameter === "aspect_ratio") {
const restoredTier = IMAGE_RESOLUTIONS.find((value) => imageQualityForTier(profile, value) === (quality || profile.quality.default)) || "1k";
restoredCustom = imagePresetForRatio(restoredTier, size);
}
} catch {
/* 无效配置不伪装成已选中的有效预设,交由请求校验处理。 */
}
}
const active =
(profile.size.allowCustom && customPreset && imageTierAvailable(profile, customPreset.tier) && matches(customPreset) ? customPreset : undefined) ||
presets.find(matches) ||
presets.find((preset) => preset.size === resolvedLegacySize) ||
(restoredCustom && imageTierAvailable(profile, restoredCustom.tier) ? restoredCustom : undefined);
const available = (value: ImageResolutionTier) => imageTierAvailable(profile, value) && (profile.size.allowCustom || presets.some((preset) => preset.tier === value));
const tier =
(active && visibleTiers.includes(active.tier) ? active.tier : undefined) ||
(profile.size.parameter === "aspect_ratio" ? visibleTiers.find((value) => imageQualityForTier(profile, value) === (quality || profile.quality.default)) : undefined) ||
(visibleTiers.includes(chosenTier) ? chosenTier : visibleTiers[0]) ||
"1k";
const choices = presets.filter((preset) => preset.tier === tier);
const select = (preset: ImageResolutionOption) => {
if (!available(preset.tier)) return;
setChosenTier(preset.tier);
setCustomPreset(preset);
setError("");
onChange(imagePresetValue(profile, preset), profile.size.parameter === "aspect_ratio" ? imageQualityForTier(profile, preset.tier) : undefined);
};
const makeCustom = (next: ImageResolutionTier, ratio: string) => {
const preset = imagePresetForRatio(next, ratio);
// 精确支持值保持原值;支持值之外的像素仍遵守请求端的 16px 步长。
if (profile.size.parameter === "size" && !profile.size.values.includes(preset.size)) {
preset.width = Math.round(preset.width / 16) * 16;
preset.height = Math.round(preset.height / 16) * 16;
preset.size = `${preset.width}x${preset.height}`;
validateImageSize(preset.width, preset.height);
}
return preset;
};
const changeTier = (next: ImageResolutionTier) => {
const ratio = active?.ratio || (size.includes(":") ? size : "1:1");
const candidate = presets.find((preset) => preset.tier === next && preset.ratio === ratio);
try {
if (candidate) select(candidate);
else if (profile.size.allowCustom) select(makeCustom(next, ratio));
else {
const first = presets.find((preset) => preset.tier === next);
if (first) select(first);
}
} catch (reason) {
setError(reason instanceof Error ? reason.message : "尺寸格式无效");
}
};
const applyCustom = () => {
try {
if (custom.includes(":") || custom.includes(":")) {
select(makeCustom(tier, custom));
return;
}
const match = custom.trim().match(/^(\d+)\s*[x×]\s*(\d+)$/i);
if (!match) throw new Error("输入比例 16:9,或像素 1824x1024");
const width = Number(match[1]),
height = Number(match[2]);
if (profile.size.parameter === "aspect_ratio") {
select(makeCustom(tier, `${width}:${height}`));
return;
}
const value = `${width}x${height}`;
validateImageSize(width, height, !profile.size.values.includes(value));
const preset = presets.find((item) => item.size === value) || {
...imagePresetForRatio(width * height <= 2_000_000 ? "1k" : width * height <= 4_300_000 ? "2k" : "4k", `${width}:${height}`),
width,
height,
size: value,
};
select(preset);
} catch (reason) {
setError(reason instanceof Error ? reason.message : "尺寸格式无效");
}
};
if (profile.size.parameter === "none") return null;
return (
<div className="image-size-picker">
{visibleTiers.length ? (
<>
<div className="image-size-label">分辨率</div>
<div className="image-size-tiers">
{visibleTiers.map((value) => (
<button type="button" key={value} aria-pressed={size !== "auto" && active?.tier === value} onClick={() => changeTier(value)}>
{value.toUpperCase()}
</button>
))}
</div>
</>
) : null}
{profile.size.values.includes("auto") ? (
<button
type="button"
className="image-size-auto"
aria-pressed={size === "auto"}
onClick={() => {
setError("");
onChange("auto");
}}
>
自动尺寸
</button>
) : null}
{choices.length ? <div className="image-size-label">宽高比</div> : null}
<div className="image-size-ratios">
{choices.map((preset) => (
<button
type="button"
key={`${preset.ratio}:${preset.size}`}
title={`${preset.ratio} · ${preset.width} × ${preset.height}`}
aria-pressed={size !== "auto" && active?.size === preset.size && active?.tier === tier}
onClick={() => select(preset)}
>
<span className="image-size-ratio-icon" style={{ width: 24 * Math.min(1, preset.width / preset.height), height: 24 * Math.min(1, preset.height / preset.width) }} />
<span>{preset.ratio}</span>
</button>
))}
</div>
{!choices.length ? <p className="image-size-hint">未配置预设尺寸{profile.size.allowCustom ? ",可输入自定义比例或尺寸" : ""}</p> : null}
<output aria-live="polite" className="image-size-output">
{size === "auto" ? "尺寸由模型决定" : active ? `${active.ratio} · ${active.width} × ${active.height} px` : size.replace("x", " × ")}
</output>
{profile.size.parameter === "aspect_ratio" ? <p className="image-size-hint">尺寸为换算参考,实际像素由模型决定{!imageResolutionUsesQuality(profile) ? ";当前协议未配置独立分辨率" : ""}。</p> : null}
{profile.size.allowCustom ? (
<details className="image-size-custom">
<summary>自定义比例或尺寸</summary>
<div className="image-size-custom-input">
<Input aria-label="自定义比例或尺寸" placeholder="16:9 或 1824x1024" value={custom} onChange={(event) => setCustom(event.target.value)} onPressEnter={applyCustom} />
<Button onClick={applyCustom}>应用</Button>
</div>
</details>
) : null}
{error ? (
<p role="alert" className="image-size-error">
{error}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,134 @@
import { useId, useState } from "react";
import { Button, Input } from "antd";
import { Check, Plus } from "lucide-react";
import "./image-size-picker.css";
import type { ImageCapabilityConfig } from "@/lib/model-capabilities";
import { IMAGE_RATIOS, IMAGE_RESOLUTIONS, imagePresetForRatio, imageSizeConfigWithPresets, imageSizePresets, imageTierAvailable } from "@/lib/image-size-presets";
import type { ImageResolutionTier } from "@/lib/image-resolution-tiers";
export function ImageSizePresetsEditor({ profile, disabled, onChange }: { profile: ImageCapabilityConfig; disabled?: boolean; onChange: (size: ImageCapabilityConfig["size"]) => void }) {
const presets = imageSizePresets(profile);
const id = useId();
const [drafts, setDrafts] = useState<Partial<Record<ImageResolutionTier, string>>>({});
const [errors, setErrors] = useState<Partial<Record<ImageResolutionTier, string>>>({});
const update = (tier: ImageResolutionTier, ratios: string[]) => {
if (disabled) return false;
try {
const next = [
...new Map(
ratios.map((ratio) => {
const normalized = imagePresetForRatio(tier, ratio);
const preset = presets.find((preset) => preset.tier === tier && preset.ratio === normalized.ratio) || normalized;
return [preset.ratio, preset] as const;
}),
).values(),
];
onChange(imageSizeConfigWithPresets(profile, [...presets.filter((preset) => preset.tier !== tier), ...next]));
setErrors((current) => ({ ...current, [tier]: "" }));
return true;
} catch (reason) {
setErrors((current) => ({ ...current, [tier]: reason instanceof Error ? reason.message : "比例格式无效" }));
return false;
}
};
const addRatio = (tier: ImageResolutionTier) => {
const ratios = (drafts[tier] || "")
.split(/[,,\n]/)
.map((value) => value.trim())
.filter(Boolean);
if (!ratios.length) return;
if (update(tier, [...presets.filter((preset) => preset.tier === tier).map((preset) => preset.ratio), ...ratios])) {
setDrafts((current) => ({ ...current, [tier]: "" }));
}
};
return (
<div className="image-size-presets-editor">
<p className="image-size-editor-intro">点选支持的比例,再次点击可移除。尺寸自动换算,已有精确尺寸保持不变。</p>
{IMAGE_RESOLUTIONS.map((tier) => {
const items = presets.filter((preset) => preset.tier === tier);
const ratios = [...new Set([...IMAGE_RATIOS, ...items.map((item) => item.ratio)])];
return (
<section key={tier} className="image-size-preset-group" aria-labelledby={`${id}-${tier}-title`}>
<header className="image-size-preset-heading">
<strong id={`${id}-${tier}-title`}>{tier.toUpperCase()}</strong>
<span>{items.length ? `${items.length} 个比例` : "未启用"}</span>
</header>
<div className="image-size-preset-body">
{!imageTierAvailable(profile, tier) ? <p className="image-size-hint">需先配置此档位对应的质量值,用户端才会开放。</p> : null}
<div className="image-size-preset-options" role="group" aria-label={`${tier.toUpperCase()} 支持的宽高比`}>
{ratios.map((ratio) => {
const selected = items.find((item) => item.ratio === ratio);
const dimensions = selected || imagePresetForRatio(tier, ratio);
return (
<button
key={ratio}
type="button"
disabled={disabled}
aria-pressed={Boolean(selected)}
aria-label={`${tier.toUpperCase()} ${ratio}`}
className="image-size-preset-option"
title={`${ratio} · ${dimensions.width} × ${dimensions.height} px${selected ? " · 点击移除" : " · 点击添加"}`}
onClick={() => update(tier, selected ? items.filter((item) => item.ratio !== ratio).map((item) => item.ratio) : [...items.map((item) => item.ratio), ratio])}
>
<span className="image-size-preset-option-label">
<span>{ratio}</span>
{selected ? <Check size={12} aria-hidden="true" /> : <Plus size={12} aria-hidden="true" />}
</span>
<small>
{dimensions.width} × {dimensions.height}
</small>
</button>
);
})}
</div>
<div className="image-size-preset-add">
<Input
aria-label={`${tier.toUpperCase()} 自定义比例`}
aria-invalid={Boolean(errors[tier])}
aria-describedby={errors[tier] ? `${id}-${tier}-error` : undefined}
disabled={disabled}
placeholder="其他比例,如 17:11"
value={drafts[tier] || ""}
onChange={(event) => {
setDrafts((current) => ({ ...current, [tier]: event.target.value }));
setErrors((current) => ({ ...current, [tier]: "" }));
}}
onPressEnter={(event) => {
event.preventDefault();
event.stopPropagation();
addRatio(tier);
}}
/>
<Button disabled={disabled || !drafts[tier]?.trim()} icon={<Plus size={14} />} onClick={() => addRatio(tier)} aria-label={`添加 ${tier.toUpperCase()} 比例`}>
添加
</Button>
</div>
{errors[tier] ? (
<p id={`${id}-${tier}-error`} role="alert" className="image-size-error">
{errors[tier]}
</p>
) : null}
</div>
</section>
);
})}
<div className="image-size-defaults">
<div className="image-size-defaults-heading">
<strong>默认输出</strong>
<span>用户选择模型时的初始尺寸</span>
</div>
<div className="image-size-default-options" role="group" aria-label="默认输出">
{profile.size.values.map((value) => {
const preset = presets.find((item) => (profile.size.parameter === "aspect_ratio" ? item.ratio === value : item.size === value));
const label = value === "auto" ? "自动" : preset && profile.size.parameter === "size" ? `${preset.tier.toUpperCase()} · ${preset.ratio}` : value;
return (
<button key={value} type="button" disabled={disabled} aria-pressed={profile.size.default === value} title={value} aria-label={`默认输出 ${label} ${value}`} onClick={() => onChange({ ...profile.size, default: value })}>
{label}
</button>
);
})}
</div>
</div>
</div>
);
}

View File

@@ -1,3 +1,5 @@
import { ImageSizePresetsEditor } from "./image-size-presets-editor";
import { imageSizeConfigWithPresets, imageSizePresets } from "@/lib/image-size-presets";
import { Input, InputNumber, Segmented, Select, Switch } from "antd";
import type { ReactNode } from "react";
@@ -18,20 +20,8 @@ const operationOptions = [
{ label: "音频生视频", value: "audio_to_video" },
];
function formatImageSizeTagLabel(size: string): string {
const raw = size.trim();
if (raw === "1:1") return "1:1 (方图)";
if (raw === "16:9") return "16:9 (横屏)";
if (raw === "9:16") return "9:16 (竖屏)";
if (raw === "1024x1024") return "1024x1024 (1:1)";
if (raw === "2048x2048") return "2048x2048 (2K 方)";
if (raw === "3840x2160") return "3840x2160 (4K 横屏)";
if (raw === "2160x3840") return "2160x3840 (4K 竖屏)";
return raw;
}
function imageSizeOptions(values: string[]) {
return values.map((v) => ({ label: formatImageSizeTagLabel(v), value: v }));
function ImageSizeHelp() {
return <p className="text-[var(--fs-label)] leading-relaxed text-foreground/60">按分辨率配置支持的比例,尺寸自动换算。size 发送像素,aspect_ratio 发送比例;独立分辨率由模型协议适配。实际输出尺寸以上游为准。</p>;
}
type Props = {
@@ -434,57 +424,40 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
if (section === "protocol") {
return (
<div className="admin-capability-protocol-editor">
<div className="admin-capability-protocol-grid">
<ProtocolParameterCard step="01" title="输出数量" description="设置单次生成图片数量">
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</ProtocolParameterCard>
<ProtocolParameterCard step="02" title="尺寸参数" description="定义尺寸字段、支持值与默认值">
<Segmented
block
disabled={disabled}
value={profile.size.parameter}
options={[
{ label: "不发送", value: "none" },
{ label: "size", value: "size" },
{ label: "aspect_ratio", value: "aspect_ratio" },
]}
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], default: "auto", allowCustom: false }
: { parameter, values: profile.size.values.length ? profile.size.values : ["1:1"], default: profile.size.default === "auto" ? "1:1" : profile.size.default },
);
}}
/>
<div className="admin-capability-protocol-editor admin-image-protocol-editor">
<div className="admin-capability-protocol-grid admin-image-protocol-grid">
<ProtocolParameterCard step="01" title="尺寸参数" description="按分辨率配置可用画幅,直接点选或输入比例" className="admin-image-size-card">
<div className="admin-image-size-intro">
<Segmented
block
disabled={disabled}
value={profile.size.parameter}
options={[
{ label: "不发送", value: "none" },
{ label: "size", value: "size" },
{ label: "aspect_ratio", value: "aspect_ratio" },
]}
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], presets: undefined, default: "auto", allowCustom: false }
: imageSizeConfigWithPresets({ ...profile, size: { ...profile.size, parameter } }, imageSizePresets(profile)),
);
}}
/>
<ImageSizeHelp />
</div>
{profile.size.parameter !== "none" ? (
<>
<Field label="支持值">
<Select
mode="tags"
className="admin-capability-tags w-full"
disabled={disabled}
value={profile.size.values}
options={imageSizeOptions(profile.size.values)}
tokenSeparators={[","]}
placeholder="例如 1:1、1024x1024"
onChange={(values) => updateSize({ values, default: values.includes(profile.size.default) || profile.size.allowCustom ? profile.size.default : values[0] || "auto" })}
/>
</Field>
<Field label="默认值">
<Select
className="w-full"
disabled={disabled}
value={profile.size.default}
options={profile.size.values.map((item) => ({ label: item, value: item }))}
onChange={(defaultValue) => updateSize({ default: defaultValue })}
/>
</Field>
<ImageSizePresetsEditor profile={profile} disabled={disabled} onChange={updateSize} />
<ParameterField label="允许自定义" description="允许支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</>
) : null}
</ProtocolParameterCard>
<ProtocolParameterCard step="02" title="输出数量" description="设置单次生成图片数量">
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</ProtocolParameterCard>
<ProtocolParameterCard step="03" title="可选参数" description="控制质量、背景与响应格式">
<ParameterField label="图片质量" description="发送 quality 参数" supported={profile.quality.supported} disabled={disabled} onChange={(supported) => updateQuality({ supported })} />
{profile.quality.supported ? (
@@ -543,6 +516,7 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
<NumberField label="单次生成张数" value={profile.maxOutputs} min={1} disabled={disabled} onChange={(maxOutputs) => update({ maxOutputs: maxOutputs || 1 })} />
</CapabilityBlock>
<CapabilityBlock title="尺寸参数">
<ImageSizeHelp />
<Segmented
block
disabled={disabled}
@@ -555,38 +529,14 @@ function ImageCapabilityEditor({ value, onChange, protocol, model, disabled, sec
onChange={(value) => {
const parameter = value as ImageCapabilityConfig["size"]["parameter"];
updateSize(
parameter === "none"
? { parameter, values: [], default: "auto", allowCustom: false }
: { parameter, values: profile.size.values.length ? profile.size.values : ["1:1"], default: profile.size.default === "auto" ? "1:1" : profile.size.default },
parameter === "none" ? { parameter, values: [], presets: undefined, default: "auto", allowCustom: false } : imageSizeConfigWithPresets({ ...profile, size: { ...profile.size, parameter } }, imageSizePresets(profile)),
);
}}
/>
{profile.size.parameter !== "none" ? (
<>
<Field label="支持值">
<Select
mode="tags"
className="admin-capability-tags w-full"
disabled={disabled}
value={profile.size.values}
options={imageSizeOptions(profile.size.values)}
tokenSeparators={[","]}
placeholder="例如 1:1、1024x1024"
onChange={(values) => updateSize({ values, default: values.includes(profile.size.default) || profile.size.allowCustom ? profile.size.default : values[0] || "auto" })}
/>
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label="默认值">
<Select
className="w-full"
disabled={disabled}
value={profile.size.default}
options={profile.size.values.map((item) => ({ label: item, value: item }))}
onChange={(defaultValue) => updateSize({ default: defaultValue })}
/>
</Field>
<ParameterField label="允许自定义" description="允许用户输入支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</div>
<ImageSizePresetsEditor profile={profile} disabled={disabled} onChange={updateSize} />
<ParameterField label="允许自定义" description="允许用户输入支持值之外的尺寸" supported={profile.size.allowCustom} disabled={disabled} onChange={(allowCustom) => updateSize({ allowCustom })} />
</>
) : null}
</CapabilityBlock>
@@ -665,9 +615,9 @@ function ReferenceCard({ title, description, children }: { title: string; descri
);
}
function ProtocolParameterCard({ step, title, description, children }: { step: string; title: string; description: string; children: ReactNode }) {
function ProtocolParameterCard({ step, title, description, children, className = "" }: { step: string; title: string; description: string; children: ReactNode; className?: string }) {
return (
<section className="admin-capability-protocol-card">
<section className={`admin-capability-protocol-card ${className}`}>
<header className="admin-capability-protocol-card-heading">
<span>{step}</span>
<div>

View File

@@ -59,11 +59,13 @@ function parseImageResolutionOption(value: string): ImageResolutionOption | null
if (!match) return null;
const width = Number(match[1]);
const height = Number(match[2]);
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0) return null;
const pixels = width * height;
const tier: ImageResolutionTier | null = pixels <= 2_000_000 ? "1k" : pixels <= 4_300_000 ? "2k" : pixels <= 8_294_400 ? "4k" : null;
if (!tier) return null;
const ratio = closestRatio(width / height);
if (!ratio) return null;
let a = width, b = height;
while (b) [a, b] = [b, a % b];
const ratio = closestRatio(width / height) || `${width / a}:${height / a}`;
return { size: `${width}x${height}`, tier, ratio, width, height };
}

View File

@@ -0,0 +1,95 @@
import { buildImageResolutionOptions, type ImageResolutionOption, type ImageResolutionTier } from "./image-resolution-tiers";
import type { ImageCapabilityConfig } from "./model-capabilities";
export const IMAGE_RESOLUTIONS: ImageResolutionTier[] = ["1k", "2k", "4k"];
export const IMAGE_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "21:9"];
const standardSizes: Record<string, string[]> = {
"1:1": ["1024x1024", "2048x2048", "2880x2880"],
"16:9": ["1824x1024", "2752x1536", "3840x2160"],
"9:16": ["1024x1824", "1536x2752", "2160x3840"],
"4:3": ["1360x1024", "2304x1728", "3264x2448"],
"3:4": ["1024x1360", "1728x2304", "2448x3264"],
"3:2": ["1536x1024", "2496x1664", "3504x2336"],
"2:3": ["1024x1536", "1664x2496", "2336x3504"],
"21:9": ["2048x878", "3136x1344", "3808x1632"],
};
export function imagePresetForRatio(tier: ImageResolutionTier, input: string): ImageResolutionOption {
const match = input.trim().match(/^(\d{1,5})\s*[::]\s*(\d{1,5})$/);
if (!match) throw new Error("请输入宽高比,例如 16:9");
let w = Number(match[1]),
h = Number(match[2]);
if (!w || !h || Math.max(w, h) / Math.min(w, h) > 3) throw new Error("宽高比必须为正数,且不超过 3:1");
let a = w,
b = h;
while (b) [a, b] = [b, a % b];
w /= a;
h /= a;
const ratio =
Object.keys(standardSizes).find((value) => {
const [width, height] = value.split(":").map(Number);
return width * h === height * w;
}) || `${w}:${h}`;
const index = IMAGE_RESOLUTIONS.indexOf(tier);
if (index < 0) throw new Error("分辨率仅支持 1K、2K、4K");
const standard = standardSizes[ratio]?.[index];
const pixels = [1_048_576, 4_194_304, 8_294_400][index];
let width = Math.round(Math.sqrt((pixels * w) / h) / 16) * 16;
let height = Math.round((width * h) / w / 16) * 16;
while (width * height > pixels || Math.max(width, height) > 3840) {
if (width >= height) {
width -= 16;
height = Math.round((width * h) / w / 16) * 16;
} else {
height -= 16;
width = Math.round((height * w) / h / 16) * 16;
}
}
if (standard) [width, height] = standard.split("x").map(Number);
return { tier, ratio, width, height, size: `${width}x${height}` };
}
export function imageQualityForTier(profile: ImageCapabilityConfig, tier: ImageResolutionTier) {
const aliases = { "1k": ["1k", "low"], "2k": ["2k", "medium"], "4k": ["4k", "high"] }[tier];
return profile.quality.supported ? profile.quality.values.find((value) => aliases.includes(value.toLowerCase())) : undefined;
}
export function imageResolutionUsesQuality(profile: ImageCapabilityConfig) {
return profile.size.parameter === "aspect_ratio" && IMAGE_RESOLUTIONS.some((tier) => imageQualityForTier(profile, tier));
}
export function imageTierAvailable(profile: ImageCapabilityConfig, tier: ImageResolutionTier) {
// 比例协议必须能把档位传给上游;允许自定义比例不等于支持任意分辨率。
if (profile.size.parameter !== "aspect_ratio") return profile.size.parameter !== "none";
return imageResolutionUsesQuality(profile) ? Boolean(imageQualityForTier(profile, tier)) : tier === "1k";
}
export function imageSizePresets(profile: ImageCapabilityConfig): ImageResolutionOption[] {
if (profile.size.parameter === "none") return [];
if (profile.size.presets) return profile.size.presets;
const pixels = buildImageResolutionOptions(profile.size.values);
const tiers = profile.size.parameter === "aspect_ratio" ? IMAGE_RESOLUTIONS.filter((tier) => imageQualityForTier(profile, tier)) : ["1k" as const];
const ratios = (tiers.length ? tiers : ["1k" as const]).flatMap((tier) =>
profile.size.values.flatMap((ratio) => {
try {
const preset = imagePresetForRatio(tier, ratio);
return pixels.some((pixel) => pixel.ratio === preset.ratio) ? [] : [preset];
} catch {
return [];
}
}),
);
return [...pixels, ...ratios];
}
export function imagePresetValue(profile: ImageCapabilityConfig, preset: ImageResolutionOption) {
if (!profile.size.presets && !profile.size.allowCustom && preset.tier === "1k" && profile.size.values.includes(preset.ratio) && !profile.size.values.includes(preset.size)) return preset.ratio;
return profile.size.parameter === "aspect_ratio" ? preset.ratio : preset.size;
}
export function imageSizeConfigWithPresets(profile: ImageCapabilityConfig, presets: ImageResolutionOption[]): ImageCapabilityConfig["size"] {
const values = [...new Set(presets.map((preset) => (profile.size.parameter === "aspect_ratio" ? preset.ratio : preset.size)))];
if (profile.size.values.includes("auto")) values.unshift("auto");
if (!values.length) values.push("auto");
return { ...profile.size, presets, values, default: values.includes(profile.size.default) ? profile.size.default : values[0] || "auto" };
}

View File

@@ -1,4 +1,5 @@
import type { ModelProtocol, ModelProtocolWorkflow } from "@/lib/model-protocols";
import type { ImageResolutionOption } from "@/lib/image-resolution-tiers";
export type ModelCapabilityConfig = {
version: number;
@@ -31,6 +32,7 @@ export type ImageCapabilityConfig = {
values: string[];
default: string;
allowCustom: boolean;
presets?: ImageResolutionOption[];
};
quality: {
supported: boolean;

View File

@@ -1,5 +1,6 @@
import { defaultImageCapabilityConfig, modelCapabilityConfigFor, normalizeImageValue, normalizeVideoValue, STANDARD_IMAGE_SIZE_VALUES, videoDurationAllowed, type ImageCapabilityConfig } from "@/lib/model-capabilities";
import { videoResolutionComparisonKey } from "@/lib/video-generation-options";
import { imageSizePresets } from "@/lib/image-size-presets";
import { modelOptionName, resolveModelChannel, selectableModelsByCapability, type AiConfig, type ModelCapability } from "@/stores/use-config-store";
export type ModelInputSummary = {
@@ -229,7 +230,8 @@ export function mergedImageCapabilityConfig(config: AiConfig, selected: string):
const allowCustom = profiles.some((profile) => profile.size.allowCustom || profile.size.values.includes("*"));
const values = concreteValues.length ? concreteValues : allowCustom ? [...STANDARD_IMAGE_SIZE_VALUES] : [];
const base = selectedProfile || profiles[0];
return { ...base, size: { ...base.size, values, allowCustom } };
const presets = profiles.some((profile) => profile.size.presets) ? [...new Map(profiles.flatMap((profile) => imageSizePresets(profile)).map((preset) => [`${preset.tier}:${preset.ratio}:${preset.size}`, preset])).values()] : undefined;
return { ...base, size: { ...base.size, values, allowCustom, presets } };
}
// 切换模型后初始化图片参数为该模型能力默认值,避免旧参数在目标模型族不兼容导致无法切换。

View File

@@ -1,6 +1,7 @@
import { ConfigProvider, Dropdown, Tooltip } from "antd";
import type { MenuProps } from "antd";
import {
Activity,
ArrowLeft,
BarChart3,
BellRing,
@@ -88,6 +89,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" /> },

View 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>
);
}

View File

@@ -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: {

View File

@@ -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)}

View File

@@ -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]);

View File

@@ -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, Modal, Popover, Spin, Tooltip } from "antd";
import { Reorder } from "motion/react";
@@ -21,7 +23,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";
@@ -1620,46 +1622,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 = [
@@ -1670,10 +1647,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>;

View File

@@ -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, Empty, Form, Image, Input, InputNumber, Modal, Segmented, Select, Tag } from "antd";
@@ -505,20 +507,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>

View File

@@ -29,6 +29,7 @@ const ArkPrivateAssetsSettingsPage = lazy(() => import("@/pages/admin/settings/a
const ResponseInterceptionSettingsPage = lazy(() => import("@/pages/admin/settings/response-interception-settings-page"));
const ThirdPartySettingsPage = lazy(() => import("@/pages/admin/settings/libtv-settings-page"));
const SystemUpdatePage = lazy(() => import("@/pages/admin/settings/system-update-page"));
const SystemPerformancePage = lazy(() => import("@/pages/admin/settings/system-performance-page"));
const StoryboardPromptsPage = lazy(() => import("@/pages/admin/storyboard-prompts/storyboard-prompts-page"));
const UsersPage = lazy(() => import("@/pages/admin/users/users-page"));
const AssetsPage = lazy(loadAssetsPage);
@@ -207,6 +208,7 @@ export const router = createBrowserRouter([
{ path: "settings/response-interception", element: <ResponseInterceptionSettingsPage /> },
{ path: "settings/third-party", element: <ThirdPartySettingsPage /> },
{ path: "settings/system-update", element: <SystemUpdatePage /> },
{ path: "settings/system-performance", element: <SystemPerformancePage /> },
{ path: "settings/libtv", element: <Navigate to="/admin/settings/third-party" replace /> },
],
},

View File

@@ -77,9 +77,9 @@ export function parseImageDimensions(value: string) {
return { width: Number(match[1]), height: Number(match[2]) };
}
export function validateImageSize(width: number, height: number) {
export function validateImageSize(width: number, height: number, requireStepAlignment = true) {
if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw new Error("图像尺寸必须是正整数,例如 1024x1024");
if (width % IMAGE_SIZE_STEP !== 0 || height % IMAGE_SIZE_STEP !== 0) throw new Error("图像尺寸的宽高必须是 16 的倍数,请调整尺寸");
if (requireStepAlignment && (width % IMAGE_SIZE_STEP !== 0 || height % IMAGE_SIZE_STEP !== 0)) throw new Error("图像尺寸的宽高必须是 16 的倍数,请调整尺寸");
if (Math.max(width, height) > IMAGE_MAX_EDGE) throw new Error("图像尺寸最长边不能超过 3840px,请调整尺寸");
if (Math.max(width, height) / Math.min(width, height) > IMAGE_MAX_RATIO) throw new Error("图像宽高比不能超过 3:1,请调整尺寸");
const pixels = width * height;
@@ -115,6 +115,19 @@ function dimensionGCD(left: number, right: number) {
export function resolveImageRequestSize(profile: ImageCapabilityConfig, quality: string | undefined, size: string) {
const request = imageSizeRequest(profile, size);
if (!request) return undefined;
if (request.parameter === "aspect_ratio" && !profile.size.allowCustom && profile.size.presets?.length) {
const normalized = normalizeQuality(quality || profile.quality.default);
const tier = normalized === "low" ? "1k" : normalized === "medium" ? "2k" : normalized === "high" ? "4k" : undefined;
if (tier && !profile.size.presets.some((preset) => preset.tier === tier && preset.ratio === request.value)) {
throw new Error("当前分辨率不支持所选图片宽高比");
}
}
const dimensions = parseImageDimensions(request.value);
// 模型声明的精确预设(如 1920x1080)不应被自定义尺寸的 16 像素对齐规则拒绝。
if (request.parameter === "size" && dimensions && profile.size.values.includes(request.value)) {
validateImageSize(dimensions.width, dimensions.height, false);
return request;
}
const value = request.parameter === "size" ? resolveRequestSize(quality, request.value) : resolveAspectRatio(request.value);
return value ? { parameter: request.parameter, value } : undefined;
}

View File

@@ -0,0 +1,125 @@
import { apiClient, request } from "./request";
export type DatabasePoolStats = {
maxOpenConnections: number;
openConnections: number;
inUse: number;
idle: number;
waitCount: number;
waitDurationMs: number;
maxIdleClosed: number;
maxLifetimeClosed: number;
};
export type SystemPerformanceCacheGroup = {
id: string;
label: string;
keys: number;
clearable: boolean;
};
export type SystemPerformance = {
collectedAt: string;
status: "healthy" | "degraded";
host: {
hostname: string;
os: string;
arch: string;
cpuCores: number;
gomaxprocs: number;
processId: number;
uptimeSeconds: number;
goroutines: number;
activeWorkerTasks: number;
loadAverage: [number, number, number];
loadAverageAvailable: boolean;
};
memory: {
systemAvailable: boolean;
totalBytes: number;
usedBytes: number;
availableBytes: number;
usagePercent: number;
heapAllocBytes: number;
heapSysBytes: number;
sysBytes: number;
heapObjects: number;
gcCount: number;
lastGCAt?: string;
};
disk: {
available: boolean;
writable: boolean;
totalBytes: number;
usedBytes: number;
freeBytes: number;
usagePercent: number;
};
database: {
driver: string;
connected: boolean;
latencyMs: number;
databaseBytes?: number;
schema: { current: number; expected: number; ready: boolean };
pool: DatabasePoolStats;
postgres?: {
serverVersion?: string;
databaseBytes?: number;
connections?: number;
maxConnections?: number;
transactions?: number;
rollbacks?: number;
cacheHitRate?: number;
tempFiles?: number;
tempBytes?: number;
deadlocks?: number;
};
};
redis: {
configured: boolean;
connected: boolean;
mode: "redis" | "local";
latencyMs?: number;
version?: string;
uptimeSeconds?: number;
usedMemoryBytes?: number;
peakMemoryBytes?: number;
maxMemoryBytes?: number;
maxMemoryPolicy?: string;
keys?: number;
clients?: number;
blockedClients?: number;
opsPerSecond?: number;
hitRate?: number;
expiredKeys?: number;
evictedKeys?: number;
pool: {
hits: number;
misses: number;
timeouts: number;
totalConnections: number;
idleConnections: number;
staleConnections: number;
pendingRequests: number;
};
cacheGroups: SystemPerformanceCacheGroup[];
statusMessage?: string;
};
build: { version: string; commit: string; buildTime: string; goVersion: string };
};
export type RuntimeCacheClearResult = {
scope: "runtime";
deletedKeys: number;
memoryEntries: number;
groups: Array<{ id: string; deletedKeys: number }>;
clearedAt: string;
};
export function getSystemPerformance(signal?: AbortSignal) {
return request<SystemPerformance>(apiClient.get("/admin/system-performance", { signal }));
}
export function clearRuntimeCache() {
return request<RuntimeCacheClearResult>(apiClient.post("/admin/system-performance/cache/clear", { scope: "runtime" }));
}

View File

@@ -10212,3 +10212,316 @@ html[data-magicui-theme-vt="active"] .admin-shell * {
border-left: 0;
}
}
/* 系统性能:高密度运维快照,仅作用于管理员性能页。 */
.admin-system-performance {
gap: 12px;
padding-bottom: 24px;
}
.admin-performance-auto,
.admin-performance-statusbar,
.admin-performance-statusbar > div,
.admin-performance-kpi-heading,
.admin-performance-cache-note,
.admin-performance-safety {
display: flex;
align-items: center;
}
.admin-performance-auto {
gap: 7px;
color: var(--admin-text-muted);
font-size: 12px;
}
.admin-performance-alert {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
padding: 9px 11px;
border: 1px solid color-mix(in srgb, var(--admin-status-error) 28%, var(--admin-divider));
border-radius: 8px;
background: color-mix(in srgb, var(--admin-status-error) 6%, var(--admin-layer-1));
color: var(--admin-status-error);
font-size: 12px;
}
.admin-performance-statusbar {
justify-content: space-between;
gap: 12px;
min-height: 34px;
padding: 6px 10px;
border: 1px solid var(--admin-divider);
border-radius: 8px;
background: var(--admin-layer-2);
color: var(--admin-text-muted);
font-size: 11px;
}
.admin-performance-statusbar > div {
gap: 9px;
min-width: 0;
}
.admin-performance-kpis {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
overflow: hidden;
border: 1px solid var(--admin-card-border);
border-radius: 10px;
background: var(--admin-layer-1);
box-shadow: var(--admin-card-shadow);
}
.admin-performance-kpi {
min-width: 0;
padding: 12px 14px 11px;
}
.admin-performance-kpi + .admin-performance-kpi {
border-left: 1px solid var(--admin-divider);
}
.admin-performance-kpi-heading {
gap: 7px;
color: var(--admin-text-muted);
}
.admin-performance-kpi-heading > span {
display: grid;
width: 25px;
height: 25px;
place-items: center;
border-radius: 6px;
background: var(--admin-layer-2);
color: var(--admin-chart-primary);
}
.admin-performance-kpi p {
min-width: 0;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.admin-performance-kpi-heading p {
font-size: 11px;
font-weight: 600;
}
.admin-performance-kpi > strong {
display: block;
margin-top: 8px;
color: var(--admin-text-primary);
font-size: 20px;
font-weight: 650;
letter-spacing: -0.025em;
}
.admin-performance-kpi > p {
margin-top: 3px;
color: var(--admin-text-muted);
font-size: 10px;
}
.admin-performance-kpi .ant-progress {
display: block;
margin-top: 7px;
line-height: 1;
}
.admin-performance-grid {
display: grid;
grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr);
align-items: start;
gap: 12px;
}
.admin-performance-side-stack {
display: grid;
gap: 12px;
}
.admin-system-performance .admin-settings-section-summary {
padding: 12px 14px;
}
.admin-system-performance .admin-settings-section-content {
padding: 0;
}
.admin-performance-facts {
display: grid;
grid-template-columns: minmax(112px, 0.72fr) minmax(0, 1.45fr);
margin: 0;
}
.admin-performance-facts dt,
.admin-performance-facts dd {
min-width: 0;
margin: 0;
padding: 8px 14px;
border-top: 1px solid var(--admin-row-border);
font-size: 11px;
line-height: 1.45;
}
.admin-performance-facts dt {
color: var(--admin-text-muted);
}
.admin-performance-facts dd {
color: var(--admin-text-secondary);
overflow-wrap: anywhere;
}
.admin-performance-submetrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
border-top: 1px solid var(--admin-divider);
}
.admin-performance-submetrics > div {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
padding: 9px 14px;
}
.admin-performance-submetrics > div:nth-child(even) {
border-left: 1px solid var(--admin-row-border);
}
.admin-performance-submetrics > div:nth-child(n + 3) {
border-top: 1px solid var(--admin-row-border);
}
.admin-performance-submetrics span,
.admin-performance-cache-groups small {
color: var(--admin-text-muted);
font-size: 10px;
}
.admin-performance-submetrics strong {
font-size: 11px;
font-weight: 600;
}
.admin-performance-cache-groups {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.admin-performance-cache-groups > div {
display: grid;
grid-template-columns: minmax(0, 1fr) auto auto;
align-items: baseline;
gap: 5px;
padding: 13px 14px;
border-top: 1px solid var(--admin-row-border);
}
.admin-performance-cache-groups > div + div {
border-left: 1px solid var(--admin-row-border);
}
.admin-performance-cache-groups span {
overflow: hidden;
color: var(--admin-text-muted);
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.admin-performance-cache-groups strong {
font-size: 16px;
font-weight: 650;
}
.admin-performance-safety {
flex-wrap: wrap;
gap: 7px 12px;
padding: 9px 14px;
border-top: 1px solid var(--admin-divider);
background: var(--admin-layer-2);
color: var(--admin-text-muted);
font-size: 10px;
}
.admin-performance-safety strong {
color: var(--admin-status-success);
}
.admin-performance-safety span::before {
margin-right: 5px;
color: var(--admin-status-success);
content: "✓";
}
.admin-performance-cache-note {
gap: 6px;
color: var(--admin-text-muted);
font-size: 11px;
}
.admin-performance-confirm {
display: grid;
gap: 8px;
color: var(--admin-text-secondary);
font-size: 13px;
line-height: 1.65;
}
.admin-performance-confirm p {
margin: 0;
}
@media (max-width: 1080px) {
.admin-performance-kpis,
.admin-performance-cache-groups {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.admin-performance-kpi:nth-child(3),
.admin-performance-kpi:nth-child(4),
.admin-performance-cache-groups > div:nth-child(n + 3) {
border-top: 1px solid var(--admin-divider);
}
.admin-performance-kpi:nth-child(3),
.admin-performance-cache-groups > div:nth-child(3) {
border-left: 0;
}
}
@media (max-width: 820px) {
.admin-performance-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 560px) {
.admin-performance-statusbar {
align-items: flex-start;
flex-direction: column;
}
.admin-performance-kpis,
.admin-performance-cache-groups {
grid-template-columns: 1fr;
}
.admin-performance-kpi + .admin-performance-kpi,
.admin-performance-cache-groups > div + div {
border-top: 1px solid var(--admin-divider);
border-left: 0;
}
.admin-performance-facts {
grid-template-columns: 100px minmax(0, 1fr);
}
}

View File

@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { CanvasNode } from "../src/components/canvas/canvas-node";
import { CanvasNodeType } from "../src/types/canvas";
const noop = () => {};
function renderChild(options: { selected?: boolean; opening?: boolean; closing?: boolean } = {}) {
return renderToStaticMarkup(
<CanvasNode
data={{ id: "child", type: CanvasNodeType.Image, title: "子图", position: { x: 600, y: 100 }, width: 340, height: 240, metadata: { batchRootId: "root", status: "idle" } }}
scale={1}
isSelected={Boolean(options.selected)}
isRelated={false}
isFocusRelated={false}
isConnectionTarget={false}
showImageInfo={false}
batchOpening={options.opening}
batchClosing={options.closing}
batchMotion={{ x: -566, y: -86, index: 0 }}
onMouseDown={noop}
onHoverStart={noop}
onHoverEnd={noop}
onConnectStart={noop}
onResize={noop}
onContentChange={noop}
onContextMenu={noop}
/>,
);
}
describe("图片组子图动画", () => {
test("普通挂载与选中子图都不播放展开动画", () => {
for (const selected of [false, true]) {
const markup = renderChild({ selected });
expect(markup).not.toContain("canvas-batch-child-in");
expect(markup).not.toContain("canvas-batch-child-out");
}
});
test("仅在图片组展开或收起期间播放对应动画", () => {
expect(renderChild({ opening: true })).toContain("canvas-batch-child-in");
expect(renderChild({ closing: true })).toContain("canvas-batch-child-out");
});
});

View File

@@ -9,6 +9,7 @@ import {
supportsImageResolutionPresets,
} from "../src/lib/image-resolution-tiers";
import { defaultImageCapabilityConfig } from "../src/lib/model-capabilities";
import { resolveImageRequestSize } from "../src/services/api/image-validation";
const sizes = [
"1024x1024", "1360x1024", "1024x1360", "1536x1024", "1024x1536", "1024x1280", "1280x1024", "2048x878", "1824x1024", "1024x1824",
@@ -17,6 +18,17 @@ const sizes = [
];
describe("image resolution tiers", () => {
test("精确像素预设保持请求原值,比例协议发送比例", () => {
const profile = defaultImageCapabilityConfig("openai-image", "test");
profile.size = { parameter: "size", values: ["1920x1080", "3840x2160", "2160x3840", "1824x1024"], default: "1920x1080", allowCustom: false };
expect(imageResolutionChoices(profile.size.values)).toEqual(["1k", "2k", "4k"]);
expect(imageSizeForResolution(buildImageResolutionOptions(profile.size.values), "1k", "16:9")).toBe("1824x1024");
expect(resolveImageRequestSize(profile, undefined, "1920x1080")).toEqual({ parameter: "size", value: "1920x1080" });
profile.size = { parameter: "aspect_ratio", values: ["16:9"], default: "16:9", allowCustom: false };
expect(resolveImageRequestSize(profile, undefined, "16:9")).toEqual({ parameter: "aspect_ratio", value: "16:9" });
profile.size = { parameter: "size", values: [], default: "auto", allowCustom: true };
expect(() => resolveImageRequestSize(profile, undefined, "1920x1080")).toThrow("16 的倍数");
});
test("将 Xiaobaishu 的精确尺寸整理为 1K、2K、4K 各十种比例", () => {
const options = buildImageResolutionOptions(sizes);

View File

@@ -0,0 +1,156 @@
import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { ImageSizePicker } from "../src/components/image-size-picker";
import { ImageSizePresetsEditor } from "../src/components/image-size-presets-editor";
import { ModelCapabilityEditor } from "../src/components/model-capability-editor";
import { defaultImageCapabilityConfig, normalizeModelCapabilityConfig } from "../src/lib/model-capabilities";
import { IMAGE_RATIOS, IMAGE_RESOLUTIONS, imagePresetForRatio, imagePresetValue, imageQualityForTier, imageSizeConfigWithPresets, imageSizePresets, imageTierAvailable } from "../src/lib/image-size-presets";
import { buildImageResolutionOptions } from "../src/lib/image-resolution-tiers";
import { resolveImageRequestSize, validateImageSize } from "../src/services/api/image-validation";
import { buildGeminiImageGenerationConfig } from "../src/lib/gemini-image";
describe("统一图片分辨率与宽高比", () => {
test("像素协议从旧比例配置切换 4K 后发送真实像素,不回退到 1K", () => {
const profile = defaultImageCapabilityConfig();
profile.size = { parameter: "size", values: ["16:9"], default: "16:9", allowCustom: true };
const value = imagePresetValue(profile, imagePresetForRatio("4k", "16:9"));
expect(value).toBe("3840x2160");
expect(resolveImageRequestSize(profile, "auto", value)).toEqual({ parameter: "size", value: "3840x2160" });
const legacy = renderToStaticMarkup(<ImageSizePicker profile={profile} size="16:9" onChange={() => {}} />);
expect(legacy).toContain("1824 × 1024 px");
const reopened = renderToStaticMarkup(<ImageSizePicker profile={profile} size="3840x1920" onChange={() => {}} />);
expect(reopened).not.toMatch(/<button[^>]*>4K/);
expect(reopened).toContain("2:1 · 3840 × 1920 px");
});
test("常用比例保持明确尺寸,等价比例归一", () => {
expect(imagePresetForRatio("1k", "16:9").size).toBe("1824x1024");
expect(imagePresetForRatio("4k", "9:16").size).toBe("2160x3840");
expect(imagePresetForRatio("1k", "32:18")).toEqual(imagePresetForRatio("1k", "16:9"));
expect(imagePresetForRatio("2k", "7:3").ratio).toBe("21:9");
expect(imagePresetForRatio("2k", "34:22").ratio).toBe("17:11");
});
test("三档预设与任意合理比例都满足像素范围", () => {
for (const tier of IMAGE_RESOLUTIONS)
for (const ratio of [...IMAGE_RATIOS, "17:11", "3:1", "1:3", "99999:99998"]) {
const preset = imagePresetForRatio(tier, ratio);
expect(() => validateImageSize(preset.width, preset.height, false)).not.toThrow();
}
for (const ratio of ["0:9", "4:1", "1:4", "NaN:1", "1.5:1", "999999999:1"]) {
expect(() => imagePresetForRatio("1k", ratio)).toThrow();
}
});
test("管理员设置同步支持值、默认值,并保持精确尺寸", () => {
const profile = defaultImageCapabilityConfig();
profile.size = { parameter: "size", values: ["1920x1080"], default: "1920x1080", allowCustom: false };
const existing = imageSizePresets(profile);
const added = imagePresetForRatio("1k", "17:11");
profile.size = imageSizeConfigWithPresets(profile, [...existing, added]);
expect(profile.size.values).toEqual(["1920x1080", added.size]);
expect(profile.size.default).toBe("1920x1080");
expect(resolveImageRequestSize(profile, undefined, "1920x1080")?.value).toBe("1920x1080");
expect(normalizeModelCapabilityConfig({ version: 1, image: profile }).image?.size.presets).toEqual(profile.size.presets);
expect(imageSizeConfigWithPresets(profile, [added]).default).toBe(added.size);
});
test("非标准精确像素不会从选项中消失", () => {
expect(buildImageResolutionOptions(["1360x880"])[0]).toMatchObject({ size: "1360x880", ratio: "17:11" });
expect(buildImageResolutionOptions(["0x1024", "1024x0"])).toEqual([]);
});
test("比例协议分别发送比例和分辨率,不把自定义权限当作 4K 能力", () => {
const grok = defaultImageCapabilityConfig("grok-image", "grok-imagine-image");
grok.size.allowCustom = true;
expect(imageTierAvailable(grok, "4k")).toBe(false);
expect(imageSizePresets(grok).some((preset) => preset.tier === "4k")).toBe(false);
const gemini = defaultImageCapabilityConfig("gemini-image", "test");
const preset = imagePresetForRatio("4k", "16:9");
expect(buildGeminiImageGenerationConfig(imagePresetValue(gemini, preset), imageQualityForTier(gemini, "4k")).imageConfig).toEqual({ aspectRatio: "16:9", imageSize: "4K" });
gemini.size.allowCustom = true;
const reopened = renderToStaticMarkup(<ImageSizePicker profile={gemini} size="17:11" quality="high" onChange={() => {}} />);
expect(reopened).toMatch(/aria-pressed="true"[^>]*>4K/);
expect(reopened).toContain("17:11");
});
test("比例与档位的组合必须在该档位配置中,允许自定义则放开比例", () => {
const profile = defaultImageCapabilityConfig("gemini-image", "test");
profile.size = imageSizeConfigWithPresets(profile, [imagePresetForRatio("1k", "1:1"), imagePresetForRatio("2k", "16:9")]);
expect(() => resolveImageRequestSize(profile, "medium", "1:1")).toThrow("当前分辨率");
expect(resolveImageRequestSize(profile, "medium", "16:9")).toEqual({ parameter: "aspect_ratio", value: "16:9" });
profile.size.allowCustom = true;
expect(resolveImageRequestSize(profile, "medium", "1:1")?.value).toBe("1:1");
});
test("管理员固定显示三档,用户端隐藏未支持档位,不发送尺寸时隐藏", () => {
const profile = defaultImageCapabilityConfig("grok-image", "grok-imagine-image");
profile.size.allowCustom = true;
const editor = renderToStaticMarkup(<ImageSizePresetsEditor profile={profile} onChange={() => {}} />);
for (const label of ["1K", "2K", "4K"]) expect(editor).toMatch(new RegExp(`<strong[^>]*>${label}</strong>`));
const picker = renderToStaticMarkup(<ImageSizePicker profile={profile} size="16:9" quality="2k" onChange={() => {}} />);
expect(picker).not.toMatch(/<button[^>]*>4K/);
expect(picker).toContain("换算参考");
profile.size.parameter = "none";
expect(renderToStaticMarkup(<ImageSizePicker profile={profile} size="auto" onChange={() => {}} />)).toBe("");
});
test("空档位始终隐藏,允许自定义也不显示;旧尺寸不导致比例区域为空", () => {
for (const protocol of ["openai-image", "gemini-image"]) {
const profile = defaultImageCapabilityConfig(protocol, "test");
profile.size = imageSizeConfigWithPresets(profile, [imagePresetForRatio("1k", "1:1"), imagePresetForRatio("4k", "16:9")]);
for (const allowCustom of [false, true]) {
profile.size.allowCustom = allowCustom;
const picker = renderToStaticMarkup(<ImageSizePicker profile={profile} size={profile.size.parameter === "aspect_ratio" ? "16:9" : "2752x1536"} quality="medium" onChange={() => {}} />);
expect(picker).toMatch(/<button[^>]*>1K/);
expect(picker).toMatch(/<button[^>]*>4K/);
expect(picker).not.toMatch(/<button[^>]*>2K/);
expect(picker).not.toContain("未配置比例");
expect(picker).toContain('title="1:1 · 1024 × 1024"');
expect(picker).not.toMatch(/aria-pressed="true"[^>]*>1K/);
}
}
});
test("仅配置一档时只显示该档;全空时保留自动尺寸与自定义入口", () => {
const profile = defaultImageCapabilityConfig();
profile.size = imageSizeConfigWithPresets(profile, [imagePresetForRatio("4k", "16:9")]);
const picker = renderToStaticMarkup(<ImageSizePicker profile={profile} size="3840x2160" onChange={() => {}} />);
expect(picker).not.toMatch(/<button[^>]*>[12]K/);
expect(picker).toMatch(/aria-pressed="true"[^>]*>4K/);
profile.size = imageSizeConfigWithPresets(profile, []);
profile.size.allowCustom = true;
const empty = renderToStaticMarkup(<ImageSizePicker profile={profile} size="auto" onChange={() => {}} />);
expect(empty).not.toContain('class="image-size-tiers"');
expect(empty).not.toContain('class="image-size-label"');
expect(empty).toContain("自动尺寸");
expect(empty).toContain("自定义比例或尺寸");
});
test("管理员比例直接点选和输入,默认输出不再使用下拉框", () => {
const profile = defaultImageCapabilityConfig();
profile.size = imageSizeConfigWithPresets(profile, [imagePresetForRatio("1k", "16:9")]);
const editor = renderToStaticMarkup(<ImageSizePresetsEditor profile={profile} onChange={() => {}} />);
expect(editor).not.toContain('role="combobox"');
expect(editor).not.toContain("ant-select");
for (const tier of ["1K", "2K", "4K"]) {
expect(editor).toContain(`aria-label="${tier} 自定义比例"`);
expect(editor).toContain(`aria-label="添加 ${tier} 比例"`);
expect(editor).toContain(`aria-label="${tier} 16:9"`);
}
expect(editor).toContain('aria-label="默认输出"');
const readOnly = renderToStaticMarkup(<ImageSizePresetsEditor profile={profile} disabled onChange={() => {}} />);
const buttons = [...readOnly.matchAll(/<button\b[^>]*>/g)];
expect(buttons.length).toBeGreaterThan(24);
expect(buttons.every(([button]) => button.includes('disabled=""'))).toBe(true);
});
test("图片协议尺寸独占整行且先于辅助参数,视频布局不受影响", () => {
const image = renderToStaticMarkup(<ModelCapabilityEditor capability="image" section="protocol" />);
expect(image).toContain("admin-image-protocol-grid");
expect(image).toContain("admin-image-size-card");
expect(image.indexOf("尺寸参数")).toBeLessThan(image.indexOf("输出数量"));
const video = renderToStaticMarkup(<ModelCapabilityEditor capability="video" section="protocol" />);
expect(video).not.toContain("admin-image-protocol-grid");
});
});