fix(canvas): 视频设置 - 按渠道能力隐藏尺寸并联动分辨率宽高

This commit is contained in:
ddCat committed 2026-08-29 11:05:59 +08:00
1 parent 6d77c250c1
commit 4b75504f75
15 files changed
+196 -50

No files matched your search

+6 -2
View File
@@ -532,8 +532,12 @@ func validateVideoCapabilityConfig(value *VideoCapabilityConfig) error {
if err := validateVideoDuration(value.Duration); err != nil { if err := validateVideoDuration(value.Duration); err != nil {
return err return err
} }
if len(value.Ratios) == 0 || strings.TrimSpace(value.DefaultRatio) == "" || !containsCapabilityString(value.Ratios, value.DefaultRatio) { if len(value.Ratios) == 0 {
return BadAuthRequest("请至少配置一个画面比例,并选择默认比例") if strings.TrimSpace(value.DefaultRatio) != "" {
return BadAuthRequest("未配置画面比例时不能设置默认比例")
}
} else if strings.TrimSpace(value.DefaultRatio) == "" || !containsCapabilityString(value.Ratios, value.DefaultRatio) {
return BadAuthRequest("默认画面比例必须属于支持值")
} }
if len(value.Resolutions) == 0 { if len(value.Resolutions) == 0 {
if strings.TrimSpace(value.DefaultResolution) != "" { if strings.TrimSpace(value.DefaultResolution) != "" {
@@ -237,6 +237,25 @@ func TestNormalizeVideoCapabilityAllowsOmittedResolution(t *testing.T) {
} }
} }
func TestNormalizeVideoCapabilityAllowsOmittedRatio(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("autodl-comfyui", "minimax_h3_lightx2v_no_pic").Video
profile.Ratios = nil
profile.DefaultRatio = ""
profile.Resolutions = []string{"480p竖", "480p横"}
profile.DefaultResolution = "480p竖"
result, err := NormalizeModelCapabilityConfig("video", "autodl-comfyui", &ModelCapabilityConfig{Version: 1, Video: profile})
if err != nil {
t.Fatalf("NormalizeModelCapabilityConfig() error = %v", err)
}
if result.Video == nil || len(result.Video.Ratios) != 0 || result.Video.DefaultRatio != "" {
t.Fatalf("normalized video ratios = %#v", result.Video)
}
if err := validateVideoTask(result.Video, canvasGenerationInput{Config: providerConfig{Model: "minimax_h3_lightx2v_no_pic", VideoSeconds: "6", VQuality: "480p竖"}}); err != nil {
t.Fatalf("validateVideoTask() error = %v", err)
}
}
func TestCapabilitySpecFromModelCapabilityConfigProjectsImageSizeOnce(t *testing.T) { func TestCapabilitySpecFromModelCapabilityConfigProjectsImageSizeOnce(t *testing.T) {
config := &ModelCapabilityConfig{ config := &ModelCapabilityConfig{
Version: 1, Version: 1,
@@ -375,9 +375,14 @@ description: 影策已实现功能的手工验证清单与未确认边界
- [x] 前端分辨率规范化、画布选中态、价格匹配与请求映射专项测试通过。 - [x] 前端分辨率规范化、画布选中态、价格匹配与请求映射专项测试通过。
- [x] AutoDL 插件 `1.0.2` 已改用通用 `lower` 并通过协议包测试;宿主仅保留旧 `1.0.1` 清单所需的兼容 shim。 - [x] AutoDL 插件 `1.0.2` 已改用通用 `lower` 并通过协议包测试;宿主仅保留旧 `1.0.1` 清单所需的兼容 shim。
- [x] Manifest 工作流的视频能力改为按 `parameters` 投影:只声明分辨率时不再补画幅能力,也不会继续提交旧的全局 `size`。
- [x] 同时支持分辨率和画幅的渠道按当前比例与分辨率推导只读宽高,例如 `16:9 + 720P = 1280×720`、`16:9 + 1080P = 1920×1080`、`16:9 + 4K = 3840×2160`。
- [x] `web` TypeScript 检查与生产构建通过。 - [x] `web` TypeScript 检查与生产构建通过。
- [x] 后端允许视频能力明确省略画幅,并通过全量 Go 测试;前端能力投影、尺寸计算和画布模型专项测试通过。
- [ ] 在画布选择 `480p竖`、`768p竖`、`480p横`、`768p横`,确认按钮选中态、底部摘要和重新打开后的状态一致。 - [ ] 在画布选择 `480p竖`、`768p竖`、`480p横`、`768p横`,确认按钮选中态、底部摘要和重新打开后的状态一致。
- [ ] 分别提交四个枚举值,确认请求中的 `resolution` 与插件声明一致,且其他标准 `720p`、`1080p` 渠道不受影响。 - [ ] 分别提交四个枚举值,确认请求中的 `resolution` 与插件声明一致,且其他标准 `720p`、`1080p` 渠道不受影响。
- [ ] 使用仅声明 `resolution` 的 AutoDL 工作流,确认画布和创作页不显示画幅/尺寸,生成请求不包含无意义的 `aspectRatio`。
- [ ] 使用同时声明画幅与分辨率的渠道,依次切换 `16:9` 下的 720P、1080P、4K 及 `9:16`,确认宽高展示随选择即时更新且请求仍按渠道协议发送比例与分辨率。
## 画布生成重复提交保护 ## 画布生成重复提交保护
@@ -585,10 +585,10 @@ function buildModelNodeConfig(globalConfig: AiConfig, node: CanvasNodeData, mode
taskWorkflowProvider: "model", taskWorkflowProvider: "model",
model, model,
quality: generationDefaults.quality || globalConfig.quality || defaultConfig.quality, quality: generationDefaults.quality || globalConfig.quality || defaultConfig.quality,
size: generationDefaults.size || globalConfig.size || defaultConfig.size, size: generationDefaults.size ?? globalConfig.size ?? defaultConfig.size,
transparentBackground: generationDefaults.transparentBackground || "false", transparentBackground: generationDefaults.transparentBackground || "false",
videoSeconds: generationDefaults.videoSeconds || normalizeVideoDuration(globalConfig.videoSeconds || defaultConfig.videoSeconds), videoSeconds: generationDefaults.videoSeconds || normalizeVideoDuration(globalConfig.videoSeconds || defaultConfig.videoSeconds),
vquality: generationDefaults.vquality || normalizeVideoResolution(globalConfig.vquality || defaultConfig.vquality), vquality: generationDefaults.vquality ?? normalizeVideoResolution(globalConfig.vquality || defaultConfig.vquality),
videoGenerateAudio: videoProfile?.generateAudio.supported ? generationDefaults.videoGenerateAudio || String(videoProfile.generateAudio.default) : "false", videoGenerateAudio: videoProfile?.generateAudio.supported ? generationDefaults.videoGenerateAudio || String(videoProfile.generateAudio.default) : "false",
videoWatermark: videoProfile?.watermark.supported ? generationDefaults.videoWatermark || String(videoProfile.watermark.default) : "false", videoWatermark: videoProfile?.watermark.supported ? generationDefaults.videoWatermark || String(videoProfile.watermark.default) : "false",
audioVoice: node.metadata?.audioVoice || globalConfig.audioVoice || defaultConfig.audioVoice, audioVoice: node.metadata?.audioVoice || globalConfig.audioVoice || defaultConfig.audioVoice,
@@ -738,10 +738,10 @@ function buildNodeConfig(globalConfig: AiConfig, node: CanvasNodeData, mode: Can
...globalConfig, ...globalConfig,
model, model,
quality: defaults.quality || globalConfig.quality || defaultConfig.quality, quality: defaults.quality || globalConfig.quality || defaultConfig.quality,
size: defaults.size || globalConfig.size || defaultConfig.size, size: defaults.size ?? globalConfig.size ?? defaultConfig.size,
transparentBackground: defaults.transparentBackground || "false", transparentBackground: defaults.transparentBackground || "false",
videoSeconds: defaults.videoSeconds || normalizeVideoDuration(globalConfig.videoSeconds || defaultConfig.videoSeconds), videoSeconds: defaults.videoSeconds || normalizeVideoDuration(globalConfig.videoSeconds || defaultConfig.videoSeconds),
vquality: defaults.vquality || normalizeVideoResolution(globalConfig.vquality || defaultConfig.vquality), vquality: defaults.vquality ?? normalizeVideoResolution(globalConfig.vquality || defaultConfig.vquality),
videoGenerateAudio: defaults.videoGenerateAudio || globalConfig.videoGenerateAudio || defaultConfig.videoGenerateAudio, videoGenerateAudio: defaults.videoGenerateAudio || globalConfig.videoGenerateAudio || defaultConfig.videoGenerateAudio,
videoWatermark: defaults.videoWatermark || globalConfig.videoWatermark || defaultConfig.videoWatermark, videoWatermark: defaults.videoWatermark || globalConfig.videoWatermark || defaultConfig.videoWatermark,
audioVoice: node.metadata?.audioVoice || globalConfig.audioVoice || defaultConfig.audioVoice, audioVoice: node.metadata?.audioVoice || globalConfig.audioVoice || defaultConfig.audioVoice,
@@ -5,7 +5,7 @@ import { Button } from "antd";
import { VideoSettingsPanel, videoResolutionLabel, videoSecondsLabel, videoSizeLabel } from "@/components/video-settings-panel"; import { VideoSettingsPanel, videoResolutionLabel, videoSecondsLabel, videoSizeLabel } from "@/components/video-settings-panel";
import { canvasThemes } from "@/lib/canvas-theme"; import { canvasThemes } from "@/lib/canvas-theme";
import { modelCapabilityConfigFor, resolveVideoResolutionValue } from "@/lib/model-capabilities"; import { modelCapabilityConfigFor, resolveVideoRatioValue, resolveVideoResolutionValue } from "@/lib/model-capabilities";
import { useThemeStore } from "@/stores/use-theme-store"; import { useThemeStore } from "@/stores/use-theme-store";
import type { AiConfig } from "@/stores/use-config-store"; import type { AiConfig } from "@/stores/use-config-store";
@@ -24,10 +24,12 @@ export function CanvasVideoSettingsPopover({ config, onConfigChange, buttonClass
const [buttonRect, setButtonRect] = useState<DOMRect | null>(null); const [buttonRect, setButtonRect] = useState<DOMRect | null>(null);
const videoProfile = modelCapabilityConfigFor(config, config.model).video; const videoProfile = modelCapabilityConfigFor(config, config.model).video;
const resolutionSupported = Boolean(videoProfile?.resolutions.length); const resolutionSupported = Boolean(videoProfile?.resolutions.length);
const sizeSupported = Boolean(videoProfile?.ratios.length);
const resolution = videoProfile ? resolveVideoResolutionValue(videoProfile, config.vquality) : ""; const resolution = videoProfile ? resolveVideoResolutionValue(videoProfile, config.vquality) : "";
const size = videoProfile ? resolveVideoRatioValue(videoProfile, config.size) : "";
const summary = [ const summary = [
...(resolutionSupported ? [videoResolutionLabel(resolution)] : []), ...(resolutionSupported ? [videoResolutionLabel(resolution)] : []),
videoSizeLabel(config.size), ...(sizeSupported ? [videoSizeLabel(size)] : []),
videoSecondsLabel(config.videoSeconds), videoSecondsLabel(config.videoSeconds),
].join(" · "); ].join(" · ");
+16 -31
View File
@@ -4,8 +4,8 @@ import { Switch } from "antd";
import { ImageSettingsTheme } from "@/components/image-settings-panel"; import { ImageSettingsTheme } from "@/components/image-settings-panel";
import { boolConfig, isSeedanceFastModel, isSeedanceVideoConfig, normalizeSeedanceDuration, normalizeSeedanceRatio, normalizeSeedanceResolution, seedanceRatioOptions } from "@/lib/seedance-video"; import { boolConfig, isSeedanceFastModel, isSeedanceVideoConfig, normalizeSeedanceDuration, normalizeSeedanceRatio, normalizeSeedanceResolution, seedanceRatioOptions } from "@/lib/seedance-video";
import { type CanvasTheme } from "@/lib/canvas-theme"; import { type CanvasTheme } from "@/lib/canvas-theme";
import { formatVideoResolutionLabel, normalizeVideoDuration, videoResolutionComparisonKey, VIDEO_DURATION_MIN } from "@/lib/video-generation-options"; import { formatVideoResolutionLabel, normalizeVideoDuration, videoDimensionsForRatioAndResolution, videoResolutionComparisonKey, VIDEO_DURATION_MIN } from "@/lib/video-generation-options";
import { modelCapabilityConfigFor, resolveVideoResolutionValue, videoDurationOptions, type VideoCapabilityConfig } from "@/lib/model-capabilities"; import { modelCapabilityConfigFor, resolveVideoRatioValue, resolveVideoResolutionValue, videoDurationOptions, type VideoCapabilityConfig } from "@/lib/model-capabilities";
import { modelOptionName, resolveModelChannel, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store"; import { modelOptionName, resolveModelChannel, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store";
const sizeOptions = [ const sizeOptions = [
@@ -36,16 +36,13 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
} }
const seconds = normalizeVideoDuration(config.videoSeconds); const seconds = normalizeVideoDuration(config.videoSeconds);
const size = normalizeVideoSizeValue(config.size);
const dimensions = readSizeDimensions(size);
const resolution = resolveVideoResolutionValue(profile, config.vquality); const resolution = resolveVideoResolutionValue(profile, config.vquality);
const ratio = resolveVideoRatioValue(profile, config.size);
const dimensions = videoDimensionsForRatioAndResolution(ratio, resolution);
const sizeSupported = profile.ratios.length > 0;
const configuredResolutions = profile.resolutions.map((value) => ({ value, label: formatVideoResolutionLabel(value) })); const configuredResolutions = profile.resolutions.map((value) => ({ value, label: formatVideoResolutionLabel(value) }));
const generateAudio = boolConfig(config.videoGenerateAudio, profile.generateAudio.default); const generateAudio = boolConfig(config.videoGenerateAudio, profile.generateAudio.default);
const watermark = boolConfig(config.videoWatermark, profile.watermark.default); const watermark = boolConfig(config.videoWatermark, profile.watermark.default);
const updateDimension = (key: "width" | "height", value: number | null) => {
const next = Math.max(1, Math.floor(value || dimensions[key] || 720));
onConfigChange("size", `${key === "width" ? next : dimensions.width}x${key === "height" ? next : dimensions.height}`);
};
return ( return (
<ImageSettingsTheme theme={theme}> <ImageSettingsTheme theme={theme}>
@@ -60,19 +57,19 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
))} ))}
</div> </div>
</SettingGroup> : null} </SettingGroup> : null}
<SettingGroup title="尺寸" color={theme.node.muted}> {sizeSupported ? <SettingGroup title="尺寸" color={theme.node.muted}>
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-1.5"> {dimensions ? <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-1.5">
<DimensionInput prefix="W" value={dimensions.width} disabled={size === "auto"} theme={theme} onChange={(value) => updateDimension("width", value)} /> <DimensionValue prefix="W" value={dimensions.width} theme={theme} />
<span className="text-xs opacity-45">×</span> <span className="text-xs opacity-45">×</span>
<DimensionInput prefix="H" value={dimensions.height} disabled={size === "auto"} theme={theme} onChange={(value) => updateDimension("height", value)} /> <DimensionValue prefix="H" value={dimensions.height} theme={theme} />
</div> </div> : null}
<div className="grid grid-cols-3 gap-1.5"> <div className="grid grid-cols-3 gap-1.5">
{profile.ratios.map((value) => ( {profile.ratios.map((value) => (
<button <button
key={value} key={value}
type="button" type="button"
className="flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-md px-1 text-[var(--fs-label)] font-medium transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1" className="flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-md px-1 text-[var(--fs-label)] font-medium transition-colors hover:brightness-110 focus-visible:outline focus-visible:outline-1 focus-visible:outline-offset-1"
style={{ background: normalizeRatioValue(config.size) === value ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }} style={{ background: ratio === value ? theme.toolbar.activeBg : "transparent", color: theme.node.text, outlineColor: theme.node.muted }}
onMouseDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()}
onClick={() => onConfigChange("size", value)} onClick={() => onConfigChange("size", value)}
> >
@@ -81,7 +78,7 @@ export function VideoSettingsPanel({ config, onConfigChange, theme, showTitle =
</button> </button>
))} ))}
</div> </div>
</SettingGroup> </SettingGroup> : null}
<SettingGroup title="秒数" color={theme.node.muted}> <SettingGroup title="秒数" color={theme.node.muted}>
<VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} disabled={(value) => !hasPriceTierForVideoSelection(priceTiers, resolution, value)} onChange={(value) => onConfigChange("videoSeconds", String(value))} /> <VideoDurationControl profile={profile} value={Number(seconds)} theme={theme} disabled={(value) => !hasPriceTierForVideoSelection(priceTiers, resolution, value)} onChange={(value) => onConfigChange("videoSeconds", String(value))} />
</SettingGroup> </SettingGroup>
@@ -224,14 +221,14 @@ function SettingGroup({ title, color, children }: { title: string; color: string
); );
} }
function DimensionInput({ prefix, value, disabled, theme, onChange }: { prefix: string; value: number; disabled: boolean; theme: CanvasTheme; onChange: (value: number | null) => void }) { function DimensionValue({ prefix, value, theme }: { prefix: string; value: number; theme: CanvasTheme }) {
return ( return (
<label className="flex h-8 overflow-hidden rounded-md text-[var(--fs-label)]" style={{ background: theme.toolbar.itemHover, color: theme.node.text, opacity: disabled ? 0.55 : 1 }}> <div className="flex h-8 overflow-hidden rounded-md text-[var(--fs-label)]" style={{ background: theme.toolbar.itemHover, color: theme.node.text }}>
<span className="grid w-7 place-items-center" style={{ color: theme.node.muted }}> <span className="grid w-7 place-items-center" style={{ color: theme.node.muted }}>
{prefix} {prefix}
</span> </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" value={value || ""} onChange={(event) => onChange(Number(event.target.value) || null)} onMouseDown={(event) => event.stopPropagation()} /> <span className="min-w-0 flex-1 px-2 leading-8 tabular-nums">{value}</span>
</label> </div>
); );
} }
@@ -365,15 +362,3 @@ function SwitchRow({ label, checked, theme, onChange }: { label: string; checked
</div> </div>
); );
} }
function readSizeDimensions(size: string) {
if (size === "auto") return { width: 0, height: 0 };
const match = size.match(/^(\d+)x(\d+)$/);
return { width: Number(match?.[1]) || 1280, height: Number(match?.[2]) || 720 };
}
function normalizeRatioValue(value: string) {
const match = String(value || "").match(/^(\d+(?:\.\d+)?)x(\d+(?:\.\d+)?)$/);
if (!match) return value;
return `${match[1]}:${match[2]}`;
}
@@ -498,10 +498,10 @@ export function buildGenerationConfig(config: AiConfig, node: CanvasNodeData | u
comfyBridge, comfyBridge,
model, model,
quality: generationDefaults.quality || requestedConfig.quality, quality: generationDefaults.quality || requestedConfig.quality,
size: generationDefaults.size || requestedConfig.size, size: generationDefaults.size ?? requestedConfig.size,
transparentBackground: generationDefaults.transparentBackground || (requestedConfig.transparentBackground === "true" ? "true" : "false"), transparentBackground: generationDefaults.transparentBackground || (requestedConfig.transparentBackground === "true" ? "true" : "false"),
videoSeconds: generationDefaults.videoSeconds || requestedConfig.videoSeconds, videoSeconds: generationDefaults.videoSeconds || requestedConfig.videoSeconds,
vquality: generationDefaults.vquality || requestedConfig.vquality, vquality: generationDefaults.vquality ?? requestedConfig.vquality,
videoGenerateAudio: generationDefaults.videoGenerateAudio || requestedConfig.videoGenerateAudio, videoGenerateAudio: generationDefaults.videoGenerateAudio || requestedConfig.videoGenerateAudio,
videoWatermark: generationDefaults.videoWatermark || requestedConfig.videoWatermark, videoWatermark: generationDefaults.videoWatermark || requestedConfig.videoWatermark,
videoArkPrivateAssetUpload: requestedConfig.videoArkPrivateAssetUpload, videoArkPrivateAssetUpload: requestedConfig.videoArkPrivateAssetUpload,
+22 -2
View File
@@ -1,4 +1,4 @@
import type { ModelProtocol } from "@/lib/model-protocols"; import type { ModelProtocol, ModelProtocolWorkflow } from "@/lib/model-protocols";
export type ModelCapabilityConfig = { export type ModelCapabilityConfig = {
version: number; version: number;
@@ -335,6 +335,22 @@ export function defaultModelCapabilityConfig(protocol?: ModelProtocol, model = "
return { version: 1, text, image: defaultImageCapabilityConfig(protocol, model), video }; return { version: 1, text, image: defaultImageCapabilityConfig(protocol, model), video };
} }
export function pluginWorkflowCapabilityConfig(protocol: ModelProtocol, workflow: ModelProtocolWorkflow): ModelCapabilityConfig | undefined {
if (workflow.capability !== "image" && workflow.capability !== "video") return undefined;
const fallback = defaultModelCapabilityConfig(protocol, workflow.id);
const fields: WorkflowVideoFieldLike[] = workflow.parameters.map((parameter) => ({
fieldName: parameter.name,
source: parameter.mapping,
fieldType: parameter.type,
options: parameter.values,
defaultValue: workflow.defaults?.[parameter.name],
}));
if (workflow.capability === "image") {
return { ...fallback, image: workflowImageCapabilityConfig(fields, fallback.image!) };
}
return { ...fallback, video: workflowVideoCapabilityConfig(fields, fallback.video!) };
}
export function modelCapabilityConfigFor(config: { channels: Array<{ id: string; models: string[]; modelCosts?: Array<{ model: string; capabilityConfig?: ModelCapabilityConfig; protocol?: ModelProtocol }> }> }, model: string) { export function modelCapabilityConfigFor(config: { channels: Array<{ id: string; models: string[]; modelCosts?: Array<{ model: string; capabilityConfig?: ModelCapabilityConfig; protocol?: ModelProtocol }> }> }, model: string) {
const separator = model.indexOf("::"); const separator = model.indexOf("::");
const channelId = separator >= 0 ? model.slice(0, separator) : ""; const channelId = separator >= 0 ? model.slice(0, separator) : "";
@@ -900,12 +916,16 @@ export function imageSizeRequest(profile: ImageCapabilityConfig, value?: string)
export function normalizeVideoValue(profile: VideoCapabilityConfig, value: { seconds?: string; ratio?: string; resolution?: string }) { export function normalizeVideoValue(profile: VideoCapabilityConfig, value: { seconds?: string; ratio?: string; resolution?: string }) {
const duration = profile.duration.selection === "enum" ? ((profile.duration.values || []).includes(Number(value.seconds)) ? Number(value.seconds) : profile.duration.default) : normalizeRangeDuration(profile, Number(value.seconds)); const duration = profile.duration.selection === "enum" ? ((profile.duration.values || []).includes(Number(value.seconds)) ? Number(value.seconds) : profile.duration.default) : normalizeRangeDuration(profile, Number(value.seconds));
const ratio = profile.ratios.includes(value.ratio || "") ? value.ratio! : profile.defaultRatio; const ratio = resolveVideoRatioValue(profile, value.ratio);
// 前端状态历史上保存过 `720`,而能力配置和供应商通常使用 `720p`;统一按能力中的原始值返回,避免被误判为不支持。 // 前端状态历史上保存过 `720`,而能力配置和供应商通常使用 `720p`;统一按能力中的原始值返回,避免被误判为不支持。
const resolution = resolveVideoResolutionValue(profile, value.resolution); const resolution = resolveVideoResolutionValue(profile, value.resolution);
return { seconds: String(duration), ratio, resolution }; return { seconds: String(duration), ratio, resolution };
} }
export function resolveVideoRatioValue(profile: VideoCapabilityConfig, value: string | undefined) {
return profile.ratios.includes(value || "") ? value! : profile.defaultRatio || profile.ratios[0] || "";
}
export function resolveVideoResolutionValue(profile: VideoCapabilityConfig, value: string | undefined) { export function resolveVideoResolutionValue(profile: VideoCapabilityConfig, value: string | undefined) {
return videoResolutionRequest(profile, value) || profile.defaultResolution || profile.resolutions[0] || ""; return videoResolutionRequest(profile, value) || profile.defaultResolution || profile.resolutions[0] || "";
} }
+26
View File
@@ -38,3 +38,29 @@ export function formatVideoResolutionLabel(value: string | number | undefined) {
if (/^\d+$/.test(normalized)) return `${normalized}P`; if (/^\d+$/.test(normalized)) return `${normalized}P`;
return normalized.replace(/^(\d+)p/i, "$1P"); return normalized.replace(/^(\d+)p/i, "$1P");
} }
export function videoDimensionsForRatioAndResolution(ratio: string | undefined, resolution: string | number | undefined) {
const ratioMatch = String(ratio || "")
.trim()
.toLowerCase()
.replace("×", "x")
.match(/^(\d+(?:\.\d+)?)(?::|x)(\d+(?:\.\d+)?)$/);
if (!ratioMatch) return undefined;
const ratioWidth = Number(ratioMatch[1]);
const ratioHeight = Number(ratioMatch[2]);
if (!Number.isFinite(ratioWidth) || !Number.isFinite(ratioHeight) || ratioWidth <= 0 || ratioHeight <= 0) return undefined;
const normalizedResolution = normalizeVideoResolution(resolution);
const resolutionMatch = normalizedResolution.match(/^(\d+)(?:p)?/i);
const shortEdge = Number(resolutionMatch?.[1]);
if (!Number.isFinite(shortEdge) || shortEdge <= 0) return undefined;
const aspect = ratioWidth / ratioHeight;
if (aspect >= 1) return { width: evenDimension(shortEdge * aspect), height: shortEdge };
return { width: shortEdge, height: evenDimension(shortEdge / aspect) };
}
function evenDimension(value: number) {
return Math.max(2, Math.round(value / 2) * 2);
}
+4 -3
View File
@@ -612,7 +612,7 @@ export default function CreatePage() {
...(mode === "image" ...(mode === "image"
? { size: normalizedImage?.size || ratio, quality: normalizedImage?.quality || quality, count: normalizedImage?.count || count, videoSeconds: config.videoSeconds } ? { size: normalizedImage?.size || ratio, quality: normalizedImage?.quality || quality, count: normalizedImage?.count || count, videoSeconds: config.videoSeconds }
: mode === "video" : mode === "video"
? { size: normalizedVideo?.ratio || ratio, videoSeconds: normalizedVideo?.seconds || seconds, vquality: (normalizedVideo?.resolution || videoQuality).replace(/p$/i, "") } ? { size: normalizedVideo?.ratio ?? ratio, videoSeconds: normalizedVideo?.seconds || seconds, vquality: (normalizedVideo?.resolution ?? videoQuality).replace(/p$/i, "") }
: {}), : {}),
}; };
try { try {
@@ -1519,9 +1519,10 @@ function GenerationSettingsMenu(props: ComposerProps) {
...(props.imageProfile.quality.supported ? [qualityLabel] : []), ...(props.imageProfile.quality.supported ? [qualityLabel] : []),
...(props.imageProfile.maxOutputs > 1 ? [props.count] : []), ...(props.imageProfile.maxOutputs > 1 ? [props.count] : []),
].join(" · "); ].join(" · ");
const summary = props.mode === "video" ? [props.ratio, ...(videoResolutionSupported ? [videoResolutionLabel(props.videoQuality)] : [])].join(" · ") : imageSummary; 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"> const panel = <div className="creation-parameter-menu">
{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} {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 === "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) : <> {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} {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 ? <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}
@@ -8,7 +8,7 @@ import { mergeFetchedChannelModelCosts } from "@/lib/channel-model-catalog";
import { desktopLocalChannelFormState, desktopLocalChannelPayloadValue, DESKTOP_LOCAL_CHANNEL_EXAMPLE_BASE_URL } from "@/lib/desktop-local-channel"; import { desktopLocalChannelFormState, desktopLocalChannelPayloadValue, DESKTOP_LOCAL_CHANNEL_EXAMPLE_BASE_URL } from "@/lib/desktop-local-channel";
import { fetchChannelModels } from "@/services/api/image"; import { fetchChannelModels } from "@/services/api/image";
import { fetchPluginProviderCatalog } from "@/services/api/plugin-catalog"; import { fetchPluginProviderCatalog } from "@/services/api/plugin-catalog";
import { defaultModelCapabilityConfig } from "@/lib/model-capabilities"; import { pluginWorkflowCapabilityConfig } from "@/lib/model-capabilities";
import type { ModelProtocolDefinition } from "@/lib/model-protocols"; import type { ModelProtocolDefinition } from "@/lib/model-protocols";
import { import {
createModelChannel, createModelChannel,
@@ -84,7 +84,7 @@ export function ChannelSettingsPane({ onOpenModels, onOpenRunningHub, onOpenComf
protocol: provider.value, protocol: provider.value,
billingMode: "fixed_request" as const, billingMode: "fixed_request" as const,
unitPriceMicrocredits: 0, unitPriceMicrocredits: 0,
capabilityConfig: workflow.capability === "image" || workflow.capability === "video" ? defaultModelCapabilityConfig(provider.value, workflow.id) : undefined, capabilityConfig: pluginWorkflowCapabilityConfig(provider.value, workflow),
defaultOptions: workflow.defaults, defaultOptions: workflow.defaults,
})) }))
: channel.modelCosts; : channel.modelCosts;
+25
View File
@@ -151,6 +151,31 @@ describe("逻辑模型选择", () => {
expect(defaults.size).toBe("16:9"); expect(defaults.size).toBe("16:9");
}); });
test("不支持画幅的视频模型不会继续提交旧的全局尺寸", () => {
const model = "autodl-channel::minimax_h3_lightx2v_no_pic";
const profile = defaultModelCapabilityConfig("autodl-comfyui", "minimax_h3_lightx2v_no_pic");
profile.video!.ratios = [];
profile.video!.defaultRatio = "";
profile.video!.resolutions = ["480p竖", "480p横"];
profile.video!.defaultResolution = "480p竖";
const config: AiConfig = {
...defaultConfig,
size: "16:9",
vquality: "720",
channels: [{ id: "autodl-channel", name: "AutoDL", baseUrl: "https://autodl.art", apiKey: "system", apiFormat: "openai", scope: "system", models: ["minimax_h3_lightx2v_no_pic"], modelCosts: [{ model: "minimax_h3_lightx2v_no_pic", capability: "video", protocol: "autodl-comfyui", billingMode: "fixed_request", unitPriceMicrocredits: 1, capabilityConfig: profile }] }],
models: [model],
videoModels: [model],
videoModel: model,
model,
};
const videoNode = { ...node("video", CanvasNodeType.Video), metadata: { model, generationMode: "video" as const } };
const generationConfig = buildGenerationConfig(config, videoNode, "video");
expect(generationConfig.size).toBe("");
expect(generationConfig.vquality).toBe("480p竖");
});
test("后台标注的视频模型不因内部标识缺少视频关键词而回退", () => { test("后台标注的视频模型不因内部标识缺少视频关键词而回退", () => {
const config = policyConfig(); const config = policyConfig();
const selectedModel = config.videoModels[0]!; const selectedModel = config.videoModels[0]!;
+51 -1
View File
@@ -8,7 +8,7 @@ import { CanvasVideoSettingsPopover } from "../src/components/canvas/canvas-vide
import { VideoSettingsPanel } from "../src/components/video-settings-panel"; import { VideoSettingsPanel } from "../src/components/video-settings-panel";
import { canvasThemes } from "../src/lib/canvas-theme"; import { canvasThemes } from "../src/lib/canvas-theme";
import { mergeFetchedChannelModelCosts, type ChannelModelCatalogItem } from "../src/lib/channel-model-catalog"; import { mergeFetchedChannelModelCosts, type ChannelModelCatalogItem } from "../src/lib/channel-model-catalog";
import { defaultModelCapabilityConfig } from "../src/lib/model-capabilities"; import { defaultModelCapabilityConfig, pluginWorkflowCapabilityConfig } from "../src/lib/model-capabilities";
import { ChannelModelSettings } from "../src/pages/settings/channel-video-pricing"; import { ChannelModelSettings } from "../src/pages/settings/channel-video-pricing";
import { fetchChannelModels } from "../src/services/api/image"; import { fetchChannelModels } from "../src/services/api/image";
import { createVideoGenerationTask } from "../src/services/api/video"; import { createVideoGenerationTask } from "../src/services/api/video";
@@ -62,6 +62,27 @@ function formEntries(body: unknown) {
} }
describe("public channel model catalog", () => { describe("public channel model catalog", () => {
test("projects Manifest video workflow parameters without inventing a size capability", () => {
const profile = pluginWorkflowCapabilityConfig("autodl-comfyui", {
id: "minimax_h3_lightx2v_no_pic",
label: "MiniMax H3 文生视频",
providerId: "autodl-comfyui",
capability: "video",
parameters: [
{ name: "prompt", type: "string", required: true, mapping: "prompt" },
{ name: "duration", type: "integer", mapping: "duration" },
{ name: "resolution", type: "string", mapping: "resolution", values: ["480p竖", "480p横"] },
],
defaults: { duration: 5, resolution: "480p竖" },
})!.video!;
expect(profile.ratios).toEqual([]);
expect(profile.defaultRatio).toBe("");
expect(profile.resolutions).toEqual(["480p竖", "480p横"]);
expect(profile.defaultResolution).toBe("480p竖");
expect(profile.duration).toEqual({ selection: "enum", values: [5], default: 5 });
});
test("preserves six public capabilities without expanding compatibility IDs", async () => { test("preserves six public capabilities without expanding compatibility IDs", async () => {
axios.post = (async () => ({ axios.post = (async () => ({
data: { data: {
@@ -243,6 +264,35 @@ describe("public channel model catalog", () => {
expect(html).not.toContain("720P"); expect(html).not.toContain("720P");
}); });
test("does not show size controls when the video capability declares no ratios", () => {
const config = configForCatalog([omniCatalog], { videoSeconds: "10", size: "16:9", vquality: "1080" });
const profile = config.channels[0]!.modelCosts![0]!.capabilityConfig!.video!;
profile.ratios = [];
profile.defaultRatio = "";
profile.resolutions = ["1080p"];
profile.defaultResolution = "1080p";
const summaryHtml = renderToStaticMarkup(React.createElement(CanvasVideoSettingsPopover, { config, onConfigChange: () => undefined }));
const panelHtml = renderToStaticMarkup(React.createElement(VideoSettingsPanel, { config, onConfigChange: () => undefined, theme: canvasThemes.dark }));
expect(summaryHtml).toContain("1080P · 10s");
expect(summaryHtml).not.toContain("16:9");
expect(panelHtml).not.toContain("尺寸");
});
test("shows dimensions derived from the selected video resolution and ratio", () => {
const config = configForCatalog([omniCatalog], { videoSeconds: "10", size: "16:9", vquality: "1080" });
const profile = config.channels[0]!.modelCosts![0]!.capabilityConfig!.video!;
profile.resolutions = ["720p", "1080p", "2160p"];
profile.defaultResolution = "720p";
const panelHtml = renderToStaticMarkup(React.createElement(VideoSettingsPanel, { config, onConfigChange: () => undefined, theme: canvasThemes.dark }));
expect(panelHtml).toContain("1920");
expect(panelHtml).toContain("1080");
expect(panelHtml).not.toContain("1280");
});
test("shows the public display name in channel model settings instead of only the internal ID", () => { test("shows the public display name in channel model settings instead of only the internal ID", () => {
const config = configForCatalog([omniCatalog]); const config = configForCatalog([omniCatalog]);
+10 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test"; import { describe, expect, test } from "bun:test";
import { defaultModelCapabilityConfig } from "../src/lib/model-capabilities"; import { defaultModelCapabilityConfig } from "../src/lib/model-capabilities";
import { formatVideoResolutionLabel, normalizeVideoResolution, videoResolutionComparisonKey, VIDEO_RESOLUTION_CAPABILITY_OPTIONS, VIDEO_RESOLUTION_OPTIONS } from "../src/lib/video-generation-options"; import { formatVideoResolutionLabel, normalizeVideoResolution, videoDimensionsForRatioAndResolution, videoResolutionComparisonKey, VIDEO_RESOLUTION_CAPABILITY_OPTIONS, VIDEO_RESOLUTION_OPTIONS } from "../src/lib/video-generation-options";
describe("video generation resolution options", () => { describe("video generation resolution options", () => {
test("统一档位包含 1440P 与 4K,并识别常见别名", () => { test("统一档位包含 1440P 与 4K,并识别常见别名", () => {
@@ -20,6 +20,15 @@ describe("video generation resolution options", () => {
expect(formatVideoResolutionLabel("768p竖")).toBe("768P竖"); expect(formatVideoResolutionLabel("768p竖")).toBe("768P竖");
}); });
test("根据当前比例和分辨率推导视频尺寸", () => {
expect(videoDimensionsForRatioAndResolution("16:9", "720p")).toEqual({ width: 1280, height: 720 });
expect(videoDimensionsForRatioAndResolution("16:9", "1080P")).toEqual({ width: 1920, height: 1080 });
expect(videoDimensionsForRatioAndResolution("16:9", "4K")).toEqual({ width: 3840, height: 2160 });
expect(videoDimensionsForRatioAndResolution("9:16", "1080p")).toEqual({ width: 1080, height: 1920 });
expect(videoDimensionsForRatioAndResolution("1:1", "1440p")).toEqual({ width: 1440, height: 1440 });
expect(videoDimensionsForRatioAndResolution("adaptive", "1080p")).toBeUndefined();
});
test("按协议限制实际可选档位", () => { test("按协议限制实际可选档位", () => {
expect(defaultModelCapabilityConfig("newapi-channel-2").video?.resolutions).toEqual(["480p", "720p", "1080p", "1440p", "2160p"]); expect(defaultModelCapabilityConfig("newapi-channel-2").video?.resolutions).toEqual(["480p", "720p", "1080p", "1440p", "2160p"]);
expect(defaultModelCapabilityConfig("volcengine-ark-video").video?.resolutions).toEqual(["480p", "720p", "1080p"]); expect(defaultModelCapabilityConfig("volcengine-ark-video").video?.resolutions).toEqual(["480p", "720p", "1080p"]);