Compare commits

...

12 Commits

Author SHA1 Message Date
Your Name
a8e62962b8 chore: add ruxa image model verification script 2026-06-08 18:22:41 +08:00
Your Name
afd1f84789 feat: add multi-select add-to-canvas UI for3D world/model history
- Add '批量添加到画布' panel in the right-side assets panel, with
 全选可添加 toggle and '添加到画布 (N)' action button.
- Add per-card '加画布 / 已选' toggle button (left of download icon),
 visible when task.status is success. Selected cards show yellow ring.
- Wire selectedAddTaskIds Set state, addableTasks/selectedAddTasks memos,
 handleToggleAddSelection / handleSelectAllForAdd / handleBatchImportToCanvas
 handlers, and a useEffect to prune stale selections when visible
 history changes.
- handleBatchImportToCanvas calls addNodesBulk (added in 3ca5859) which
 loops addNode and reuses its ring-scan auto-overlap logic, so multiple
 world3d/model3d nodes land at distinct canvas positions instead of
 stacking on the viewport center.
2026-06-08 16:56:57 +08:00
Your Name
c9fe549e86 feat: add multi-select add-to-canvas UI for3D world/model history
- Add '批量添加到画布' panel in the right-side assets panel, with
 全选可添加 toggle and '添加到画布 (N)' action button.
- Add per-card '加画布 / 已选' toggle button (right-of-download icon),
 visible when task.status is success. Selected cards show yellow ring.
- Wire selectedAddTaskIds Set state, addableTasks/selectedAddTasks memos,
 handleToggleAddSelection / handleSelectAllForAdd / handleBatchImportToCanvas
 handlers, and a useEffect to prune stale selections when the visible
 history changes.
- handleBatchImportToCanvas calls addNodesBulk (added in store commit)
 which loops addNode and reuses its ring-scan auto-overlap logic, so
 multiple world3d/model3d nodes land at distinct canvas positions instead
 of stacking on the viewport center.
2026-06-08 16:26:36 +08:00
Your Name
fdb5304111 merge: integrate remote changes from origin/codex/main-force-detail-generation 2026-06-08 15:45:51 +08:00
Your Name
3ca5859e26 feat: support multi-select add-to-canvas for3D world/model history
- Extend canvas store addNode's auto-overlap avoidance (ring-scan) to all
 node types, not just 'image'. Previously, repeated import-to-canvas for
 world3d/model3d nodes stacked them on the same viewport center
 coordinate, making them appear locked and impossible to drag apart.
- Add addNodesBulk helper that loops addNode and reuses its avoidance
 logic, suitable for batch-importing multiple history records.
- Wire selectedAddTaskIds state, addableTasks/selectedAddTasks memos,
 toggle/selectAll handlers, and prepare handleBatchImportToCanvas in
 the3D canvas page so future UI can hand off bulk import to the store.
2026-06-08 15:44:27 +08:00
Your Name
c825618398 fix ruxa image resolution mapping 2026-06-06 16:35:45 +08:00
Your Name
528968d74d feat: add watermark removal to detail results 2026-06-05 17:58:22 +08:00
Your Name
5b328355ea feat: configure selected image toolbar density 2026-06-04 17:08:01 +08:00
Your Name
2b82d57f73 feat: configure selected image toolbar density 2026-06-04 17:06:52 +08:00
Your Name
21209894aa fix: compact canvas image tools 2026-06-04 14:09:06 +08:00
Your Name
2090dbd582 fix: compact canvas image tools 2026-06-04 14:02:05 +08:00
Your Name
456c498c32 feat: add canvas ai wash quick panel 2026-06-04 13:09:42 +08:00
17 changed files with 1366 additions and 453 deletions

View File

@ -192,6 +192,8 @@ import {
type CanvasToolbarConfig,
type CanvasToolbarItemKey,
DEFAULT_CANVAS_TOOLBAR_ITEMS,
MAX_SELECTED_IMAGE_INLINE_ACTION_COUNT,
MIN_SELECTED_IMAGE_INLINE_ACTION_COUNT,
defaultCanvasToolbarConfig,
getDefaultCanvasToolbarItem,
normalizeCanvasToolbarConfig,
@ -3691,6 +3693,7 @@ export function AdminSettingsClient() {
return {
...prev,
canvasToolbarConfig: {
...normalized,
items: {
...normalized.items,
[key]: {
@ -12468,6 +12471,54 @@ export function AdminSettingsClient() {
恢复全部默认
</Button>
</div>
<div className="flex flex-col gap-3 rounded-lg border bg-background/60 p-3 md:flex-row md:items-center md:justify-between">
<div className="space-y-1">
<Label
className="font-medium text-sm"
htmlFor="selectedImageInlineActionCount"
>
选中图片一级按钮数量
</Label>
<div className="text-muted-foreground text-xs">
控制画布中选中图片后,快捷弹窗主条直接显示几个功能按钮;超出的功能自动收进“更多”菜单。
</div>
</div>
<Input
className="w-28"
id="selectedImageInlineActionCount"
max={MAX_SELECTED_IMAGE_INLINE_ACTION_COUNT}
min={MIN_SELECTED_IMAGE_INLINE_ACTION_COUNT}
onChange={(event) => {
const normalized =
normalizeCanvasToolbarConfig(
siteSettings.canvasToolbarConfig
);
const parsed = Number(event.target.value);
const nextValue = Number.isFinite(parsed)
? Math.min(
MAX_SELECTED_IMAGE_INLINE_ACTION_COUNT,
Math.max(
MIN_SELECTED_IMAGE_INLINE_ACTION_COUNT,
Math.round(parsed)
)
)
: normalized.selectedImageInlineActionCount;
setSiteSettings({
...siteSettings,
canvasToolbarConfig: {
...normalized,
selectedImageInlineActionCount: nextValue,
},
});
}}
type="number"
value={
normalizeCanvasToolbarConfig(
siteSettings.canvasToolbarConfig
).selectedImageInlineActionCount
}
/>
</div>
{Array.from(
new Set(
DEFAULT_CANVAS_TOOLBAR_ITEMS.map(

View File

@ -205,6 +205,7 @@ export async function generateImageWithFailoverCandidate(params: {
const candidateResult = await (candidateLanguageModel as any).doGenerate({
messages: candidateMessages,
imageParams: imageParams || fallbackImageParams,
imageGenConfig: candidate.model.imageGenConfig || null,
modelDisplayName: candidate.model.displayName,
overrideModelId: candidate.model.modelId,
});

View File

@ -410,6 +410,7 @@ async function replayAssistantMessagesForDuplicateRequest({
}
type ChatImageParams = NonNullable<PostRequestBody["imageParams"]>;
type ChatImageSize = NonNullable<ChatImageParams["imageSize"]>;
type AgentRecommendedImageParams = {
aspectRatio?: string;
imageSize?: string;
@ -444,6 +445,14 @@ type AgentVideoPlan = {
recommendedVideoParams?: AgentRecommendedVideoParams;
};
function normalizeChatImageSize(value?: string | null): ChatImageSize | undefined {
const normalized = String(value || "").trim().toUpperCase();
if (normalized === "1K" || normalized === "2K" || normalized === "4K") {
return normalized;
}
return undefined;
}
function hasUserCustomizedImageParams(params?: PostRequestBody["imageParams"]): boolean {
if (!params) return false;
const customizedAspectRatio =
@ -484,7 +493,8 @@ function mergeImageParamsWithAgentRecommendation(params: {
if (!hasUserCustomSettings) {
if (recommended.aspectRatio) merged.aspectRatio = recommended.aspectRatio;
if (recommended.imageSize) merged.imageSize = recommended.imageSize;
const recommendedImageSize = normalizeChatImageSize(recommended.imageSize);
if (recommendedImageSize) merged.imageSize = recommendedImageSize;
if (typeof recommended.imageCount === "number") merged.imageCount = recommended.imageCount;
}
@ -2038,12 +2048,19 @@ export async function POST(request: Request) {
imageSize: smartAutoDetectedIntent === "image_edit" ? "4K" : "2K",
imageCount: 1,
} as const;
const normalizedEffectiveImageSize = normalizeChatImageSize(effectiveImageParams?.imageSize);
const effectiveImageGenerationParams = {
...(effectiveImageParams || {}),
aspectRatio: effectiveImageParams?.aspectRatio || defaultImageQualityParams.aspectRatio,
imageSize: normalizedEffectiveImageSize || defaultImageQualityParams.imageSize,
imageCount: effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount,
};
if (shouldApplyAgentImageParams) {
chatApiLogger.info("[Smart Auto Mode] 🎯 Effective image params:", {
incoming: requestBody.imageParams,
recommended: smartAutoRecommendedImageParams,
merged: effectiveImageParams,
merged: effectiveImageGenerationParams,
hasUserCustomImageParams,
});
}
@ -3551,7 +3568,7 @@ export async function POST(request: Request) {
}
let finalImage = firstImage;
let finalImageSizeLabel = resolvedImageSize;
let finalImageSizeLabel: string = resolvedImageSize;
try {
const normalizedImage = await normalizeReplacementResultImage({
generatedImageUrl: firstImage.originalUrl,
@ -4379,7 +4396,7 @@ export async function POST(request: Request) {
throw new Error("未返回结果图片");
}
let finalImage = firstImage;
let finalImageSizeLabel = resolvedImageSize;
let finalImageSizeLabel: string = resolvedImageSize;
try {
const normalizedImage = await normalizeReplacementResultImage({
generatedImageUrl: firstImage.originalUrl,
@ -6127,10 +6144,7 @@ export async function POST(request: Request) {
: undefined
);
const modelCreditCostPerImage = getModelCreditCost(currentModelConfig, "image", {
imageSize:
typeof effectiveImageParams?.imageSize === "string"
? effectiveImageParams.imageSize
: defaultImageQualityParams.imageSize,
imageSize: effectiveImageGenerationParams.imageSize,
});
const modelCreditCostPerVideo = getModelCreditCost(currentModelConfig, "video", {
duration: Number(effectiveVideoParams?.duration) || undefined,
@ -6165,7 +6179,7 @@ export async function POST(request: Request) {
1,
Math.round(
Number(
effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1
effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1
)
)
);
@ -6245,7 +6259,7 @@ export async function POST(request: Request) {
const isGeminiImageProvider = ["gemini-image", "huanke-gemini"].includes((languageModel as any).provider);
if (isGeminiImageProvider && typeof (languageModel as any).doGenerate === "function") {
chatApiLogger.info("[Chat API] Using Gemini image generation, provider:", (languageModel as any).provider);
chatApiLogger.info("[Chat API] Image params:", effectiveImageParams);
chatApiLogger.info("[Chat API] Image params:", effectiveImageGenerationParams);
// 🆕 获取备用模型配置
const currentModelConfig = await getAiModelById({ id: finalModelId });
@ -6332,11 +6346,7 @@ export async function POST(request: Request) {
// 调用 doGenerate 获取图片(如果是备用模型,传入 overrideModelId)
const result = await (languageModel as any).doGenerate({
messages: modelMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
},
imageParams: effectiveImageGenerationParams,
overrideModelId: isRetry ? modelIdToUse : undefined, // 🆕 使用备用模型 ID
});
@ -6362,7 +6372,7 @@ export async function POST(request: Request) {
phase: "processing",
providerType: (languageModel as any).provider,
modelName: currentModelConfig?.displayName || actualModelId,
imageCount: effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1,
imageCount: effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1,
},
"gemini:image-status-start",
);
@ -6384,10 +6394,10 @@ export async function POST(request: Request) {
runtimeModelId: actualModelId,
finalModelId,
providerType: (languageModel as any).provider,
aspectRatio: effectiveImageParams?.aspectRatio,
imageSize: effectiveImageParams?.imageSize,
aspectRatio: effectiveImageGenerationParams.aspectRatio,
imageSize: effectiveImageGenerationParams.imageSize,
imageCount:
effectiveImageParams?.imageCount ||
effectiveImageGenerationParams.imageCount ||
defaultImageQualityParams.imageCount ||
1,
},
@ -6405,7 +6415,7 @@ export async function POST(request: Request) {
const fallbackResult = await generateImageWithFailoverCandidate({
candidate,
messages: buildMessagesForGemini(),
imageParams: effectiveImageParams,
imageParams: effectiveImageGenerationParams,
fallbackImageParams: {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
@ -6431,8 +6441,8 @@ export async function POST(request: Request) {
primaryModelId: actualModelId,
fallbackModelId: candidate.model.modelId,
providerType: candidate.provider.type,
aspectRatio: effectiveImageParams?.aspectRatio,
imageSize: effectiveImageParams?.imageSize,
aspectRatio: effectiveImageGenerationParams.aspectRatio,
imageSize: effectiveImageGenerationParams.imageSize,
},
}).catch((healthError) => {
chatApiLogger.warn("[Chat API] Record Gemini fallback health failure failed:", healthError);
@ -6467,9 +6477,9 @@ export async function POST(request: Request) {
triedFallbackModelIds.add(String(candidate.model.id || ""));
chatApiLogger.info(`[Chat API] 🔁 Gemini cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
const fallbackResult = await generateImageWithFailoverCandidate({
candidate,
messages: buildMessagesForGemini(),
imageParams: effectiveImageParams,
candidate,
messages: buildMessagesForGemini(),
imageParams: effectiveImageGenerationParams,
fallbackImageParams: {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
@ -6665,12 +6675,7 @@ export async function POST(request: Request) {
const volcanoResult = await (volcanoLanguageModel as any).doGenerate({
messages: volcanoMessages,
maxImages: 1, // 故障转移时只生成 1 张
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
});
const imageMarkdown = volcanoResult.text || "图片生成失败";
@ -6844,7 +6849,7 @@ export async function POST(request: Request) {
].includes((languageModel as any).provider);
if (isAlibabaLikeImageProvider && typeof (languageModel as any).doGenerate === "function") {
chatApiLogger.info("[Chat API] Using image generation provider:", (languageModel as any).provider);
chatApiLogger.info("[Chat API] Image params:", effectiveImageParams);
chatApiLogger.info("[Chat API] Image params:", effectiveImageGenerationParams);
// 🆕 获取模型显示名称,用于错误提示
const alibabaModelConfig = await getAiModelById({ id: finalModelId });
@ -6950,12 +6955,7 @@ export async function POST(request: Request) {
apiKey: falApiKey,
modelId: actualModelId,
messages: falMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
});
const placeholderMessageId = generateUUID();
@ -6982,9 +6982,9 @@ export async function POST(request: Request) {
optimizedPrompt: smartAutoOptimizedPrompt || userPrompt || queuedTask.prompt,
userPrompt: userPrompt || queuedTask.prompt,
requestedImageCount:
effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1,
aspectRatio: effectiveImageParams?.aspectRatio,
imageSize: effectiveImageParams?.imageSize,
effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1,
aspectRatio: effectiveImageGenerationParams.aspectRatio,
imageSize: effectiveImageGenerationParams.imageSize,
outputSizeLabel: queuedTask.outputSizeLabel,
sourceImageUrls: requestTargetResolution?.targetImageUrls || queuedTask.sourceImageUrls,
sourceAssetIds: requestTargetResolution?.targetAssetIds || [],
@ -7012,7 +7012,7 @@ export async function POST(request: Request) {
providerType: "fal-image",
modelName: modelDisplayName,
imageCount:
effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1,
effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1,
},
"alibaba:image-status-queued",
);
@ -7074,12 +7074,8 @@ export async function POST(request: Request) {
// 调用 doGenerate 获取图片,传递模型显示名称
const result = await (languageModel as any).doGenerate({
messages: modelMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
imageGenConfig: alibabaModelConfig?.imageGenConfig || null,
modelDisplayName, // 🆕 传递模型显示名称
overrideModelId: isRetry ? modelIdToUse : undefined,
});
@ -7107,7 +7103,7 @@ export async function POST(request: Request) {
phase: "processing",
providerType: (languageModel as any).provider,
modelName: alibabaModelConfig?.displayName || actualModelId,
imageCount: effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1,
imageCount: effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1,
},
"alibaba:image-status-start",
);
@ -7126,7 +7122,7 @@ export async function POST(request: Request) {
const fallbackResult = await generateImageWithFailoverCandidate({
candidate,
messages: messagesForAlibaba,
imageParams: effectiveImageParams,
imageParams: effectiveImageGenerationParams,
fallbackImageParams: {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
@ -7218,12 +7214,8 @@ export async function POST(request: Request) {
const candidateResult = await (candidateLanguageModel as any).doGenerate({
messages: candidateMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
imageGenConfig: candidate.model.imageGenConfig || null,
modelDisplayName: candidate.model.displayName,
overrideModelId: candidate.model.modelId,
});
@ -7501,12 +7493,7 @@ export async function POST(request: Request) {
const tryGenerateImage = async (modelIdToUse: string, isRetry: boolean) => {
const result = await (languageModel as any).doGenerate({
messages: modelMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
overrideModelId: isRetry ? modelIdToUse : undefined,
});
if (result?.finishReason === "error") {
@ -7531,7 +7518,7 @@ export async function POST(request: Request) {
phase: "processing",
providerType: "volcano-vision",
modelName: volcanoModelConfig?.displayName || actualModelId,
imageCount: effectiveImageParams?.imageCount || defaultImageQualityParams.imageCount || 1,
imageCount: effectiveImageGenerationParams.imageCount || defaultImageQualityParams.imageCount || 1,
},
"volcano:image-status-start",
);
@ -7548,7 +7535,7 @@ export async function POST(request: Request) {
const fallbackResult = await generateImageWithFailoverCandidate({
candidate,
messages: messagesForVolcano,
imageParams: effectiveImageParams,
imageParams: effectiveImageGenerationParams,
fallbackImageParams: {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
@ -7639,12 +7626,8 @@ export async function POST(request: Request) {
const candidateResult = await (candidateLanguageModel as any).doGenerate({
messages: candidateMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
imageGenConfig: candidate.model.imageGenConfig || null,
modelDisplayName: candidate.model.displayName,
overrideModelId: candidate.model.modelId,
});
@ -8402,7 +8385,7 @@ export async function POST(request: Request) {
const fallbackResult = await generateImageWithFailoverCandidate({
candidate,
messages: messagesForCrossProvider,
imageParams: effectiveImageParams,
imageParams: effectiveImageGenerationParams,
fallbackImageParams: {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
@ -8498,12 +8481,8 @@ export async function POST(request: Request) {
const candidateResult = await (candidateLanguageModel as any).doGenerate({
messages: candidateMessages,
imageParams:
effectiveImageParams || {
aspectRatio: defaultImageQualityParams.aspectRatio,
imageSize: defaultImageQualityParams.imageSize,
imageCount: defaultImageQualityParams.imageCount,
},
imageParams: effectiveImageGenerationParams,
imageGenConfig: candidate.model.imageGenConfig || null,
modelDisplayName: candidate.model.displayName,
overrideModelId: candidate.model.modelId,
});

View File

@ -30,10 +30,20 @@ const videoParamsSchema = z.object({
returnLastFrame: z.boolean().optional(),
}).optional();
const imageSizeValues = ["1K", "2K", "4K"] as const;
function normalizeImageSizeInput(value: unknown) {
if (typeof value !== "string") return undefined;
const normalized = value.trim().toUpperCase();
return imageSizeValues.includes(normalized as (typeof imageSizeValues)[number])
? normalized
: undefined;
}
// 🆕 图片生成参数 schema
const imageParamsSchema = z.object({
aspectRatio: z.string().optional(),
imageSize: z.string().optional(),
imageSize: z.preprocess(normalizeImageSizeInput, z.enum(imageSizeValues).optional()),
imageCount: z.number().min(1).max(10).optional(),
// 阿里生图专用参数
size: z.string().optional(), // 自定义分辨率,如 "1024*1024"

View File

@ -1894,11 +1894,13 @@ const updateSchema = z.object({
.optional(),
canvasToolbarConfig: z
.object({
selectedImageInlineActionCount: z.number().int().min(3).max(12).optional(),
items: z
.record(
z.object({
label: z.string().trim().max(40).optional(),
iconUrl: z.string().trim().max(2000).optional(),
enabled: z.boolean().optional(),
})
)
.optional(),

View File

@ -27,7 +27,8 @@ import {
Palette,
PenLine,
Play,
PlusCircle,
Plus,
PlusCircle,
RefreshCw,
RotateCw,
Scissors,
@ -649,8 +650,10 @@ export default function CanvasModel3DPage() {
const user = session?.user;
const viewport = useCanvasStore(canvasSelectors.viewport);
const addNode = useCanvasStore((state) => state.addNode);
const getCanvasState = useCanvasStore((state) => state.getCanvasState);
const addNode = useCanvasStore((state) => state.addNode);
const addNodesBulk = useCanvasStore((state) => state.addNodesBulk);
const selectNodes = useCanvasStore((state) => state.selectNodes);
const getCanvasState = useCanvasStore((state) => state.getCanvasState);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("model");
const [mode, setMode] = useState<GenerationMode>("text");
@ -724,8 +727,10 @@ export default function CanvasModel3DPage() {
const [viewerResetToken, setViewerResetToken] = useState(0);
const [taskHistory, setTaskHistory] = useState<TaskRecord[]>([]);
const [currentTask, setCurrentTask] = useState<TaskRecord | null>(null);
const [selectedWorldShareTaskIds, setSelectedWorldShareTaskIds] = useState<string[]>([]);
const [currentTask, setCurrentTask] = useState<TaskRecord | null>(null);
const [selectedWorldShareTaskIds, setSelectedWorldShareTaskIds] = useState<string[]>([]);
// 多选"添加到画布":独立于分享多选,让用户从历史列表中挑选多个世界/模型一次性上画布
const [selectedAddTaskIds, setSelectedAddTaskIds] = useState<Set<string>>(new Set());
const [autoDownloadTaskId, setAutoDownloadTaskId] = useState<string | null>(
null
);
@ -1273,9 +1278,19 @@ export default function CanvasModel3DPage() {
[visibleTaskHistory]
);
const selectedWorldShareTasks = useMemo(() => {
const selectedIds = new Set(selectedWorldShareTaskIds);
return shareableWorldTasks.filter((task) => selectedIds.has(task.taskId));
}, [selectedWorldShareTaskIds, shareableWorldTasks]);
const selectedIds = new Set(selectedWorldShareTaskIds);
return shareableWorldTasks.filter((task) => selectedIds.has(task.taskId));
}, [selectedWorldShareTaskIds, shareableWorldTasks]);
// 可添加到画布的历史记录(世界 + 模型,仅成功状态)
const addableTasks = useMemo(
() => visibleTaskHistory.filter((task) => task.status === "success"),
[visibleTaskHistory]
);
const selectedAddTasks = useMemo(
() => addableTasks.filter((task) => selectedAddTaskIds.has(task.taskId)),
[addableTasks, selectedAddTaskIds]
);
useEffect(() => {
const shareableIds = new Set(shareableWorldTasks.map((task) => task.taskId));
@ -2264,7 +2279,216 @@ export default function CanvasModel3DPage() {
}
}, [id, selectedWorldShareTasks, upsertTaskHistory]);
const handleDisableCurrentShare = useCallback(async () => {
// 多选添加到画布的 handlers
const handleToggleAddSelection = useCallback(
(task: TaskRecord, event?: MouseEvent<HTMLButtonElement>) => {
event?.stopPropagation();
if (task.status !== "success") {
toast.error("仅成功生成的世界/模型可添加到画布");
return;
}
setSelectedAddTaskIds((prev) => {
const next = new Set(prev);
if (next.has(task.taskId)) {
next.delete(task.taskId);
} else {
next.add(task.taskId);
}
return next;
});
},
[]
);
const handleSelectAllForAdd = useCallback(() => {
setSelectedAddTaskIds((prev) => {
if (prev.size === addableTasks.length) {
return new Set();
}
return new Set(addableTasks.map((task) => task.taskId));
});
}, [addableTasks]);
//清理已不存在的选中项
useEffect(() => {
const addableIds = new Set(addableTasks.map((task) => task.taskId));
setSelectedAddTaskIds((prev) => {
const next = new Set<string>();
for (const id of prev) {
if (addableIds.has(id)) next.add(id);
}
return next.size === prev.size ? prev : next;
});
}, [addableTasks]);
//批量添加到画布:复用 addNodesBulk → addNode ring-scan 自动避让
const handleBatchImportToCanvas = useCallback(async () => {
const targets = selectedAddTasks;
if (targets.length ===0) {
toast.error("请至少选择1 个成功生成的世界/模型");
return;
}
const viewportX = viewport.x ||0;
const viewportY = viewport.y ||0;
const viewportZoom = viewport.zoom ||1;
const stageWidth =
typeof window !== "undefined" ? window.innerWidth :1280;
const stageHeight =
typeof window !== "undefined" ? window.innerHeight :720;
const targetWidth =380;
const targetHeight =300;
const baseX =
(stageWidth *0.48 - viewportX) / viewportZoom - targetWidth /2;
const baseY =
(stageHeight *0.45 - viewportY) / viewportZoom - targetHeight /2;
const nodeConfigs: Array<Parameters<typeof addNode>[0]> = [];
for (const task of targets) {
if (task.status !== "success") continue;
const isWorldTask = task.provider === "worldlabs-3d";
const worldAssetPayload = task.assetPayload ?? null;
const taskModelUrl = resolveTaskModelUrl(task);
const primarySplatUrl = isWorldTask
? pickBestArchivedWorldLabsSplatUrl(worldAssetPayload?.spzUrls)
: null;
const worldImageUrl =
worldAssetPayload?.panoUrl ||
worldAssetPayload?.thumbnailUrl ||
task.previewImageUrl ||
null;
const canImport = isWorldTask
? Boolean(
taskModelUrl ||
worldAssetPayload?.worldUrl ||
worldImageUrl ||
primarySplatUrl
)
: Boolean(taskModelUrl);
if (!canImport) continue;
nodeConfigs.push(
isWorldTask
? {
type: "world3d",
position: { x: baseX, y: baseY },
size: { width: targetWidth, height: targetHeight },
data: {
worldUrl: worldAssetPayload?.worldUrl || undefined,
imageUrl: worldImageUrl || undefined,
meshUrl: taskModelUrl || worldAssetPayload?.meshUrl || undefined,
splatUrl: primarySplatUrl || undefined,
previewImage:
task.previewImageUrl ||
worldAssetPayload?.thumbnailUrl ||
undefined,
prompt: task.prompt,
modelVersion: task.modelVersion,
status: "completed",
activeView: primarySplatUrl
? "splat"
: worldImageUrl
? "image"
: "mesh",
firstPerson: false,
hotspots: [],
semanticsMetadata:
worldAssetPayload?.semanticsMetadata || undefined,
metadata: {
taskId: task.taskId,
provider: task.provider,
mode: task.mode,
sourceTaskId: task.sourceTaskId,
progress: task.progress,
triangles: viewerStats.triangles,
vertices: viewerStats.vertices,
meshCount: viewerStats.meshCount,
assetPayload: task.assetPayload ?? null,
},
},
connections: [],
}
: {
type: "model3d",
position: { x: baseX, y: baseY },
size: { width: targetWidth, height: targetHeight },
data: {
src: taskModelUrl!,
previewImage: task.previewImageUrl || undefined,
prompt: task.prompt,
modelVersion: task.modelVersion,
format: extractModelFormat(taskModelUrl!),
status: "completed",
metadata: {
taskId: task.taskId,
provider: task.provider,
mode: task.mode,
sourceTaskId: task.sourceTaskId,
progress: task.progress,
triangles: viewerStats.triangles,
vertices: viewerStats.vertices,
meshCount: viewerStats.meshCount,
assetPayload: task.assetPayload ?? null,
},
},
connections: [],
}
);
}
if (nodeConfigs.length ===0) {
toast.error("选中的资产没有可添加到画布的内容");
return;
}
const createdNodeIds = addNodesBulk(nodeConfigs);
if (createdNodeIds.length >0) {
selectNodes(createdNodeIds);
}
setSelectedAddTaskIds(new Set());
const skipped = targets.length - nodeConfigs.length;
const worldCount = nodeConfigs.filter((c) => c.type === "world3d").length;
const modelCount = nodeConfigs.length - worldCount;
const summary = [
worldCount >0 ? `${worldCount} 个世界` : "",
modelCount >0 ? `${modelCount} 个模型` : "",
]
.filter(Boolean)
.join(" + ");
toast.success(
skipped >0
? `已批量添加 ${summary}(跳过 ${skipped} 个无资源项)`
: `已批量添加 ${summary}到画布`
);
try {
await canvasService.saveCanvasState(id, getCanvasState());
} catch (error) {
console.error("[Model3DPage] 保存批量画布失败:", error);
}
}, [
addNode,
addNodesBulk,
getCanvasState,
id,
selectNodes,
selectedAddTasks,
viewerStats.meshCount,
viewerStats.triangles,
viewerStats.vertices,
viewport.x,
viewport.y,
viewport.zoom,
]);
const handleDisableCurrentShare = useCallback(async () => {
if (!currentTask || currentTask.provider !== "worldlabs-3d") {
toast.error("当前没有可关闭分享的世界资产");
return;
@ -4050,17 +4274,50 @@ export default function CanvasModel3DPage() {
size="sm"
variant="outline"
>
分享所选
</Button>
</div>
</div>
) : null}
<ScrollArea className="flex-1">
分享所选
</Button>
</div>
</div>
) : null}
{addableTasks.length >0 ? (
<div className="space-y-2 border-white/10 border-b px-3 py-3">
<div className="flex items-center justify-between gap-2 text-[11px] text-zinc-500">
<span>批量添加到画布</span>
<span>已选 {selectedAddTaskIds.size}</span>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
className="h-8 border-white/10 bg-zinc-950/60 text-xs text-zinc-200 hover:bg-zinc-800"
disabled={addableTasks.length ===0}
onClick={handleSelectAllForAdd}
size="sm"
variant="outline"
>
{selectedAddTaskIds.size === addableTasks.length && addableTasks.length >0
? "取消全选"
: "全选可添加"}
</Button>
<Button
className="h-8 border-yellow-400/30 bg-yellow-400/15 text-xs text-yellow-100 hover:bg-yellow-400/25"
disabled={selectedAddTaskIds.size ===0}
onClick={() => void handleBatchImportToCanvas()}
size="sm"
variant="outline"
>
添加到画布 ({selectedAddTaskIds.size})
</Button>
</div>
</div>
) : null}
<ScrollArea className="flex-1">
<div className="grid grid-cols-2 gap-2 p-3">
{visibleTaskHistory.map((task) => {
const canShareWorld =
task.provider === "worldlabs-3d" && task.status === "success";
const isSelectedForShare = selectedWorldShareTaskIds.includes(task.taskId);
const isSelectedForAdd =
task.status === "success" && selectedAddTaskIds.has(task.taskId);
const canAddToCanvas = task.status === "success";
return (
<button
@ -4069,8 +4326,10 @@ export default function CanvasModel3DPage() {
currentTask?.taskId === task.taskId &&
"border-yellow-500 ring-2 ring-yellow-500/30 shadow-[0_18px_40px_rgba(0,0,0,0.28)]",
isSelectedForShare &&
"border-cyan-300 ring-2 ring-cyan-300/40"
)}
"border-cyan-300 ring-2 ring-cyan-300/40",
isSelectedForAdd &&
"border-yellow-300 ring-2 ring-yellow-300/40"
)}
key={task.taskId}
onClick={() => handleSelectTask(task)}
type="button"
@ -4111,19 +4370,35 @@ export default function CanvasModel3DPage() {
<Check className="mr-1 h-3 w-3" />
) : null}
{isSelectedForShare ? "已选" : "选择"}
</Button>
) : null}
{task.status === "success" && resolveTaskModelUrl(task) ? (
<Button
className="absolute right-2 top-2 z-10 h-7 w-7 rounded-full border border-white/10 bg-black/60 text-zinc-100 opacity-0 shadow-lg backdrop-blur-sm transition-opacity hover:bg-black/80 group-hover:opacity-100"
onClick={(event) => handleDownloadTask(task, event)}
size="icon"
type="button"
variant="ghost"
>
<Download className="h-3.5 w-3.5" />
</Button>
) : null}
</Button>
) : null}
{canAddToCanvas ? (
<Button
className={cn(
"absolute right-10 top-2 z-10 h-7 rounded-full border border-white/10 bg-black/60 px-2 text-[10px] text-zinc-100 opacity-0 shadow-lg backdrop-blur-sm transition-opacity hover:bg-black/80 group-hover:opacity-100",
isSelectedForAdd &&
"border-yellow-300/60 bg-yellow-400/25 text-yellow-50 opacity-100"
)}
onClick={(event) => handleToggleAddSelection(task, event)}
size="sm"
type="button"
variant="ghost"
>
<Plus className="mr-1 h-3 w-3" />
{isSelectedForAdd ? "已选" : "加画布"}
</Button>
) : null}
{task.status === "success" && resolveTaskModelUrl(task) ? (
<Button
className="absolute right-2 top-2 z-10 h-7 w-7 rounded-full border border-white/10 bg-black/60 text-zinc-100 opacity-0 shadow-lg backdrop-blur-sm transition-opacity hover:bg-black/80 group-hover:opacity-100"
onClick={(event) => handleDownloadTask(task, event)}
size="icon"
type="button"
variant="ghost"
>
<Download className="h-3.5 w-3.5" />
</Button>
) : null}
{task.previewImageUrl ? (
<img
alt="preview"

View File

@ -18,6 +18,7 @@ import { motion, AnimatePresence } from "framer-motion";
import {
ArrowUp,
CheckCircle2,
Droplet,
RefreshCw,
ChevronDown,
ChevronUp,
@ -67,6 +68,7 @@ import { useAgentStylePerformanceMonitor } from "@/components/agents/use-agent-s
import { ImageAnnotator } from "@/components/image-annotator";
import { useCanvasStore } from "@/store/canvas";
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
import { requestLongTaskResult } from "@/lib/client/long-task";
import { buildImageProxyUrl } from "@/lib/image-delivery";
import { extractImageUrlsFromText } from "@/lib/image-url";
import {
@ -1457,6 +1459,8 @@ export function AgentGenerationWorkspaceDarkV2({
const [replacementRerunTarget, setReplacementRerunTarget] =
useState<ReplacementRerunTarget | null>(null);
const [replacementRerunPrompt, setReplacementRerunPrompt] = useState("");
const [detailWatermarkRemoveCardIds, setDetailWatermarkRemoveCardIds] =
useState<Set<string>>(() => new Set());
const closePsdTemplateDialog = useCallback(() => {
setIsPsdTemplateDialogOpen(false);
setPsdTemplateDialogSourceUrl(null);
@ -3859,6 +3863,74 @@ export function AgentGenerationWorkspaceDarkV2({
title: String(params.title || "").trim() || "待改字结果",
});
}, []);
const handleRemoveDetailResultWatermark = useCallback(
async (params: {
cardId: string;
imageUrl: string;
}) => {
const rawUrl = String(params.imageUrl || "").trim();
const cardId = String(params.cardId || "").trim();
if (!cardId || !/^https?:\/\//i.test(rawUrl)) {
toast.error("结果图地址无效,无法去水印");
return;
}
if (isAnyGenerationRunning) {
toast.info("当前仍有生成任务处理中,完成后再去水印");
return;
}
if (detailWatermarkRemoveCardIds.has(cardId)) {
return;
}
setDetailWatermarkRemoveCardIds((current) => {
const next = new Set(current);
next.add(cardId);
return next;
});
toast.info("正在去水印...");
try {
const payload = await requestLongTaskResult({
endpoint: "/api/watermark-remove",
payload: {
image_url: rawUrl,
},
});
if (!payload?.success) {
throw new Error(payload?.error || payload?.detail || "去水印失败");
}
const nextUrl = String(payload.original_url || payload.thumbnail_url || "").trim();
if (!/^https?:\/\//i.test(nextUrl)) {
throw new Error("去水印完成但结果地址无效");
}
handleUpdateReplacementResultRecord({
modeType: "detail_replacement",
cardId,
url: nextUrl,
text: "已完成去水印处理。",
status: "completed",
});
setActiveResultModeType("detail_replacement");
setSelectedResultUrl(nextUrl);
toast.success("去水印完成,已更新当前结果图");
} catch (error) {
console.error("[AgentGenerationWorkspaceDarkV2] 去水印失败:", error);
toast.error(error instanceof Error ? error.message : "去水印失败,请稍后重试");
} finally {
setDetailWatermarkRemoveCardIds((current) => {
const next = new Set(current);
next.delete(cardId);
return next;
});
}
},
[
detailWatermarkRemoveCardIds,
handleUpdateReplacementResultRecord,
isAnyGenerationRunning,
]
);
const getReplacementExecutionCards = useCallback(
(params: {
modeType: ReplacementModeType;
@ -7057,6 +7129,7 @@ export function AgentGenerationWorkspaceDarkV2({
const statusMeta = getReplacementCardStatusMeta(card.status);
const isPending = card.status === "generating" || card.status === "queued";
const hasResult = Boolean(card.resultUrl) && !isPending;
const isWatermarkRemoving = detailWatermarkRemoveCardIds.has(card.id);
return (
<div
key={`${card.id}-result`}
@ -7144,6 +7217,27 @@ export function AgentGenerationWorkspaceDarkV2({
>
重新生图
</button>
<button
type="button"
disabled={isAnyGenerationRunning || isWatermarkRemoving}
onClick={() =>
void handleRemoveDetailResultWatermark({
cardId: card.id,
imageUrl: card.resultUrl!,
})
}
className={cn(
IMAGE_OVERLAY_ACTION_CLASS,
"inline-flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-45"
)}
>
{isWatermarkRemoving ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Droplet className="h-3.5 w-3.5" />
)}
<span>{isWatermarkRemoving ? "去水印中" : "去水印"}</span>
</button>
</div>
</div>
) : (

View File

@ -1284,14 +1284,14 @@ export function AiWashWorkspace({
) : (
<div className="text-center">
<button
className="inline-flex h-16 items-center rounded-[22px] bg-[#111111] px-9 text-[18px] font-semibold text-white shadow-[0_18px_42px_rgba(0,0,0,0.14)] transition hover:-translate-y-0.5 hover:bg-black"
className="inline-flex h-12 items-center rounded-[18px] bg-[#111111] px-6 text-[15px] font-semibold text-white shadow-[0_12px_28px_rgba(0,0,0,0.12)] transition hover:-translate-y-0.5 hover:bg-black"
onClick={() => onRequestAddImage?.()}
type="button"
>
<ImageIcon className="mr-3 h-5 w-5" />
<ImageIcon className="mr-2.5 h-4 w-4" />
添加图片
</button>
<div className="mt-4 text-[14px] text-[#777777]">
<div className="mt-2.5 text-[13px] text-[#777777]">
选择本地图后即可开始 {config.modeLabel || "AI洗图"}
</div>
</div>

View File

@ -170,6 +170,7 @@ import {
getScaledNodeContentStyle,
} from "@/lib/canvas/node-content-scale";
import {
getSelectedImageInlineActionCount,
getCanvasToolbarItem,
isCanvasToolbarItemEnabled,
type CanvasToolbarConfig,
@ -1180,6 +1181,47 @@ export function ImageNode({
);
const imageLayerSplitEnabled =
isLayerSplitEnabled && imageLayerSplitEnabledByToolbar;
const selectedImageInlineActionCount =
getSelectedImageInlineActionCount(canvasToolbarConfig);
const selectedImageToolbarActionCandidates = [
{ key: "pickObject", enabled: imagePickObjectEnabled },
{ key: "enhance", enabled: imageEnhanceEnabled },
{ key: "removeBackground", enabled: imageRemoveBackgroundEnabled },
{ key: "aiWashQuick", enabled: imageAiWashQuickEnabled },
{ key: "textEdit", enabled: imageTextEditEnabled },
{ key: "boxCutout", enabled: imageBoxCutoutEnabled },
{ key: "localEdit", enabled: imageLocalEditEnabled },
{ key: "removeWatermark", enabled: imageRemoveWatermarkEnabled },
{ key: "resize", enabled: imageResizeEnabled },
{ key: "multiAngle", enabled: imageMultiAngleEnabled },
{ key: "generate3dModel", enabled: imageGenerate3dModelEnabled },
{ key: "generate3dWorld", enabled: imageGenerate3dWorldEnabled },
{ key: "layerSplit", enabled: imageLayerSplitEnabled },
{ key: "extend", enabled: imageExtendEnabled },
{ key: "crop", enabled: imageCropEnabled },
{ key: "adjust", enabled: imageAdjustEnabled },
{ key: "flipRotate", enabled: imageFlipRotateEnabled },
{ key: "promptRegenerate", enabled: imagePromptRegenerateEnabled },
{ key: "note", enabled: imageNoteEnabled },
] as const;
type SelectedImageToolbarActionKey =
(typeof selectedImageToolbarActionCandidates)[number]["key"];
const enabledSelectedImageToolbarActions =
selectedImageToolbarActionCandidates.filter((action) => action.enabled);
const selectedImageInlineActionKeys = new Set<SelectedImageToolbarActionKey>(
enabledSelectedImageToolbarActions
.slice(0, selectedImageInlineActionCount)
.map((action) => action.key)
);
const selectedImageMoreActionKeys = new Set<SelectedImageToolbarActionKey>(
enabledSelectedImageToolbarActions
.slice(selectedImageInlineActionCount)
.map((action) => action.key)
);
const isSelectedImageActionInline = (key: SelectedImageToolbarActionKey) =>
selectedImageInlineActionKeys.has(key);
const isSelectedImageActionInMore = (key: SelectedImageToolbarActionKey) =>
selectedImageMoreActionKeys.has(key);
const hasHoverImageMorePrimaryActions =
imageRemoveBackgroundEnabled ||
imageRemoveWatermarkEnabled ||
@ -1201,29 +1243,12 @@ export function ImageNode({
imageNodeMoreEnabled &&
(hasHoverImageMorePrimaryActions || hasHoverImageMoreSecondaryActions);
const hasSelectedImageMorePrimaryActions =
imageExtendEnabled ||
imageCropEnabled ||
imageAdjustEnabled ||
imageFlipRotateEnabled ||
imagePromptRegenerateEnabled ||
imageNoteEnabled;
selectedImageMoreActionKeys.size > 0;
const hasSelectedImageMoreMenu =
imageNodeMoreEnabled &&
(hasSelectedImageMorePrimaryActions || imageDeleteEnabled);
hasSelectedImageMorePrimaryActions ||
(imageNodeMoreEnabled && imageDeleteEnabled);
const hasSelectedImagePrimaryToolbarActions =
imagePickObjectEnabled ||
imageEnhanceEnabled ||
imageRemoveBackgroundEnabled ||
imageBoxCutoutEnabled ||
imageLocalEditEnabled ||
imageRemoveWatermarkEnabled ||
imageResizeEnabled ||
imageTextEditEnabled ||
imageMultiAngleEnabled ||
imageGenerate3dModelEnabled ||
imageGenerate3dWorldEnabled ||
imageAiWashQuickEnabled ||
imageLayerSplitEnabled;
selectedImageInlineActionKeys.size > 0;
const hasSelectedImageSecondaryToolbarActions =
hasSelectedImageMoreMenu || imageDownloadEnabled;
const contentScale = useMemo(
@ -4294,7 +4319,7 @@ export function ImageNode({
const rect = containerRef.current.getBoundingClientRect();
const toolbarWidth = Math.max(
280,
(toolbarSize.width || 980) * FLOATING_TOOLBAR_SCALE
(toolbarSize.width || 640) * FLOATING_TOOLBAR_SCALE
);
const toolbarHeight = Math.max(
42,
@ -4302,12 +4327,12 @@ export function ImageNode({
);
const titleSafeHeight = 34;
const gap = 12;
const { viewportPadding, maxTop, safeLeft, safeRight } =
const { viewportPadding, maxTop, safeBottom, safeLeft, safeRight } =
getFloatingViewportBounds(toolbarHeight);
let top = rect.top - toolbarHeight - titleSafeHeight - gap;
if (top < viewportPadding) {
top = rect.bottom + gap;
let top = rect.bottom + gap;
if (top + toolbarHeight > safeBottom) {
top = rect.top - toolbarHeight - titleSafeHeight - gap;
}
top = Math.min(Math.max(top, viewportPadding), maxTop);
@ -4332,36 +4357,31 @@ export function ImageNode({
return { top: 0, left: 0, maxWidth: 480 };
};
const getAiWashQuickPanelPosition = (
anchor: { top: number; left: number; maxWidth: number }
) => {
if (typeof window === "undefined") {
return { top: 0, left: 0, width: 360, maxHeight: 520 };
const getAiWashQuickPanelPosition = () => {
if (!containerRef.current || typeof window === "undefined") {
return { top: 0, left: 0, width: 286, maxHeight: 430 };
}
const panelWidth = 360;
const panelHeight = 540;
const gap = 10;
const toolbarHeight = Math.max(
42,
(toolbarSize.height || 60) * FLOATING_TOOLBAR_SCALE
);
const rect = containerRef.current.getBoundingClientRect();
const panelWidth = 286;
const panelHeight = 430;
const gap = 12;
const { viewportPadding, safeBottom, safeLeft, safeRight, maxTop } =
getFloatingViewportBounds(panelHeight);
const width = Math.min(panelWidth, Math.max(260, safeRight - safeLeft));
let top = anchor.top + toolbarHeight + gap;
let left = rect.right + gap;
if (left + width > safeRight) {
left = rect.left - width - gap;
}
left = Math.min(Math.max(left, safeLeft), Math.max(safeLeft, safeRight - width));
let top = rect.top;
if (top + panelHeight > safeBottom) {
top = anchor.top - panelHeight - gap;
top = rect.bottom - panelHeight;
}
top = Math.min(Math.max(top, viewportPadding), maxTop);
const preferredLeft = anchor.left;
const left = Math.min(
Math.max(preferredLeft, safeLeft),
Math.max(safeLeft, safeRight - width)
);
return {
top,
left,
@ -7457,7 +7477,7 @@ export function ImageNode({
const cropPanelPosition = getCropPanelPosition();
const imageAdjustPanelPosition = getImageAdjustPanelPosition();
const toolbarPosition = getToolbarPosition();
const aiWashQuickPanelPosition = getAiWashQuickPanelPosition(toolbarPosition);
const aiWashQuickPanelPosition = getAiWashQuickPanelPosition();
const boxCutoutToolbarPosition = getBoxCutoutToolbarPosition();
const flipRotatePanelPosition = getFlipRotatePanelPosition();
const anglePanelPosition = getAnglePanelPosition();
@ -8653,7 +8673,7 @@ export function ImageNode({
typeof document !== "undefined" &&
createPortal(
<div
className="fixed z-[10000] rounded-[28px] border border-slate-200 bg-white/96 p-3.5 text-slate-950 shadow-[0_20px_54px_rgba(15,23,42,0.16)] backdrop-blur-xl dark:border-white/12 dark:bg-slate-950/94 dark:text-white"
className="fixed z-[10000] overflow-hidden rounded-[14px] border border-slate-200 bg-white text-slate-950 shadow-[0_18px_44px_rgba(15,23,42,0.18)] dark:border-white/12 dark:bg-slate-950 dark:text-white"
data-canvas-no-drag="true"
onClick={(event) => event.stopPropagation()}
onMouseDown={(event) => event.stopPropagation()}
@ -8664,104 +8684,89 @@ export function ImageNode({
width: aiWashQuickPanelPosition.width,
maxHeight: aiWashQuickPanelPosition.maxHeight,
overflowY: "auto",
scrollbarWidth: "thin",
scrollbarWidth: "none",
}}
>
<div className="mb-3 flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2.5">
<span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-[16px] border border-slate-200 bg-white shadow-[0_8px_18px_rgba(15,23,42,0.06)] dark:border-white/12 dark:bg-white/8">
<div className="flex items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-white/10">
<div className="flex min-w-0 items-center gap-3">
<span className="flex h-6 w-6 shrink-0 items-center justify-center text-slate-950 dark:text-white">
<CanvasToolbarIcon
className="h-5 w-5"
fallback={Sparkles}
iconUrl={aiWashQuickConfig.modeIconUrl}
/>
</span>
<div className="min-w-0">
<div className="truncate font-semibold text-[16px] tracking-[-0.03em]">
{aiWashQuickModeLabel}
</div>
<div className="mt-0.5 text-[12px] text-slate-500 dark:text-white/52">
选中图片快捷洗图
</div>
<div className="min-w-0 truncate text-[17px] font-semibold tracking-[-0.02em]">
{aiWashQuickModeLabel}
</div>
</div>
<button
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-500 transition hover:border-slate-950 hover:text-slate-950 dark:border-white/12 dark:bg-white/8 dark:text-white/60 dark:hover:border-white dark:hover:text-white"
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-slate-400 transition hover:bg-slate-100 hover:text-slate-950 dark:text-white/54 dark:hover:bg-white/10 dark:hover:text-white"
onClick={() => setAiWashQuickPanelOpen(false)}
title="关闭"
type="button"
>
<X className="h-4 w-4" />
<X className="h-3.5 w-3.5" />
</button>
</div>
{aiWashConfigLoading ? (
<div className="mb-3 flex items-center gap-2 rounded-[18px] border border-slate-200 bg-slate-50 px-3 py-2 text-[13px] text-slate-500 dark:border-white/10 dark:bg-white/6 dark:text-white/58">
<Loader2 className="h-4 w-4 animate-spin" />
<div className="flex items-center gap-2 border-b border-slate-100 px-4 py-3 text-[13px] text-slate-500 dark:border-white/10 dark:text-white/58">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
正在加载 AI洗图 配置...
</div>
) : null}
<div className="space-y-3">
<div className="rounded-[22px] border border-slate-200 bg-slate-50/70 p-3 dark:border-white/10 dark:bg-white/[0.04]">
<div className="divide-y divide-slate-100 dark:divide-white/10">
<div className="px-4 py-3">
<div className="mb-2 flex items-center justify-between gap-2">
<div className="flex items-center gap-2 text-[14px] font-semibold">
<div className="flex items-center gap-2 text-[14px] font-semibold text-slate-950 dark:text-white">
<SlidersHorizontal className="h-4 w-4" />
渲染目标
目标
</div>
<span className="rounded-full border border-slate-200 bg-white px-2 py-0.5 text-[11px] text-slate-500 dark:border-white/10 dark:bg-white/8 dark:text-white/58">
<span className="rounded-full border border-slate-200 bg-white px-2 py-0.5 text-[12px] text-slate-500 dark:border-white/10 dark:bg-white/8 dark:text-white/58">
{getAiWashStatusLabel(aiWashQuickStatus)}
</span>
</div>
<div className="space-y-2">
{aiWashQuickPresets.map((preset) => {
const isActive = selectedAiWashQuickPreset?.id === preset.id;
return (
<button
className={cn(
"w-full rounded-[16px] border px-3 py-2.5 text-left transition",
isActive
? "border-slate-950 bg-slate-950 text-white shadow-[0_10px_22px_rgba(15,23,42,0.16)] dark:border-white dark:bg-white dark:text-slate-950"
: "border-slate-200 bg-white text-slate-600 hover:border-slate-950 hover:text-slate-950 dark:border-white/10 dark:bg-white/7 dark:text-white/64 dark:hover:border-white dark:hover:text-white"
)}
key={preset.id}
onClick={() => {
setAiWashQuickPresetId(preset.id);
setAiWashQuickStatus("idle");
}}
type="button"
>
<div className="truncate font-semibold text-[13px]">
{preset.title}
</div>
{preset.description ? (
<div
className={cn(
"mt-1 line-clamp-2 text-[12px] leading-5",
isActive ? "text-white/72 dark:text-slate-700" : "text-slate-500 dark:text-white/46"
)}
>
{preset.description}
</div>
) : null}
</button>
);
})}
</div>
<Select
onValueChange={(value) => {
setAiWashQuickPresetId(value);
setAiWashQuickStatus("idle");
}}
value={selectedAiWashQuickPreset?.id || aiWashQuickPresetId}
>
<SelectTrigger className="h-10 rounded-[10px] border-slate-200 bg-white px-3 text-[14px] shadow-none dark:border-white/10 dark:bg-white/8">
<SelectValue placeholder="选择渲染目标" />
</SelectTrigger>
<SelectContent className="border-slate-200 bg-white text-slate-950 dark:border-white/10 dark:bg-slate-950 dark:text-white">
{aiWashQuickPresets.map((preset) => (
<SelectItem key={preset.id} value={preset.id}>
{preset.title}
</SelectItem>
))}
</SelectContent>
</Select>
{selectedAiWashQuickPreset?.description ? (
<div className="mt-2 line-clamp-2 text-[12px] leading-5 text-slate-500 dark:text-white/46">
{selectedAiWashQuickPreset.description}
</div>
) : null}
</div>
<div className="rounded-[22px] border border-slate-200 bg-white p-3 dark:border-white/10 dark:bg-white/[0.04]">
<div className="mb-2 text-[14px] font-semibold">参数设置</div>
<div className="px-4 py-3">
<div className="mb-2 text-[14px] font-semibold text-slate-950 dark:text-white">
参数
</div>
{shouldShowAiWashQuickModelSelector ? (
<div className="mb-3 space-y-1.5">
<Label className="text-[12px] text-slate-500 dark:text-white/54">
<Label className="text-[12px] font-medium text-slate-500 dark:text-white/54">
生图模型
</Label>
<Select
onValueChange={setAiWashQuickModelId}
value={selectedAiWashQuickModel?.id || aiWashQuickModelId}
>
<SelectTrigger className="h-10 rounded-[15px] border-slate-200 bg-white text-[13px] shadow-[0_1px_2px_rgba(15,23,42,0.04)] dark:border-white/10 dark:bg-white/8">
<SelectTrigger className="h-10 rounded-[10px] border-slate-200 bg-white px-3 text-[14px] shadow-none dark:border-white/10 dark:bg-white/8">
<SelectValue placeholder="选择生图模型" />
</SelectTrigger>
<SelectContent className="border-slate-200 bg-white text-slate-950 dark:border-white/10 dark:bg-slate-950 dark:text-white">
@ -8787,7 +8792,7 @@ export function ImageNode({
</Select>
<div className="text-[12px] leading-5 text-slate-500 dark:text-white/50">
{selectedAiWashQuickModel
? `当前模型:${selectedAiWashQuickModel.displayName} · ${
? `${selectedAiWashQuickModel.displayName} · ${
selectedAiWashQuickModel.unitCost > 0
? `${selectedAiWashQuickModel.unitCost} 积分/张`
: "未设置积分"
@ -8798,15 +8803,15 @@ export function ImageNode({
</div>
</div>
) : selectedAiWashQuickModel ? (
<div className="mb-3 rounded-[15px] border border-slate-200 bg-slate-50 px-3 py-2 text-[12px] text-slate-500 dark:border-white/10 dark:bg-white/6 dark:text-white/52">
管理员已锁定模型:{selectedAiWashQuickModel.displayName}
<div className="mb-3 rounded-[10px] border border-slate-200 bg-slate-50 px-3 py-2 text-[12px] text-slate-500 dark:border-white/10 dark:bg-white/6 dark:text-white/52">
{selectedAiWashQuickModel.displayName}
{selectedAiWashQuickModel.unitCost > 0
? ` · ${selectedAiWashQuickModel.unitCost} 积分/张`
: ""}
</div>
) : null}
<div className="space-y-2.5">
<div className="-mx-4 divide-y divide-slate-100 dark:divide-white/10">
{aiWashQuickControls.map((control) => {
const selectedIndex =
aiWashQuickLevels[control.id] ?? control.defaultLevel;
@ -8816,14 +8821,14 @@ export function ImageNode({
null;
return (
<div
className="rounded-[16px] border border-slate-200 bg-slate-50/70 px-3 py-2.5 dark:border-white/10 dark:bg-white/[0.04]"
className="px-4 py-3"
key={control.id}
>
<div className="mb-2 flex items-center justify-between gap-2">
<div className="text-[13px] font-semibold">
<div className="text-[14px] font-semibold">
{control.label}
</div>
<span className="min-w-9 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-center text-[11px] text-slate-600 dark:border-white/10 dark:bg-white/8 dark:text-white/64">
<span className="min-w-8 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-center text-[12px] text-slate-600 dark:border-white/10 dark:bg-white/8 dark:text-white/64">
{activeLevel?.label || selectedIndex + 1}
</span>
</div>
@ -8839,7 +8844,7 @@ export function ImageNode({
}
rangeClassName="bg-slate-950 dark:bg-white"
step={1}
thumbClassName="h-3.5 w-3.5 border border-slate-300 bg-white shadow-[0_0_0_3px_rgba(15,23,42,0.06)]"
thumbClassName="h-3.5 w-3.5 border border-slate-300 bg-white shadow-[0_0_0_4px_rgba(15,23,42,0.06)]"
trackClassName="h-1.5 bg-slate-200 dark:bg-white/14"
value={[selectedIndex]}
/>
@ -8849,14 +8854,9 @@ export function ImageNode({
</div>
</div>
{aiWashQuickPrompt ? (
<div className="max-h-20 overflow-hidden rounded-[18px] border border-slate-200 bg-slate-50 px-3 py-2 text-[12px] leading-5 text-slate-500 dark:border-white/10 dark:bg-white/[0.04] dark:text-white/48">
{aiWashQuickPrompt}
</div>
) : null}
<div className="px-3 py-3">
<Button
className="h-11 w-full rounded-[18px] bg-slate-950 text-[14px] font-semibold text-white shadow-[0_12px_26px_rgba(15,23,42,0.16)] hover:bg-slate-900 hover:text-white disabled:bg-slate-200 disabled:text-slate-400 disabled:shadow-none dark:bg-white dark:text-slate-950 dark:hover:bg-slate-100 dark:disabled:bg-white/12 dark:disabled:text-white/30"
className="h-10 w-full rounded-[10px] bg-slate-950 text-[14px] font-semibold text-white shadow-none hover:bg-slate-900 hover:text-white disabled:bg-slate-100 disabled:text-slate-300 disabled:shadow-none dark:bg-white dark:text-slate-950 dark:hover:bg-slate-100 dark:disabled:bg-white/12 dark:disabled:text-white/30"
disabled={
isSubmittingAiWashQuick ||
!selectedAiWashQuickPreset ||
@ -8866,18 +8866,19 @@ export function ImageNode({
type="button"
>
{isSubmittingAiWashQuick ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
) : (
<Sparkles className="mr-2 h-4 w-4" />
<Sparkles className="mr-2 h-3.5 w-3.5" />
)}
{isSubmittingAiWashQuick
? "正在 AI洗图"
: `开始 ${aiWashQuickModeLabel}${
? "生成中"
: `${aiWashQuickModeLabel}${
selectedAiWashQuickModel?.unitCost
? ` · ${selectedAiWashQuickModel.unitCost} 积分`
: ""
: ""
}`}
</Button>
</div>
</div>
</div>,
document.body
@ -8898,7 +8899,7 @@ export function ImageNode({
createPortal(
<TooltipProvider delayDuration={200}>
<div
className="fixed z-[9999] flex items-center rounded-[24px] border border-slate-200 bg-white px-2 py-2 text-gray-800 shadow-[0_14px_38px_rgba(15,23,42,0.16)] dark:border-slate-700 dark:bg-slate-900 dark:text-gray-100"
className="fixed z-[9999] flex items-center gap-0.5 rounded-[24px] border border-slate-200 bg-white px-2 py-1.5 text-gray-800 shadow-[0_14px_38px_rgba(15,23,42,0.16)] dark:border-slate-700 dark:bg-slate-900 dark:text-gray-100"
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
@ -8913,7 +8914,7 @@ export function ImageNode({
180,
Math.floor(toolbarPosition.maxWidth / FLOATING_TOOLBAR_SCALE)
)}px`,
overflowX: "auto",
overflowX: "visible",
scrollbarWidth: "none",
}}
>
@ -8939,11 +8940,13 @@ export function ImageNode({
</Button>
) : null}
{imageAddToChatEnabled && hasSelectedImagePrimaryToolbarActions ? (
{imageAddToChatEnabled &&
(hasSelectedImagePrimaryToolbarActions ||
hasSelectedImageSecondaryToolbarActions) ? (
<div className="mx-1 h-6 w-px bg-slate-200 dark:bg-slate-700" />
) : null}
{imagePickObjectEnabled ? (
{isSelectedImageActionInline("pickObject") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing || isPickerLoading || isThisNodePicking}
@ -8960,7 +8963,7 @@ export function ImageNode({
</Button>
) : null}
{imageEnhanceEnabled ? (
{isSelectedImageActionInline("enhance") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -8977,7 +8980,7 @@ export function ImageNode({
</Button>
) : null}
{imageRemoveBackgroundEnabled ? (
{isSelectedImageActionInline("removeBackground") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -8994,41 +8997,7 @@ export function ImageNode({
</Button>
) : null}
{imageBoxCutoutEnabled ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("box-cutout")}
title={imageBoxCutoutItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Scan}
item={imageBoxCutoutItem}
/>
{imageBoxCutoutItem.label}
</Button>
) : null}
{imageLocalEditEnabled ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing || isSubmittingLocalEdit}
onClick={() => handleAction("local-edit")}
title={imageLocalEditItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Wand2}
item={imageLocalEditItem}
/>
{imageLocalEditItem.label}
</Button>
) : null}
{imageAiWashQuickEnabled ? (
{isSelectedImageActionInline("aiWashQuick") ? (
<Button
className={cn(
"h-10 rounded-xl px-3 font-medium text-[13px] transition",
@ -9055,41 +9024,7 @@ export function ImageNode({
</Button>
) : null}
{imageRemoveWatermarkEnabled ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("watermark")}
title={imageRemoveWatermarkItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Eraser}
item={imageRemoveWatermarkItem}
/>
{imageRemoveWatermarkItem.label}
</Button>
) : null}
{imageResizeEnabled ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("resize")}
title={imageResizeItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Maximize2}
item={imageResizeItem}
/>
{imageResizeItem.label}
</Button>
) : null}
{imageTextEditEnabled ? (
{isSelectedImageActionInline("textEdit") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing || isDetectingText || isApplyingTextEdit}
@ -9106,7 +9041,75 @@ export function ImageNode({
</Button>
) : null}
{imageMultiAngleEnabled ? (
{isSelectedImageActionInline("boxCutout") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("box-cutout")}
title={imageBoxCutoutItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Scan}
item={imageBoxCutoutItem}
/>
{imageBoxCutoutItem.label}
</Button>
) : null}
{isSelectedImageActionInline("localEdit") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing || isSubmittingLocalEdit}
onClick={() => handleAction("local-edit")}
title={imageLocalEditItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Wand2}
item={imageLocalEditItem}
/>
{imageLocalEditItem.label}
</Button>
) : null}
{isSelectedImageActionInline("removeWatermark") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("watermark")}
title={imageRemoveWatermarkItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Eraser}
item={imageRemoveWatermarkItem}
/>
{imageRemoveWatermarkItem.label}
</Button>
) : null}
{isSelectedImageActionInline("resize") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("resize")}
title={imageResizeItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Maximize2}
item={imageResizeItem}
/>
{imageResizeItem.label}
</Button>
) : null}
{isSelectedImageActionInline("multiAngle") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -9123,7 +9126,7 @@ export function ImageNode({
</Button>
) : null}
{imageGenerate3dModelEnabled ? (
{isSelectedImageActionInline("generate3dModel") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -9140,7 +9143,7 @@ export function ImageNode({
</Button>
) : null}
{imageGenerate3dWorldEnabled ? (
{isSelectedImageActionInline("generate3dWorld") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -9157,7 +9160,7 @@ export function ImageNode({
</Button>
) : null}
{imageLayerSplitEnabled ? (
{isSelectedImageActionInline("layerSplit") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
@ -9174,6 +9177,108 @@ export function ImageNode({
</Button>
) : null}
{isSelectedImageActionInline("extend") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("extend")}
title={imageExtendItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Expand}
item={imageExtendItem}
/>
{imageExtendItem.label}
</Button>
) : null}
{isSelectedImageActionInline("crop") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("crop")}
title={imageCropItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={Crop}
item={imageCropItem}
/>
{imageCropItem.label}
</Button>
) : null}
{isSelectedImageActionInline("adjust") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("adjust")}
title={imageAdjustItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={SlidersHorizontal}
item={imageAdjustItem}
/>
{imageAdjustItem.label}
</Button>
) : null}
{isSelectedImageActionInline("flipRotate") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("flip-rotate")}
title={imageFlipRotateItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={FlipHorizontal2}
item={imageFlipRotateItem}
/>
{imageFlipRotateItem.label}
</Button>
) : null}
{isSelectedImageActionInline("promptRegenerate") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("prompt-regenerate")}
title={imagePromptRegenerateItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={RefreshCw}
item={imagePromptRegenerateItem}
/>
{imagePromptRegenerateItem.label}
</Button>
) : null}
{isSelectedImageActionInline("note") ? (
<Button
className="h-10 rounded-xl px-3 font-medium text-[13px] text-slate-700 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-100 dark:hover:bg-zinc-800"
disabled={isProcessing}
onClick={() => handleAction("note")}
title={imageNoteItem.label}
variant="ghost"
>
<CanvasToolbarIcon
className="mr-1.5 h-4 w-4"
fallback={StickyNote}
item={imageNoteItem}
/>
{imageNoteItem.label}
</Button>
) : null}
{hasSelectedImagePrimaryToolbarActions &&
hasSelectedImageSecondaryToolbarActions ? (
<div className="mx-1 h-6 w-px bg-slate-200 dark:bg-slate-700" />
@ -9201,7 +9306,91 @@ export function ImageNode({
className="bg-white opacity-100 backdrop-blur-none dark:bg-slate-900 dark:text-slate-100"
side="bottom"
>
{imageExtendEnabled ? (
{isSelectedImageActionInMore("boxCutout") ? (
<DropdownMenuItem onClick={() => handleAction("box-cutout")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Scan}
item={imageBoxCutoutItem}
/>
{imageBoxCutoutItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("localEdit") ? (
<DropdownMenuItem onClick={() => handleAction("local-edit")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Wand2}
item={imageLocalEditItem}
/>
{imageLocalEditItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("removeWatermark") ? (
<DropdownMenuItem onClick={() => handleAction("watermark")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Eraser}
item={imageRemoveWatermarkItem}
/>
{imageRemoveWatermarkItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("resize") ? (
<DropdownMenuItem onClick={() => handleAction("resize")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Maximize2}
item={imageResizeItem}
/>
{imageResizeItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("multiAngle") ? (
<DropdownMenuItem onClick={() => handleAction("angle")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Box}
item={imageMultiAngleItem}
/>
{imageMultiAngleItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("generate3dModel") ? (
<DropdownMenuItem
onClick={() => handleAction("generate-3d-model")}
>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Box}
item={imageGenerate3dModelItem}
/>
{imageGenerate3dModelItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("generate3dWorld") ? (
<DropdownMenuItem
onClick={() => handleAction("generate-3d-world")}
>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Globe2}
item={imageGenerate3dWorldItem}
/>
{imageGenerate3dWorldItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("layerSplit") ? (
<DropdownMenuItem onClick={() => handleAction("layer-split")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
fallback={Layers}
item={imageLayerSplitItem}
/>
{imageLayerSplitItem.label}
</DropdownMenuItem>
) : null}
{isSelectedImageActionInMore("extend") ? (
<DropdownMenuItem onClick={() => handleAction("extend")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
@ -9211,7 +9400,7 @@ export function ImageNode({
{imageExtendItem.label}
</DropdownMenuItem>
) : null}
{imageCropEnabled ? (
{isSelectedImageActionInMore("crop") ? (
<DropdownMenuItem onClick={() => handleAction("crop")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
@ -9221,7 +9410,7 @@ export function ImageNode({
{imageCropItem.label}
</DropdownMenuItem>
) : null}
{imageAdjustEnabled ? (
{isSelectedImageActionInMore("adjust") ? (
<DropdownMenuItem onClick={() => handleAction("adjust")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
@ -9231,7 +9420,7 @@ export function ImageNode({
{imageAdjustItem.label}
</DropdownMenuItem>
) : null}
{imageFlipRotateEnabled ? (
{isSelectedImageActionInMore("flipRotate") ? (
<DropdownMenuItem onClick={() => handleAction("flip-rotate")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"
@ -9241,7 +9430,7 @@ export function ImageNode({
{imageFlipRotateItem.label}
</DropdownMenuItem>
) : null}
{imagePromptRegenerateEnabled ? (
{isSelectedImageActionInMore("promptRegenerate") ? (
<DropdownMenuItem
onClick={() => handleAction("prompt-regenerate")}
>
@ -9253,7 +9442,7 @@ export function ImageNode({
{imagePromptRegenerateItem.label}
</DropdownMenuItem>
) : null}
{imageNoteEnabled ? (
{isSelectedImageActionInMore("note") ? (
<DropdownMenuItem onClick={() => handleAction("note")}>
<CanvasToolbarIcon
className="mr-2 h-4 w-4"

View File

@ -71,8 +71,17 @@ const IMAGE_SIZE_OPTIONS = [
{ value: "2K", label: "2K", disabled: false },
{ value: "4K", label: "4K", disabled: false },
] as const;
type ImageSizeValue = (typeof IMAGE_SIZE_OPTIONS)[number]["value"];
const IMAGE_SIZE_PIXEL_MAP: Record<string, number> = {
function normalizeImageSizeValue(value?: string, fallback: ImageSizeValue = "2K"): ImageSizeValue {
const normalized = String(value || "").trim().toUpperCase();
if (normalized === "1K" || normalized === "2K" || normalized === "4K") {
return normalized;
}
return fallback;
}
const IMAGE_SIZE_PIXEL_MAP: Record<ImageSizeValue, number> = {
"1K": 1024,
"2K": 2048,
"4K": 4096,
@ -143,16 +152,16 @@ export function ImageParamsBar({
const fallbackCount = options[0] ?? 1;
const imageCount = options.includes(raw.imageCount || fallbackCount) ? (raw.imageCount || fallbackCount) : fallbackCount;
// 根据模型配置校正分辨率:如果当前选择的档位被禁用,则降级到可用的档位
let imageSize = raw.imageSize || "2K";
let imageSize = normalizeImageSizeValue(raw.imageSize);
if (imageGenConfig) {
const sizeAllowed = (s: string) => {
const sizeAllowed = (s: ImageSizeValue) => {
if (s === "1K") return imageGenConfig.supports1K !== false;
if (s === "2K") return imageGenConfig.supports2K !== false;
if (s === "4K") return imageGenConfig.supports4K !== false;
return true;
};
if (!sizeAllowed(imageSize)) {
imageSize = ["2K", "1K", "4K"].find(sizeAllowed) || "2K";
imageSize = (["2K", "1K", "4K"] as const).find(sizeAllowed) || "2K";
}
}
return {
@ -209,7 +218,7 @@ export function ImageParamsBar({
return getGrsaiGptImageOutputSize(aspectRatio, imageSize);
}
const size = IMAGE_SIZE_PIXEL_MAP[imageSize] || IMAGE_SIZE_PIXEL_MAP["2K"];
const size = IMAGE_SIZE_PIXEL_MAP[normalizeImageSizeValue(imageSize)];
if (aspectRatio === "auto" || aspectRatio === "1:1") {
return { width: size, height: size };
}

View File

@ -15,29 +15,29 @@ interface RuxaImageParams {
outputFormat?: "png" | "jpg" | "jpeg" | "webp";
}
interface RuxaImageModelConfig {
supportsSize?: boolean;
supports1K?: boolean;
supports2K?: boolean;
supports4K?: boolean;
}
interface UploadedImage {
thumbnail: string;
original: string;
}
const DEFAULT_RESOLUTION = "1k";
const DEFAULT_RESOLUTION = "1K";
const DEFAULT_OUTPUT_FORMAT = "png";
const POLL_INTERVAL_MS = 2000;
const POLL_MAX_ATTEMPTS = 90;
const RUXA_NANO_BANANA_2_DOC_MODEL_ID = "gemini-3.1-flash-image-preview";
const RUXA_MODEL_ID_ALIASES: Record<string, string> = {
"google/nano-banana-2": RUXA_NANO_BANANA_2_DOC_MODEL_ID,
};
const POLL_MAX_ATTEMPTS = 240;
function normalizeRuxaModelId(modelId?: string) {
const raw = String(modelId || "").trim();
if (!raw) return "gpt-image-1.5";
return RUXA_MODEL_ID_ALIASES[raw] || raw;
}
function isRuxaNanoBanana2Model(modelId?: string) {
const normalized = normalizeRuxaModelId(modelId);
return normalized === RUXA_NANO_BANANA_2_DOC_MODEL_ID;
if (!raw) {
throw new Error("RUXA 模型 ID 未配置");
}
return raw;
}
function normalizeUrlForCompare(url: string) {
@ -68,7 +68,9 @@ function normalizeAspectRatio(aspectRatio?: string) {
const normalized = aspectRatio.trim().toLowerCase();
if (normalized === "auto") return undefined;
const ratio = aspectRatio.trim();
if (["1:1", "16:9", "9:16", "4:3", "3:4", "2:3", "3:2"].includes(ratio)) {
if (
["1:1", "16:9", "9:16", "4:3", "3:4", "2:3", "3:2", "5:4", "4:5", "21:9"].includes(ratio)
) {
return ratio;
}
return undefined;
@ -76,25 +78,65 @@ function normalizeAspectRatio(aspectRatio?: string) {
function normalizeResolution(imageSize?: string) {
if (!imageSize) return DEFAULT_RESOLUTION;
const normalized = imageSize.trim().toLowerCase();
if (["1k", "2k", "4k"].includes(normalized)) return normalized;
const normalized = imageSize.trim().toUpperCase();
if (["1K", "2K", "4K"].includes(normalized)) return normalized;
return DEFAULT_RESOLUTION;
}
function normalizeOutputFormat(outputFormat?: string): "png" | "jpg" | "webp" {
function normalizeOutputFormat(outputFormat?: string): "png" | "jpg" {
if (!outputFormat) return DEFAULT_OUTPUT_FORMAT;
const normalized = outputFormat.trim().toLowerCase();
if (normalized === "jpg" || normalized === "jpeg") return "jpg";
if (normalized === "webp") return "webp";
return "png";
}
function normalizeRuxaOutputFormat(modelId: string | undefined, outputFormat?: string) {
const normalized = normalizeOutputFormat(outputFormat);
if (!isRuxaNanoBanana2Model(modelId)) {
return normalized;
function isResolutionSupported(resolution: string, config?: RuxaImageModelConfig | null) {
if (config?.supportsSize === false) {
return false;
}
return normalized === "jpg" ? "jpeg" : normalized;
const normalized = resolution.toLowerCase();
if (normalized === "1k") return config?.supports1K !== false;
if (normalized === "2k") return config?.supports2K !== false;
if (normalized === "4k") return config?.supports4K !== false;
return true;
}
function buildRuxaTaskInput({
prompt,
imageUrls,
aspectRatio,
resolution,
outputFormat,
modelConfig,
}: {
prompt: string;
imageUrls: string[];
aspectRatio?: string;
resolution: string;
outputFormat: string;
modelConfig?: RuxaImageModelConfig | null;
}) {
const input: Record<string, unknown> = {
prompt,
output_format: outputFormat,
};
const ratio = aspectRatio || "1:1";
input.size = ratio;
input.aspect_ratio = ratio;
if (isResolutionSupported(resolution, modelConfig)) {
input.resolution = resolution;
}
if (imageUrls[0]) {
input.image = imageUrls[0];
}
if (imageUrls.length > 0) {
input.image_input = imageUrls.slice(0, 8);
}
return input;
}
function extractTaskId(payload: any): string | undefined {
@ -132,9 +174,16 @@ function extractStatus(payload: any): string | undefined {
function extractErrorMessage(payload: any): string {
let parsedResultJson: any = null;
if (typeof payload?.resultJson === "string" && payload.resultJson.trim()) {
const rawResultJson =
typeof payload?.resultJson === "string" && payload.resultJson.trim()
? payload.resultJson
: typeof payload?.data?.resultJson === "string" && payload.data.resultJson.trim()
? payload.data.resultJson
: "";
if (rawResultJson) {
try {
parsedResultJson = JSON.parse(payload.resultJson);
parsedResultJson = JSON.parse(rawResultJson);
} catch {
parsedResultJson = null;
}
@ -148,7 +197,7 @@ function extractErrorMessage(payload: any): string {
payload?.errorMessage ||
parsedResultJson?.failMsg ||
parsedResultJson?.error ||
payload?.resultJson ||
rawResultJson ||
payload?.data?.message ||
payload?.data?.error ||
"RUXA 任务执行失败"
@ -388,48 +437,38 @@ export function createRuxaImage({ apiKey, baseURL }: RuxaImageConfig) {
doGenerate: async (options: {
messages: Array<{ role: string; content: any }>;
imageParams?: RuxaImageParams;
imageGenConfig?: RuxaImageModelConfig | null;
overrideModelId?: string;
}) => {
const { prompt, imageUrls } = extractPromptAndImages(options.messages);
const aspectRatio = normalizeAspectRatio(options.imageParams?.aspectRatio);
const resolution = normalizeResolution(options.imageParams?.imageSize);
const requestedModelId = options.overrideModelId || modelId || "gpt-image-1.5";
const requestedModelId = options.overrideModelId || modelId;
const activeModelId = normalizeRuxaModelId(requestedModelId);
const outputFormat = normalizeRuxaOutputFormat(activeModelId, options.imageParams?.outputFormat);
const isNanoBanana2 = isRuxaNanoBanana2Model(activeModelId);
const outputFormat = normalizeOutputFormat(options.imageParams?.outputFormat);
const createEndpoint = joinApiPath(baseURL, "/api/v1/tasks/create");
const callbackUrl = process.env.RUXA_CALLBACK_URL?.trim();
const input: Record<string, unknown> = {
const input = buildRuxaTaskInput({
prompt,
output_format: outputFormat,
};
if (isNanoBanana2) {
input.size = aspectRatio || "1:1";
} else {
input.resolution = resolution;
}
if (aspectRatio && !isNanoBanana2) {
input.size = aspectRatio;
input.aspect_ratio = aspectRatio;
}
if (imageUrls[0]) {
input.image = imageUrls[0];
}
if (imageUrls.length > 1) {
input.image_input = imageUrls;
}
imageUrls,
aspectRatio,
resolution,
outputFormat,
modelConfig: options.imageGenConfig,
});
const requestBody = {
input,
model: activeModelId,
...(callbackUrl ? { callBackUrl: callbackUrl } : {}),
...(callbackUrl ? { callback_url: callbackUrl } : {}),
};
if (activeModelId !== requestedModelId) {
console.log("[Ruxa Image] Remapped modelId for provider compatibility:", {
requestedModelId,
activeModelId,
});
}
console.log("[Ruxa Image] Creating task:", {
model: activeModelId,
resolution: input.resolution || null,
aspectRatio: input.aspect_ratio || input.size || null,
outputFormat,
imageInputCount: imageUrls.length,
});
const createResponse = await fetch(createEndpoint, {
method: "POST",
headers: {
@ -494,6 +533,7 @@ export function createRuxaImage({ apiKey, baseURL }: RuxaImageConfig) {
doStream: async function* (options: {
messages: Array<{ role: string; content: any }>;
imageParams?: RuxaImageParams;
imageGenConfig?: RuxaImageModelConfig | null;
overrideModelId?: string;
}) {
const result = await this.doGenerate(options);

View File

@ -1,4 +1,7 @@
export const CANVAS_TOOLBAR_CONFIG_SETTING_KEY = "canvas_toolbar_config";
export const DEFAULT_SELECTED_IMAGE_INLINE_ACTION_COUNT = 7;
export const MIN_SELECTED_IMAGE_INLINE_ACTION_COUNT = 3;
export const MAX_SELECTED_IMAGE_INLINE_ACTION_COUNT = 12;
export const DEFAULT_CANVAS_TOOLBAR_ITEMS = [
{
@ -716,6 +719,7 @@ export type CanvasToolbarItemConfig = {
export type CanvasToolbarConfig = {
items: Record<CanvasToolbarItemKey, CanvasToolbarItemConfig>;
selectedImageInlineActionCount: number;
};
const DEFAULT_ITEM_BY_KEY = DEFAULT_CANVAS_TOOLBAR_ITEMS.reduce(
@ -732,12 +736,29 @@ const DEFAULT_ITEM_BY_KEY = DEFAULT_CANVAS_TOOLBAR_ITEMS.reduce(
export const defaultCanvasToolbarConfig: CanvasToolbarConfig = {
items: DEFAULT_ITEM_BY_KEY,
selectedImageInlineActionCount: DEFAULT_SELECTED_IMAGE_INLINE_ACTION_COUNT,
};
function normalizeString(value: unknown, maxLength: number) {
return String(value || "").trim().slice(0, maxLength);
}
function normalizeInteger(
value: unknown,
fallback: number,
min: number,
max: number
) {
const parsed =
typeof value === "number"
? value
: typeof value === "string"
? Number(value)
: Number.NaN;
if (!Number.isFinite(parsed)) return fallback;
return Math.min(max, Math.max(min, Math.round(parsed)));
}
export function normalizeCanvasToolbarConfig(
value: unknown
): CanvasToolbarConfig {
@ -769,7 +790,21 @@ export function normalizeCanvasToolbarConfig(
};
});
return { items };
return {
items,
selectedImageInlineActionCount: normalizeInteger(
raw.selectedImageInlineActionCount,
DEFAULT_SELECTED_IMAGE_INLINE_ACTION_COUNT,
MIN_SELECTED_IMAGE_INLINE_ACTION_COUNT,
MAX_SELECTED_IMAGE_INLINE_ACTION_COUNT
),
};
}
export function getSelectedImageInlineActionCount(
config: CanvasToolbarConfig | null | undefined
): number {
return normalizeCanvasToolbarConfig(config).selectedImageInlineActionCount;
}
export function getDefaultCanvasToolbarItem(

View File

@ -587,6 +587,7 @@ export async function generateCanvasImage(
...imageParams,
imageCount: batchImageCount,
},
imageGenConfig: selectedModel.model.imageGenConfig || null,
});
return result.text || "";
};

View File

@ -3,7 +3,7 @@ const MAX_STRING_LENGTH = 240;
const SENSITIVE_KEY_PATTERN =
/(authorization|cookie|password|secret|token|apikey|api_key|accesskey|access_key|clientsecret|client_secret|credential|prompt|session|csrf|code)/i;
const URL_KEY_PATTERN = /(url|uri|endpoint|origin|href|src|image|thumbnail|avatar|file)/i;
const URL_KEY_PATTERN = /(url|uri|endpoint|origin|href|src|thumbnail|avatar|file)/i;
const DATA_URL_PATTERN = /^data:[^;]+;base64,/i;
const EMBEDDED_DATA_URL_PATTERN = /data:[^;,\s]+;base64,[A-Za-z0-9+/=_-]+/gi;
const EMBEDDED_URL_PATTERN = /https?:\/\/[^\s"'<>),]+/gi;

View File

@ -33,6 +33,7 @@
"clean:artifacts": "node scripts/clean-local-artifacts.mjs",
"smoke:routes": "node scripts/smoke-routes.mjs",
"verify:release": "node scripts/verify-release.mjs",
"verify:ruxa-models": "pnpm exec tsx scripts/verify-ruxa-image-models.ts",
"backfill:agent-preview-images": "pnpm exec tsx scripts/backfill-agent-workflow-preview-images.ts",
"rewrite:agent-preview-image-urls": "pnpm exec tsx scripts/rewrite-agent-workflow-preview-image-urls.ts",
"format": "pnpm exec ultracite fix",

View File

@ -0,0 +1,208 @@
import { config as loadEnv } from "dotenv";
import { and, eq, sql } from "drizzle-orm";
import { db } from "../lib/db";
import { aiModel, aiProvider } from "../lib/db/schema";
loadEnv({ path: ".env.local" });
type ModelExpectation = {
modelId: string;
displayName: string;
};
const EXPECTED_MODELS: ModelExpectation[] = [
{ modelId: "google/nano-banana-2", displayName: "nano-banana-2「专线」" },
{ modelId: "google/nano-banana-pro", displayName: "nano-banana-pro「专线」" },
];
type Row = {
providerId: string;
providerName: string;
providerType: string;
modelId: string;
displayName: string;
supportsImageGen: boolean | null;
supportsVision: boolean | null;
isEnabled: boolean | null;
isHidden: boolean | null;
healthStatus: string | null;
imageGenConfig: Record<string, unknown> | null;
};
function getConfigFlag(
config: Record<string, unknown> | null,
key: string
): boolean | null {
const raw = config?.[key];
return typeof raw === "boolean" ? raw : null;
}
async function main() {
const rows = await db
.select({
providerId: aiProvider.id,
providerName: aiProvider.name,
providerType: aiProvider.type,
modelId: aiModel.modelId,
displayName: aiModel.displayName,
supportsImageGen: aiModel.supportsImageGen,
supportsVision: aiModel.supportsVision,
isEnabled: aiModel.isEnabled,
isHidden: aiModel.isHidden,
healthStatus: aiModel.healthStatus,
imageGenConfig: aiModel.imageGenConfig,
})
.from(aiModel)
.innerJoin(aiProvider, eq(aiModel.providerId, aiProvider.id))
.where(
and(
eq(aiProvider.type, "ruxa-image"),
sql`LOWER(${aiProvider.name}) LIKE ${"%ruxa%"}`,
sql`LOWER(${aiModel.modelId}) IN (${"google/nano-banana-2"}, ${"google/nano-banana-pro"})`
)
);
const found = new Map<string, Row[]>();
for (const row of rows) {
const bucket = found.get(row.providerId) ?? [];
bucket.push(row);
found.set(row.providerId, bucket);
}
const providers = [...found.entries()].map(([providerId, models]) => ({
providerId,
providerName: models[0]?.providerName ?? "",
providerType: models[0]?.providerType ?? "",
modelCount: models.length,
models,
}));
const failures: string[] = [];
const expectByModelId = new Map(
EXPECTED_MODELS.map((entry) => [entry.modelId, entry.displayName])
);
const expectedSet = new Set(expectByModelId.keys());
for (const row of rows) {
if (!expectedSet.has(row.modelId)) {
failures.push(`Unexpected model present in RUXA image provider: ${row.modelId}`);
continue;
}
const expectedDisplayName = expectByModelId.get(row.modelId);
if (expectedDisplayName && row.displayName !== expectedDisplayName) {
failures.push(
`${row.providerName} ${row.modelId}: displayName mismatch (expected "${expectedDisplayName}", got "${row.displayName}")`
);
}
const config =
row.imageGenConfig &&
typeof row.imageGenConfig === "object" &&
!Array.isArray(row.imageGenConfig)
? (row.imageGenConfig as Record<string, unknown>)
: null;
if (row.supportsImageGen !== true) {
failures.push(`${row.providerName} ${row.modelId}: supportsImageGen is not true`);
}
if (row.supportsVision !== true) {
failures.push(`${row.providerName} ${row.modelId}: supportsVision is not true`);
}
if (row.isEnabled !== true) {
failures.push(`${row.providerName} ${row.modelId}: isEnabled is not true`);
}
if (row.isHidden === true) {
failures.push(`${row.providerName} ${row.modelId}: isHidden should be false`);
}
if (row.healthStatus !== "healthy") {
failures.push(
`${row.providerName} ${row.modelId}: healthStatus is ${row.healthStatus ?? "null"}, expected healthy`
);
}
if (getConfigFlag(config, "supportsSize") !== true) {
failures.push(`${row.providerName} ${row.modelId}: imageGenConfig.supportsSize should be true`);
}
if (getConfigFlag(config, "supports1K") !== true) {
failures.push(
`${row.providerName} ${row.modelId}: imageGenConfig.supports1K should be true`
);
}
if (getConfigFlag(config, "supports2K") !== true) {
failures.push(
`${row.providerName} ${row.modelId}: imageGenConfig.supports2K should be true`
);
}
if (getConfigFlag(config, "supports4K") !== true) {
failures.push(
`${row.providerName} ${row.modelId}: imageGenConfig.supports4K should be true`
);
}
}
for (const provider of providers) {
const providerModels = provider.models.map((item) => item.modelId);
for (const expected of EXPECTED_MODELS) {
if (!providerModels.includes(expected.modelId)) {
failures.push(
`${provider.providerName}: missing required model ${expected.modelId} (${expected.displayName})`
);
}
}
}
const providerSummary = providers
.sort((a, b) => a.providerName.localeCompare(b.providerName))
.map((provider) => {
return {
providerName: provider.providerName,
providerType: provider.providerType,
providerId: provider.providerId,
hasAllTargets: EXPECTED_MODELS.every((expected) =>
provider.models.some((row) => row.modelId === expected.modelId)
),
modelRows: provider.models
.sort((a, b) => a.modelId.localeCompare(b.modelId))
.map((row) => ({
modelId: row.modelId,
displayName: row.displayName,
isEnabled: row.isEnabled,
healthStatus: row.healthStatus,
imageSize4K: getConfigFlag(
row.imageGenConfig &&
typeof row.imageGenConfig === "object" &&
!Array.isArray(row.imageGenConfig)
? (row.imageGenConfig as Record<string, unknown>)
: null,
"supports4K"
),
})),
};
});
console.log(
JSON.stringify(
{
expected: EXPECTED_MODELS,
providerSummary,
},
null,
2
)
);
if (failures.length > 0) {
console.error("RUXA image model check failed:");
failures.forEach((item) => console.error(`- ${item}`));
process.exit(1);
}
console.log("RUXA image model check passed.");
}
main().catch((error) => {
console.error("RUXA image model verification failed to execute:", error);
process.exit(1);
});

View File

@ -122,7 +122,10 @@ interface CanvasStore {
// 节点操作
addNode: (node: Omit<CanvasNode, 'id' | 'createdAt' | 'updatedAt'>) => string;
updateNode: (id: string, updates: Partial<CanvasNode>) => void;
addNodesBulk: (
nodes: Array<Omit<CanvasNode, 'id' | 'createdAt' | 'updatedAt'>>
) => string[];
updateNode: (id: string, updates: Partial<CanvasNode>) => void;
deleteNode: (id: string) => void;
deleteSelectedNodes: () => void;
addSuppressedMediaKeys: (keys: string[]) => void;
@ -230,82 +233,97 @@ export const useCanvasStore = create<CanvasStore>()(
// 节点操作
addNode: (nodeData) => {
const imageMetadata =
nodeData.type === 'image' && nodeData.data && typeof nodeData.data === 'object'
? (((nodeData.data as any).metadata ?? {}) as Record<string, unknown>)
: {};
const shouldPreserveImagePosition =
imageMetadata.allowOverlap === true || imageMetadata.placementMode === 'overlay';
const imageMetadata =
nodeData.type === 'image' && nodeData.data && typeof nodeData.data === 'object'
? (((nodeData.data as any).metadata ?? {}) as Record<string, unknown>)
: {};
const shouldPreserveImagePosition =
imageMetadata.allowOverlap === true || imageMetadata.placementMode === 'overlay';
const resolveImagePosition = (
basePosition: Position,
size: Size,
nodes: CanvasNode[]
): Position => {
if (nodeData.type !== 'image' || shouldPreserveImagePosition) return basePosition;
const padding = 20;
const width = size?.width || 300;
const height = size?.height || 300;
const stepX = width + padding;
const stepY = height + padding;
//通用避让算法:对所有节点类型生效(除 image 的 placementMode兼容情况外)
// 历史原因:早期只对 image 类型做避让,导致 world3d/model3d 等重复添加会叠到一起。
// 现在统一避让,image 的 allowOverlap/overlay 元数据仍可跳过避让以保持向后兼容。
const resolveAutoPosition = (
basePosition: Position,
size: Size,
nodes: CanvasNode[],
nodeType: NodeType
): Position => {
// image 类型若标记了"允许重叠",保持原坐标以兼容既有行为
if (nodeType === 'image' && shouldPreserveImagePosition) return basePosition;
const padding =20;
const width = size?.width ||300;
const height = size?.height ||300;
const stepX = width + padding;
const stepY = height + padding;
const overlaps = (pos: Position) => nodes.some(n => {
if (n.type !== 'image') return false;
const nSize = n.size || { width: 300, height: 300 };
return !(
pos.x + width + padding <= n.position.x ||
pos.x >= n.position.x + nSize.width + padding ||
pos.y + height + padding <= n.position.y ||
pos.y >= n.position.y + nSize.height + padding
);
});
const overlaps = (pos: Position) => nodes.some(n => {
if (n.type !== nodeType) return false;
const nSize = n.size || { width:300, height:300 };
return !(
pos.x + width + padding <= n.position.x ||
pos.x >= n.position.x + nSize.width + padding ||
pos.y + height + padding <= n.position.y ||
pos.y >= n.position.y + nSize.height + padding
);
});
if (!overlaps(basePosition)) return basePosition;
if (!overlaps(basePosition)) return basePosition;
const maxRings = 20;
for (let ring = 1; ring <= maxRings; ring++) {
for (let dx = -ring; dx <= ring; dx++) {
for (let dy = -ring; dy <= ring; dy++) {
if (Math.abs(dx) !== ring && Math.abs(dy) !== ring) continue;
const candidate = {
x: basePosition.x + dx * stepX,
y: basePosition.y + dy * stepY,
};
if (!overlaps(candidate)) {
return candidate;
}
}
}
}
const maxRings =20;
for (let ring =1; ring <= maxRings; ring++) {
for (let dx = -ring; dx <= ring; dx++) {
for (let dy = -ring; dy <= ring; dy++) {
if (Math.abs(dx) !== ring && Math.abs(dy) !== ring) continue;
const candidate = {
x: basePosition.x + dx * stepX,
y: basePosition.y + dy * stepY,
};
if (!overlaps(candidate)) {
return candidate;
}
}
}
}
return basePosition;
};
return basePosition;
};
const id = generateId();
const now = new Date();
const basePosition = nodeData.position || { x: 0, y: 0 };
const nodeSize = nodeData.size || { width: 300, height: 300 };
const finalPosition = resolveImagePosition(basePosition, nodeSize, get().nodes);
const node: CanvasNode = {
...nodeData,
id,
createdAt: now,
updatedAt: now,
position: finalPosition,
};
const id = generateId();
const now = new Date();
const basePosition = nodeData.position || { x:0, y:0 };
const nodeSize = nodeData.size || { width:300, height:300 };
const finalPosition = resolveAutoPosition(basePosition, nodeSize, get().nodes, nodeData.type);
const node: CanvasNode = {
...nodeData,
id,
createdAt: now,
updatedAt: now,
position: finalPosition,
};
set((state) => {
state.nodes.push(node);
if (node.type === 'image') {
state.lastAddedNodeId = id;
}
});
set((state) => {
state.nodes.push(node);
if (node.type === 'image') {
state.lastAddedNodeId = id;
}
});
// 添加到历史
get().pushHistory();
// 添加到历史
get().pushHistory();
return id;
},
return id;
},
//批量添加节点:循环调用 addNode 以复用其避让逻辑,
//适用于从历史列表中多选世界/模型添加到画布等场景。
addNodesBulk: (nodesData) => {
const ids: string[] = [];
for (const nodeData of nodesData) {
ids.push(get().addNode(nodeData));
}
return ids;
},
updateNode: (id, updates) => set((state) => {
const index = state.nodes.findIndex(n => n.id === id);