From 77b25662b42968eb19cac6c43b1db1f46a62614c Mon Sep 17 00:00:00 2001 From: 134 Date: Sat, 4 Jul 2026 13:40:02 +0800 Subject: [PATCH 01/29] fix: send layout drafts to fal scale edits --- app/api/canvas/local-edit/route.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/api/canvas/local-edit/route.ts b/app/api/canvas/local-edit/route.ts index 004fa0011..28be69d65 100644 --- a/app/api/canvas/local-edit/route.ts +++ b/app/api/canvas/local-edit/route.ts @@ -3884,18 +3884,19 @@ export async function POST(request: NextRequest) { isScaleAdjustOperation && resolvedScaleAdjustModelEntry?.provider?.type === "alibaba-image"; const useScaleAdjustCoordinatePrompt = useScaleAdjustCoordinateGuide; + const useScaleAdjustFullFrameFalEdit = + isScaleAdjustOperation && + isScaleAdjustFalNanoBananaEditModel(resolvedScaleAdjustModelEntry); const useFalScaleAdjustCoordinatePrompt = useScaleAdjustCoordinatePrompt && - resolvedScaleAdjustModelEntry?.provider?.type === "fal-image"; + resolvedScaleAdjustModelEntry?.provider?.type === "fal-image" && + !useScaleAdjustFullFrameFalEdit; const useScaleAdjustVisualLayoutGuide = useScaleAdjustCoordinatePrompt && !useFalScaleAdjustCoordinatePrompt && !useProviderTextOnlyCoordinatePrompt; const useScaleAdjustMarkedPhotoGuide = useScaleAdjustCoordinatePrompt && !useScaleAdjustVisualLayoutGuide; - const useScaleAdjustFullFrameFalEdit = - isScaleAdjustOperation && - isScaleAdjustFalNanoBananaEditModel(resolvedScaleAdjustModelEntry); const useScaleAdjustStructureLockedPatchWorkflow = isScaleAdjustOperation && !useScaleAdjustFullFrameFalEdit && From 690d04ec712878f466359dfc52c5c8e8bd33ec19 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 14:16:09 +0800 Subject: [PATCH 02/29] feat: add downloads for style pro and ai wash results --- components/canvas/AiWashWorkspace.tsx | 53 +++++++++++++++ components/style-pro/StyleProWorkspace.tsx | 76 +++++++++++++++++++++- 2 files changed, 128 insertions(+), 1 deletion(-) diff --git a/components/canvas/AiWashWorkspace.tsx b/components/canvas/AiWashWorkspace.tsx index 5e878afe9..10690b970 100644 --- a/components/canvas/AiWashWorkspace.tsx +++ b/components/canvas/AiWashWorkspace.tsx @@ -3,6 +3,7 @@ import { ChevronDown, Clock3, + Download, History as HistoryIcon, ImageIcon, Loader2, @@ -45,6 +46,7 @@ import { type AiWashControlLevel, type AiWashPreset, } from "@/lib/ai-wash/config"; +import { downloadCanvasImageAsPng } from "@/lib/client/canvas-image-download"; import { buildImageProxyUrl } from "@/lib/image-delivery"; import { cn } from "@/lib/utils"; import { imageGenerationService } from "@/services/canvas"; @@ -368,6 +370,11 @@ function getAiWashStatusLabel(status?: AiWashResultStatus) { } } +function buildAiWashDownloadName(result: AiWashResultCard) { + const createdAt = result.createdAt || Date.now(); + return `ai-wash-${result.title || result.presetId || "result"}-${createdAt}`; +} + function composePresetPrompt(params: { preset: AiWashPreset; selectedLevelIndexByControl: Record; @@ -456,6 +463,9 @@ export function AiWashWorkspace({ useState>({}); const [historySourceOverride, setHistorySourceOverride] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); + const [downloadingResultId, setDownloadingResultId] = useState( + null + ); const [isHistoryExpanded, setIsHistoryExpanded] = useState(false); const [lastErrorMessage, setLastErrorMessage] = useState(""); const [comparePositionById, setComparePositionById] = useState< @@ -977,6 +987,30 @@ export function AiWashWorkspace({ }); }, [compareSourceUrl, onApplyResult, selectedResult]); + const handleDownloadSelectedResult = useCallback(async () => { + if (!selectedResult?.imageUrl) { + toast.error("请先选择一张洗图结果"); + return; + } + + const downloadId = selectedResult.presetId || selectedResult.imageUrl; + setDownloadingResultId(downloadId); + try { + await downloadCanvasImageAsPng({ + url: selectedResult.imageUrl, + name: buildAiWashDownloadName(selectedResult), + candidates: [selectedResult.imageUrl], + }); + toast.success("图片已开始下载"); + } catch (error) { + toast.error(error instanceof Error ? error.message : "下载失败"); + } finally { + setDownloadingResultId((current) => + current === downloadId ? null : current + ); + } + }, [selectedResult]); + const handleLoadHistoryBatch = useCallback((entry: AiWashHistoryBatch) => { const loadedPresetId = (entry.items.find((item) => item.isDefault) || entry.items[0])?.presetId || ""; @@ -1430,6 +1464,25 @@ export function AiWashWorkspace({ + {selectedResult?.imageUrl ? ( + + ) : null} + + ) : null} ); } @@ -1021,6 +1055,9 @@ export function StyleProWorkspace({ useState("style"); const [selectedModelId, setSelectedModelId] = useState(""); const [uploading, setUploading] = useState(false); + const [downloadingImageId, setDownloadingImageId] = useState( + null + ); const [generationTaskState, setGenerationTaskState] = useState(null); const generating = @@ -1458,6 +1495,34 @@ export function StyleProWorkspace({ [config] ); + const handleDownloadResult = useCallback( + async (item?: StyleProHistoryItem | null) => { + const target = item || currentResult; + if (!target?.resultImageUrl) { + toast.error("暂无可下载的结果图"); + return; + } + + const downloadId = target.id || target.resultImageUrl; + setDownloadingImageId(downloadId); + try { + await downloadCanvasImageAsPng({ + url: target.resultImageUrl, + name: buildStyleProDownloadName(target), + candidates: [target.resultImageUrl], + }); + toast.success("图片已开始下载"); + } catch (error) { + toast.error(error instanceof Error ? error.message : "下载失败"); + } finally { + setDownloadingImageId((current) => + current === downloadId ? null : current + ); + } + }, + [currentResult] + ); + const disabledReason = !sourceImageUrl ? "请先上传图片" : generationMode === "realistic" && config?.realisticModeAvailable === false @@ -1875,6 +1940,15 @@ export function StyleProWorkspace({ { + void handleDownloadResult(currentResult); + }} taskState={generationTaskState} /> From 57a4840df24af9d29ba76706f87bd1fe4002befa Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 14:27:48 +0800 Subject: [PATCH 03/29] fix: keep canvas chat messages ordered --- .../canvas/chat-panel/canvas-chat-media.ts | 12 +++-- tests/routes/canvas-chat-helpers.test.ts | 49 +++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/components/canvas/chat-panel/canvas-chat-media.ts b/components/canvas/chat-panel/canvas-chat-media.ts index 0d022f2d6..88d2e2269 100644 --- a/components/canvas/chat-panel/canvas-chat-media.ts +++ b/components/canvas/chat-panel/canvas-chat-media.ts @@ -381,11 +381,15 @@ export function sortCanvasMessagesByCreatedAt(messages: ChatMessage[]): ChatMess .sort((a, b) => { const messageA = a.message; const messageB = b.message; - const timeA = getMessageTimestamp(messageA) ?? 0; - const timeB = getMessageTimestamp(messageB) ?? 0; - if (timeA !== timeB) return timeA - timeB; + const timeA = getMessageTimestamp(messageA); + const timeB = getMessageTimestamp(messageB); + const hasTimeA = timeA !== null; + const hasTimeB = timeB !== null; - if (messageA.role !== messageB.role) { + if (hasTimeA && hasTimeB && timeA !== timeB) return timeA - timeB; + if (hasTimeA !== hasTimeB) return hasTimeA ? -1 : 1; + + if (hasTimeA && hasTimeB && messageA.role !== messageB.role) { if (messageA.role === "user") return -1; if (messageB.role === "user") return 1; } diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index d51b0caec..6edd96b14 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -4,6 +4,7 @@ import { extractAssistantImageUrls, extractVideoUrls, normalizeMediaUrl, + sortCanvasMessagesByCreatedAt, stripMediaMarkup, } from "@/components/canvas/chat-panel/canvas-chat-media"; import { @@ -211,6 +212,54 @@ import type { CanvasAgentContext } from "@/types/canvas/agent-protocol"; import type { ChatMessage } from "@/lib/types"; test.describe("canvas chat pure helpers", () => { + test("keeps optimistic messages without timestamps after persisted history", () => { + const messages = [ + { + id: "optimistic-latest-user", + role: "user", + parts: [{ type: "text", text: "你能为我做什么?列出表给我" }], + }, + { + id: "persisted-first-user", + role: "user", + createdAt: "2026-07-07T01:00:00.000Z", + parts: [{ type: "text", text: "你好" }], + }, + { + id: "persisted-first-assistant", + role: "assistant", + createdAt: "2026-07-07T01:00:01.000Z", + parts: [{ type: "text", text: "你好,我在。" }], + }, + ] as ChatMessage[]; + + expect(sortCanvasMessagesByCreatedAt(messages).map((message) => message.id)).toEqual([ + "persisted-first-user", + "persisted-first-assistant", + "optimistic-latest-user", + ]); + }); + + test("preserves relative order among messages without timestamps", () => { + const messages = [ + { + id: "pending-user", + role: "user", + parts: [{ type: "text", text: "生成一张图" }], + }, + { + id: "pending-assistant", + role: "assistant", + parts: [{ type: "text", text: "分析中" }], + }, + ] as ChatMessage[]; + + expect(sortCanvasMessagesByCreatedAt(messages).map((message) => message.id)).toEqual([ + "pending-user", + "pending-assistant", + ]); + }); + test("formats uploaded spreadsheet rows as safe markdown tables for OpenClaw", () => { const markdown = rowsToOpenClawMarkdownTable([ ["名称", "备注"], From ee7d104734b43865f29a75ec8f68ff833af8a01c Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 14:38:26 +0800 Subject: [PATCH 04/29] fix: add agent preface before generation --- app/(chat)/api/chat/route.ts | 86 +++++++++++++++++++++++++++ components/canvas/CanvasChatPanel.tsx | 5 +- 2 files changed, 87 insertions(+), 4 deletions(-) diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index 3dd0b80fc..df38dbc43 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -541,6 +541,65 @@ function writeCanvasOperationShadowChunk(params: { ); } +const AGENT_EXECUTION_PREFACE_INTERNAL_PATTERN = + /(?:^|\n)\s*(?:#{1,6}\s*)?(?:需求理解|图片分析|执行计划|输出设置|优化后提示词|使用建议)(?:\s|[::]|$)|【\s*(?:需求理解|图片分析|执行计划|输出设置|优化后提示词|使用建议)\s*】|提示词|自动优化|模型|提交生成|回写|流程|步骤/; + +function buildAgentExecutionPrefaceText(params: { + friendlyMessage?: string | null; + fallback: string; +}) { + const fallback = String(params.fallback || "").replace(/\s+/g, " ").trim(); + const rawMessage = String(params.friendlyMessage || "") + .replace(//g, "") + .trim(); + + if (!rawMessage || AGENT_EXECUTION_PREFACE_INTERNAL_PATTERN.test(rawMessage)) { + return fallback; + } + + const candidate = rawMessage + .split(/\r?\n/) + .map((line) => line.replace(/^[-*]\s*/, "").trim()) + .find(Boolean); + + if (!candidate || AGENT_EXECUTION_PREFACE_INTERNAL_PATTERN.test(candidate)) { + return fallback; + } + + const firstSentence = candidate.match(/^(.{1,80}?[。!?!?~~])/u)?.[1] || candidate; + const compact = firstSentence.replace(/\s+/g, " ").trim().slice(0, 80); + return /[。!?!?~~]$/.test(compact) ? compact : `${compact}。`; +} + +async function writeAgentExecutionPrefaceMessage(params: { + writer: StreamWriter; + chatId: string; + label: string; + friendlyMessage?: string | null; + fallback: string; +}) { + const text = buildAgentExecutionPrefaceText({ + friendlyMessage: params.friendlyMessage, + fallback: params.fallback, + }); + if (!text) return null; + + const messageId = generateUUID(); + writeAssistantTextChunk(params.writer, text, params.label, messageId); + + try { + await saveAssistantTextOnlyMessage({ + chatId: params.chatId, + messageId, + text, + }); + } catch (error) { + chatApiLogger.warn("[Chat API] Failed to persist agent execution preface:", error); + } + + return messageId; +} + async function replayAssistantMessagesForDuplicateRequest({ chatId, userMessageId, @@ -7715,6 +7774,16 @@ export async function POST(request: Request) { ) { const directImageStream = createUIMessageStream({ execute: async ({ writer }) => { + await writeAgentExecutionPrefaceMessage({ + writer, + chatId: id, + label: "agent:generate_image:preface", + friendlyMessage: smartAutoFriendlyMessage, + fallback: + directAgentToolTargetImageUrls.length > 0 + ? "收到,我会参考你选的图片来生成新画面,稍等一下。" + : "好的,我按你的描述来做一版画面,稍等我处理一下。", + }); writeAgentProgressChunk( writer, buildDirectAgentImageContextProgress({ @@ -7917,6 +7986,16 @@ export async function POST(request: Request) { ) { const directVideoStream = createUIMessageStream({ execute: async ({ writer }) => { + await writeAgentExecutionPrefaceMessage({ + writer, + chatId: id, + label: "agent:generate_video:preface", + friendlyMessage: smartAutoFriendlyMessage, + fallback: + directAgentToolTargetImageUrls.length > 0 + ? "收到,我会参考你选的画面来生成视频,稍等一下。" + : "好的,我按你的需求来做这段视频,稍等我处理一下。", + }); const assistantMessageId = generateUUID(); writeAgentProgressChunk( writer, @@ -8123,6 +8202,13 @@ export async function POST(request: Request) { const directToolLabel = getDirectAgentToolLabel(directAgentToolCapability); const directToolStream = createUIMessageStream({ execute: async ({ writer }) => { + await writeAgentExecutionPrefaceMessage({ + writer, + chatId: id, + label: `agent:${directAgentToolCapability}:preface`, + friendlyMessage: smartAutoFriendlyMessage, + fallback: `好的,我来帮你${directToolLabel},稍等我处理一下。`, + }); writeAgentProgressChunk( writer, buildDirectAgentImageContextProgress({ diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index a482b60f6..181ea13f9 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -12225,10 +12225,7 @@ export function CanvasChatPanel({ const isAgentTargetClarificationActive = shouldShowAgentTargetLockCard && activeAgentTargetLock?.stage === "clarify"; const shouldShowAgentProgressCard = - activeComposerMode === "agent" && - Boolean(activeAgentProgress) && - activeAgentProgress?.stage !== "completed" && - activeAgentProgress?.stage !== "failed"; + false; const agentTargetLockPreviewItems = useMemo(() => { if (!activeAgentTargetLock) return [] as AgentTargetLockRefPreview[]; const targets = Array.isArray(activeAgentTargetLock.targets) ? activeAgentTargetLock.targets : []; From 15f9e1910abea11a04a7c1338ebeb9a8648428d5 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 14:54:58 +0800 Subject: [PATCH 05/29] fix: stabilize canvas agent chat feedback --- components/canvas/CanvasChatPanel.tsx | 72 ++++++++++++-- .../runtime/direct-agent-response-builders.ts | 94 ++++++++++++++----- tests/routes/canvas-chat-helpers.test.ts | 26 +++++ 3 files changed, 162 insertions(+), 30 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 181ea13f9..b00a2649e 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -792,6 +792,8 @@ const CANVAS_AGENT_SECTION_TITLES = new Set([ "需求理解", CANVAS_IMAGE_ANALYSIS_TITLE, "执行计划", + "执行结果", + "后续操作", "优化后提示词", "输出设置", ]); @@ -2303,6 +2305,7 @@ export function CanvasChatPanel({ const [analysisCollapseState, setAnalysisCollapseState] = useState>({}); const [typedAssistantSections, setTypedAssistantSections] = useState>({}); const [activeTypingSections, setActiveTypingSections] = useState>({}); + const [agentTypewriterMessageIds, setAgentTypewriterMessageIds] = useState>({}); const [clawdTypewriterMessageIds, setClawdTypewriterMessageIds] = useState>({}); const [insufficientPointsState, setInsufficientPointsState] = useState<{ balance: number; @@ -6466,6 +6469,18 @@ export function CanvasChatPanel({ const normalizedAttachments = Array.isArray(messageData.attachments) ? messageData.attachments : []; + const appendedMessageId = String(messageData.id || "").trim(); + const appendedAssistantText = normalizedParts + .filter( + (part: any) => + part?.type === "text" && typeof part?.text === "string" + ) + .map((part: any) => String(part.text || "")) + .join("\n\n"); + const appendedAssistantVisibleText = normalizeCanvasAgentText( + stripCanvasModelRoutingLines(stripMediaMarkup(appendedAssistantText)) + .replace(//g, "") + ); const emptyNearestUserImageKeys = new Set(); const incomingImageUrls = normalizedParts.flatMap((part: any) => part?.type === "text" && typeof part?.text === "string" @@ -6525,6 +6540,18 @@ export function CanvasChatPanel({ if (!isEventForActiveChat) { return; } + + if ( + messageData.role === "assistant" && + appendedMessageId && + appendedAssistantVisibleText + ) { + setAgentTypewriterMessageIds((previousIds) => + previousIds[appendedMessageId] + ? previousIds + : { ...previousIds, [appendedMessageId]: true } + ); + } setMessages((prevMessages) => { const existingIndex = prevMessages.findIndex( @@ -6993,11 +7020,20 @@ export function CanvasChatPanel({ currentModelIdRef.current = selectedModelId; inFlightChatIdRef.current = activeChatId; inFlightRawChatIdRef.current = rawChatId; + const launchUserMessageId = generateUUID(); + const launchCreatedAt = new Date(); sendMessage({ + id: launchUserMessageId, role: "user", parts, - }); + createdAt: launchCreatedAt, + metadata: { + createdAt: launchCreatedAt.toISOString(), + composerMode: activeComposerModeRef.current || activeComposerMode, + modelId: selectedModelId, + }, + } as any); hasHydratedHistoryRef.current = true; pendingLaunchRef.current = null; @@ -7010,7 +7046,7 @@ export function CanvasChatPanel({ if (editableDiv) { editableDiv.innerHTML = ""; } - }, [activeChatId, rawChatId, selectedModelId, status, sendMessage, clearSelection, launchAutoSendTick]); + }, [activeChatId, rawChatId, selectedModelId, status, sendMessage, clearSelection, launchAutoSendTick, activeComposerMode]); // 当历史消息加载完成后,更新消息列表(支持同一会话的增量刷新) const loadedHistorySignatureRef = useRef(""); @@ -10821,6 +10857,20 @@ export function CanvasChatPanel({ !shouldTreatAsCanvasAgentControlIntent && effectiveComposerMode === "image" && Boolean(requestModel && isCanvasImageModel(requestModel)); + const userMessageId = generateUUID(); + const latestMessageTimestamp = messages.reduce( + (latest, message) => Math.max(latest, getMessageTimestamp(message) ?? 0), + 0 + ); + const optimisticCreatedAt = new Date( + Math.max(Date.now(), latestMessageTimestamp + 1) + ); + const optimisticUserMetadata = { + createdAt: optimisticCreatedAt.toISOString(), + composerMode: effectiveComposerMode, + agentEntryMode: effectiveAgentEntryMode, + modelId: effectiveModelId, + }; // 🆕 隐藏提示词(不在 UI 中展示) const hiddenSegments: string[] = []; @@ -10933,9 +10983,12 @@ export function CanvasChatPanel({ // 使用与 multimodal-input 相同的格式发送消息 try { sendMessage({ + id: userMessageId, role: "user", parts: parts, - }); + createdAt: optimisticCreatedAt, + metadata: optimisticUserMetadata, + } as any); } catch (error) { releaseSendGuard(activeChatId); if (shouldShowOptimisticImageGeneration) { @@ -11019,6 +11072,7 @@ export function CanvasChatPanel({ markSessionClawdSkillTagPromptApplied, buildHistoryMessagesUrl, workflowContext, + messages, ]); const handleOpenClawQuickAction = useCallback( @@ -12953,6 +13007,11 @@ export function CanvasChatPanel({ const shouldTypeClawAssistantMessage = message.role === "assistant" && Boolean(clawdTypewriterMessageIds[message.id]); + const shouldTypeAgentAssistantMessage = + message.role === "assistant" && + Boolean(agentTypewriterMessageIds[message.id]); + const shouldForceTypeAssistantMessage = + shouldTypeClawAssistantMessage || shouldTypeAgentAssistantMessage; const isClawAssistantMessage = message.role === "assistant" && (isClawdMode || isClawdChatMessage(message)); @@ -13161,16 +13220,16 @@ export function CanvasChatPanel({ !typedAssistantSections[analysisTypingKey] && ((shouldTypeAssistantMessage && !hasCanvasRenderableMarkdown(analysisSection?.analysis || "")) || - shouldTypeClawAssistantMessage); + shouldForceTypeAssistantMessage); const shouldAnimatePlainText = !analysisSection && Boolean(plainText) && !typedAssistantSections[plainTextTypingKey] && ((shouldTypeAssistantMessage && !hasCanvasRenderableMarkdown(plainText)) || - shouldTypeClawAssistantMessage); + shouldForceTypeAssistantMessage); const shouldDeferAssistantMedia = - isClawAssistantMessage && + (isClawAssistantMessage || shouldTypeAgentAssistantMessage) && (shouldAnimateAnalysis || shouldAnimatePlainText); const visibleImageUrls = shouldDeferAssistantMedia ? [] @@ -13182,6 +13241,7 @@ export function CanvasChatPanel({ !isDetailGenerationMode && !isClawAssistantMessage && visibleImageUrls.length > 0 && + !plainText.trim() && !plainText.includes(CANVAS_IMAGE_DONE_SUMMARY) && !isLatestAssistantDuringGeneration; const renderPlainText = (text: string, key: string) => ( diff --git a/lib/ai/runtime/direct-agent-response-builders.ts b/lib/ai/runtime/direct-agent-response-builders.ts index c1b349c86..0576f56d1 100644 --- a/lib/ai/runtime/direct-agent-response-builders.ts +++ b/lib/ai/runtime/direct-agent-response-builders.ts @@ -10,6 +10,56 @@ import { type DirectAgentToolCapability, } from "@/lib/ai/runtime/direct-agent-execution"; +function normalizeDirectAgentResultSentence(value: string) { + const normalized = String(value || "") + .replace(/结果如下[::]?\s*$/u, "") + .replace(/[,,。::]\s*$/u, "") + .trim(); + return normalized || "已完成处理"; +} + +function buildDirectAgentResultCard(params: { + result: string; + mediaMarkdown?: string | null; + followUp: string; +}) { + return [ + "### 执行结果", + `- ${normalizeDirectAgentResultSentence(params.result)},结果如下。`, + params.mediaMarkdown, + "### 后续操作", + `- ${params.followUp}`, + ] + .filter(Boolean) + .join("\n\n"); +} + +function getDirectAgentFollowUpMessage(capability: DirectAgentToolCapability) { + switch (capability) { + case "remove_background": + return "如需微调边缘、替换背景或继续合成,可以直接告诉我。"; + case "remove_watermark": + return "如需继续修补局部痕迹或统一画面质感,可以直接告诉我。"; + case "enhance": + return "如需继续调整清晰度、色彩或细节强度,可以直接告诉我。"; + case "resize": + return "如需继续改尺寸、比例或输出规格,可以直接告诉我。"; + case "extend": + return "如需继续扩展画面、调整构图或补充边缘内容,可以直接告诉我。"; + case "angle_variant": + return "如需继续换角度、换机位或统一系列视角,可以直接告诉我。"; + case "local_edit": + case "box_cutout": + return "如需继续修改局部、替换元素或细化边缘,可以直接告诉我。"; + case "generate_video": + return "如需继续调整镜头、节奏、比例或时长,可以直接告诉我。"; + case "generate_image": + case "generic_edit": + default: + return "如需继续调整风格、构图、主体细节或尺寸,可以直接告诉我。"; + } +} + export function buildDirectAgentAnalysisAssistantText(params: { summary: string; answer?: string | null; @@ -32,12 +82,11 @@ export function buildDirectAgentImageGenerationAssistantText(params: { modelDisplayName?: string | null; }) { return prependImageModelBadge( - [ - getDirectAgentToolSuccessMessage("generate_image"), - params.imageMarkdown, - ] - .filter(Boolean) - .join("\n\n"), + buildDirectAgentResultCard({ + result: getDirectAgentToolSuccessMessage("generate_image"), + mediaMarkdown: params.imageMarkdown, + followUp: getDirectAgentFollowUpMessage("generate_image"), + }), params.modelDisplayName, ); } @@ -47,12 +96,11 @@ export function buildDirectAgentVideoGenerationAssistantText(params: { modelDisplayName?: string | null; }) { return prependImageModelBadge( - [ - getDirectAgentToolSuccessMessage("generate_video"), - buildAgentToolVideoMarkdown(params.videoUrl), - ] - .filter(Boolean) - .join("\n\n"), + buildDirectAgentResultCard({ + result: getDirectAgentToolSuccessMessage("generate_video"), + mediaMarkdown: buildAgentToolVideoMarkdown(params.videoUrl), + followUp: getDirectAgentFollowUpMessage("generate_video"), + }), params.modelDisplayName, ); } @@ -64,16 +112,15 @@ export function buildDirectAgentImageEditAssistantText(params: { imageSize?: string; }) { return prependImageModelBadge( - [ - getDirectAgentToolSuccessMessage(params.capability), - buildAgentToolImageMarkdown({ + buildDirectAgentResultCard({ + result: getDirectAgentToolSuccessMessage(params.capability), + mediaMarkdown: buildAgentToolImageMarkdown({ originalUrl: params.originalUrl, thumbnailUrl: params.thumbnailUrl, imageSize: params.imageSize, }), - ] - .filter(Boolean) - .join("\n\n"), + followUp: getDirectAgentFollowUpMessage(params.capability), + }), getDirectAgentToolLabel(params.capability), ); } @@ -87,12 +134,11 @@ export function buildDirectAgentBatchImageEditAssistantText(params: { }>; }) { return prependImageModelBadge( - [ - getDirectAgentToolSuccessMessage(params.capability), - buildAgentToolImagesMarkdown(params.results), - ] - .filter(Boolean) - .join("\n\n"), + buildDirectAgentResultCard({ + result: getDirectAgentToolSuccessMessage(params.capability), + mediaMarkdown: buildAgentToolImagesMarkdown(params.results), + followUp: getDirectAgentFollowUpMessage(params.capability), + }), getDirectAgentToolLabel(params.capability), ); } diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index 6edd96b14..c4d257b53 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -131,6 +131,10 @@ import { resolveDirectAgentToolExecution, shouldRunDirectAgentBatchImageEdit, } from "@/lib/ai/runtime/direct-agent-execution"; +import { + buildDirectAgentImageEditAssistantText, + buildDirectAgentImageGenerationAssistantText, +} from "@/lib/ai/runtime/direct-agent-response-builders"; import { inferAngleEditOptionsFromText } from "@/lib/ai/runtime/angle-edit-options"; import { hasDirectAgentLocalEditIntent, @@ -1179,6 +1183,28 @@ test.describe("canvas chat pure helpers", () => { ); }); + test("formats direct agent image results as structured markdown cards", () => { + const generatedText = buildDirectAgentImageGenerationAssistantText({ + imageMarkdown: "![生成结果](https://cdn.example.com/generated.png)", + modelDisplayName: "Test Image Model", + }); + + expect(generatedText).toContain("### 执行结果"); + expect(generatedText).toContain("- 已完成图片生成,结果如下。"); + expect(generatedText).toContain("![生成结果](https://cdn.example.com/generated.png)"); + expect(generatedText).toContain("### 后续操作"); + + const editText = buildDirectAgentImageEditAssistantText({ + capability: "remove_background", + originalUrl: "https://cdn.example.com/cutout.png", + }); + + expect(editText).toContain("### 执行结果"); + expect(editText).toContain("- 已完成抠图处理,结果如下。"); + expect(editText).toContain("https://cdn.example.com/cutout.png"); + expect(editText).toContain("替换背景"); + }); + test("only runs direct image edit batches for explicit safe batch requests", () => { expect( shouldRunDirectAgentBatchImageEdit({ From 610d2aed9b35ce8b9c9c6b3630f877b7a6dc37b2 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 15:17:43 +0800 Subject: [PATCH 06/29] feat: add canvas agent orchestration kernel --- app/(chat)/api/chat/route.ts | 14 +- components/canvas/CanvasChatPanel.tsx | 28 ++-- lib/ai/context-memory/target-resolution.ts | 53 +++++-- lib/ai/runtime/canvas-agent-kernel.ts | 156 +++++++++++++++++++++ lib/ai/runtime/intent-arbiter.ts | 28 ++-- tests/routes/canvas-chat-helpers.test.ts | 94 +++++++++++++ 6 files changed, 338 insertions(+), 35 deletions(-) create mode 100644 lib/ai/runtime/canvas-agent-kernel.ts diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index df38dbc43..c3be7a608 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -262,6 +262,7 @@ import { recordProviderHealthSuccess, shouldAvoidProvider, } from "@/lib/ai/runtime/provider-health"; +import { resolveCanvasAgentRequestPolicy } from "@/lib/ai/runtime/canvas-agent-kernel"; import { arbitrateAgentIntent } from "@/lib/ai/runtime/intent-arbiter"; import { buildAgentRoleIdentityInstruction } from "@/lib/ai/runtime/agent-role-profile"; import { getVideoStoryboardConfig } from "@/lib/video-agent/config"; @@ -1095,8 +1096,19 @@ export async function POST(request: Request) { const shouldRespectDirectComposerMode = composerMode === "image" || composerMode === "video" || composerMode === "detail"; const shouldIsolateDirectComposerContext = shouldRespectDirectComposerMode; - let shouldRunAgentConversation = finalModelId === "auto"; + const requestPolicy = resolveCanvasAgentRequestPolicy({ + composerMode, + agentEntryMode: agentPresetId ? "preset" : "auto", + selectedChatModel: finalModelId, + hasCanvasControlIntentFastPath, + }); + finalModelId = requestPolicy.effectiveSelectedChatModel; + let shouldRunAgentConversation = + finalModelId === "auto" || requestPolicy.shouldForceToolOrchestration; let shouldKeepSelectedModel = false; + if (requestPolicy.reason === "agent_auto_composer") { + chatApiLogger.info("[Smart Auto Mode] 🧭 Agent composer forces tool orchestration, ignoring stale selected model"); + } if (shouldRespectDirectComposerMode && shouldRunAgentConversation) { shouldRunAgentConversation = false; chatApiLogger.info(`[Smart Auto Mode] ⛳ Direct composer mode (${composerMode}) disables initial auto-agent routing`); diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index b00a2649e..0c1439f39 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -77,6 +77,7 @@ import { getImageCreditCostFromConfig, getImageModelCreditDiscountLabel, } from "@/lib/ai/image-model-pricing"; +import { resolveCanvasAgentRequestPolicy } from "@/lib/ai/runtime/canvas-agent-kernel"; import { getVideoToolOptionsForMode } from "@/lib/ai/video-tool-capability"; import type { ChatMessage } from "@/lib/types"; import type { @@ -5352,14 +5353,8 @@ export function CanvasChatPanel({ } if (mode === "agent") { - const preferredAgentModelId = - allModels.find( - (model) => - model.id === lastConversationModelId && - isCanvasConversationOnlyModel(model) - )?.id || "auto"; - currentModelIdRef.current = preferredAgentModelId; - setSelectedModelId(preferredAgentModelId); + currentModelIdRef.current = "auto"; + setSelectedModelId("auto"); setIsDetailGenerationMode(false); return targetChatSessionId; } @@ -6160,7 +6155,15 @@ export function CanvasChatPanel({ const hiddenPrompt = hiddenPromptRef.current || undefined; const autoContext = autoContextRef.current || undefined; const contextPayload = capturedContextPayload; - const requestModel = allModels.find((model) => model.id === currentModelIdRef.current); + const requestPolicy = resolveCanvasAgentRequestPolicy({ + composerMode: effectiveComposerMode, + agentEntryMode: effectiveAgentEntryMode, + selectedChatModel: currentModelIdRef.current, + }); + const effectiveSelectedChatModel = requestPolicy.effectiveSelectedChatModel; + const requestModel = allModels.find( + (model) => model.id === effectiveSelectedChatModel + ); const requestIsVideoModel = isCanvasVideoModel(requestModel); const requestIsConversationModel = isCanvasConversationOnlyModel(requestModel); hiddenPromptRef.current = null; @@ -6177,10 +6180,13 @@ export function CanvasChatPanel({ selectedAgentPreset?.id ? selectedAgentPreset.id : undefined, - selectedChatModel: currentModelIdRef.current, + selectedChatModel: effectiveSelectedChatModel, composerMode: effectiveComposerMode, selectedVisibilityType: "private", - deepThinkingEnabled: requestIsConversationModel + deepThinkingEnabled: + effectiveComposerMode === "agent" + ? undefined + : requestIsConversationModel ? false : requestIsVideoModel || currentModelIdRef.current === "auto" ? undefined diff --git a/lib/ai/context-memory/target-resolution.ts b/lib/ai/context-memory/target-resolution.ts index e0d8f8064..6c69dd7ef 100644 --- a/lib/ai/context-memory/target-resolution.ts +++ b/lib/ai/context-memory/target-resolution.ts @@ -5,16 +5,17 @@ import type { ResolvedImageRef, ResolvedTargetAssets, } from "@/lib/ai/context-memory/types"; +import { + hasCanvasAgentActionableImageEditIntent, + hasCanvasAgentDeicticTarget, + resolveCanvasAgentTargetPreference, +} from "@/lib/ai/runtime/canvas-agent-kernel"; const ORIGINAL_IMAGE_REGEX = /(原图|上传图|参考图|最初那张|第一张图|素材图|源图|原始图片|原始那张|我发的那张|上传的那张|原来的图)/i; const LATEST_RESULT_REGEX = /(上一张|上一轮|刚生成|最新生成|这个结果|该结果|按这个结果|继续在这张|基于这张结果|延续上一次结果|上一版|刚才那张结果|生成的图|生成图|结果图|出图结果|刚出的图|上一张生成图|上一轮结果图|现在这张生成图)/i; -const DEICTIC_TARGET_REGEX = - /(这张图|这只|这个|这款|这套|当前这张|当前这个|当前这只|这一张|这一只|这个产品|这个物体|这只猫|这只狗)/i; const SELECTION_REGEX = /(选中的|当前这张|我选的|这几张|这些图|选中图)/i; -const ACTIONABLE_EDIT_REGEX = - /(改|调整|优化|换|替换|去掉|抠|重绘|增强|修|处理|按照|按|保留|统一|色差|背景|清晰|风格|亮一点|暗一点|白底|透明底)/i; const ACTIONABLE_GENERATION_REGEX = /(生图|生成|画一张|出图|来一张|再来一张|做一张|做图|做视频|视频生成|生成视频|动起来)/i; const IMPLICIT_HISTORY_TARGET_REGEX = @@ -255,6 +256,7 @@ export function resolveTargetAssets( const focusPolicy = params.contextPayload?.focusPolicy || "auto"; const workingStateGeneratedUrls = normalizeStringArray(workingState?.lastGeneratedImageUrls); const workingStateUploadedUrls = normalizeStringArray(workingState?.lastUploadedImageUrls); + const workingStateResolvedUrls = normalizeStringArray(workingState?.lastResolvedTargetImageUrls); const generatedRefs = workingStateGeneratedUrls.length > 0 ? toWorkingMemoryRefs(workingStateGeneratedUrls) : assistantRefs; const originalRefs = @@ -384,7 +386,39 @@ export function resolveTargetAssets( }); } - if (DEICTIC_TARGET_REGEX.test(text)) { + const canvasAgentTargetPreference = resolveCanvasAgentTargetPreference({ + text, + selectedImageCount: selectedRefs.length, + latestResultImageCount: generatedRefs.length, + workingMemoryTargetImageCount: workingStateResolvedUrls.length, + }); + if (canvasAgentTargetPreference.shouldPreferLatestResult) { + return buildResolvedTargetAssets({ + targetRefs: generatedRefs, + candidateRefs, + resolutionMode: + workingStateGeneratedUrls.length > 0 ? "working_memory" : "latest_result", + confidence: canvasAgentTargetPreference.confidence, + needsClarification: false, + reason: "用户使用指代表达并提出图片编辑意图,默认续接最近生成结果", + fromHistory: true, + }); + } + + if (canvasAgentTargetPreference.shouldPreferWorkingMemoryTarget) { + const refs = toWorkingMemoryRefs(workingStateResolvedUrls); + return buildResolvedTargetAssets({ + targetRefs: refs, + candidateRefs, + resolutionMode: "working_memory", + confidence: canvasAgentTargetPreference.confidence, + needsClarification: false, + reason: "用户使用指代表达并提出图片编辑意图,使用工作记忆中的上一轮目标图", + fromHistory: true, + }); + } + + if (hasCanvasAgentDeicticTarget(text)) { if (selectedRefs.length > 0) { return buildResolvedTargetAssets({ targetRefs: selectedRefs, @@ -421,7 +455,7 @@ export function resolveTargetAssets( } if ( - ACTIONABLE_EDIT_REGEX.test(text) && + hasCanvasAgentActionableImageEditIntent(text) && currentRefs.length === 0 && generatedRefs.length > 0 && selectedLooksLikeOriginal && @@ -463,14 +497,13 @@ export function resolveTargetAssets( }); } - const workingStateResolvedUrls = normalizeStringArray(workingState?.lastResolvedTargetImageUrls); const allowsImplicitHistoryTarget = IMPLICIT_HISTORY_TARGET_REGEX.test(text) && - (ACTIONABLE_EDIT_REGEX.test(text) || + (hasCanvasAgentActionableImageEditIntent(text) || ACTIONABLE_GENERATION_REGEX.test(text) || LATEST_RESULT_REGEX.test(text) || ORIGINAL_IMAGE_REGEX.test(text) || - DEICTIC_TARGET_REGEX.test(text) || + hasCanvasAgentDeicticTarget(text) || SELECTION_REGEX.test(text)); if (allowsImplicitHistoryTarget) { @@ -525,7 +558,7 @@ export function resolveTargetAssets( } } - if (ACTIONABLE_EDIT_REGEX.test(text)) { + if (hasCanvasAgentActionableImageEditIntent(text)) { return buildResolvedTargetAssets({ targetRefs: [], candidateRefs, diff --git a/lib/ai/runtime/canvas-agent-kernel.ts b/lib/ai/runtime/canvas-agent-kernel.ts new file mode 100644 index 000000000..68467384f --- /dev/null +++ b/lib/ai/runtime/canvas-agent-kernel.ts @@ -0,0 +1,156 @@ +import type { DirectAgentToolCapability } from "@/lib/ai/runtime/direct-agent-execution"; + +export type CanvasAgentComposerMode = "agent" | "image" | "video" | "detail" | "clawd"; +export type CanvasAgentEntryMode = "auto" | "preset"; + +export interface CanvasAgentRequestPolicy { + effectiveSelectedChatModel: string; + shouldForceToolOrchestration: boolean; + reason: string | null; +} + +export interface CanvasAgentTargetPreference { + shouldPreferLatestResult: boolean; + shouldPreferWorkingMemoryTarget: boolean; + confidence: number; + reason: string | null; +} + +const DEICTIC_TARGET_REGEX = + /(这张图|这只|这个|这款|这套|当前这张|当前这个|当前这只|这一张|这一只|这个产品|这个物体|这只猫|这只狗)/i; + +const ACTIONABLE_IMAGE_EDIT_REGEX = + /(抠图|去背景|透明背景|去背|扣图|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|调色|调整颜色|亮度|对比度|饱和度|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调|处理)/i; + +export function normalizeCanvasAgentRequestText(text: string) { + return String(text || "").toLowerCase().replace(/\s+/g, "").trim(); +} + +export function hasCanvasAgentDeicticTarget(text: string) { + return DEICTIC_TARGET_REGEX.test(String(text || "")); +} + +export function hasCanvasAgentActionableImageEditIntent(text: string) { + return ACTIONABLE_IMAGE_EDIT_REGEX.test(String(text || "")); +} + +export function inferCanvasAgentImageEditCapability( + text: string, +): DirectAgentToolCapability | null { + const normalizedText = normalizeCanvasAgentRequestText(text); + if (!normalizedText) return null; + if (/去水印|水印|去logo|移除logo|去除logo/.test(normalizedText)) { + return "remove_watermark"; + } + if (/抠图|去背景|透明背景|去背|扣图|移除背景/.test(normalizedText)) { + return "remove_background"; + } + if (/多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位/.test(normalizedText)) { + return "angle_variant"; + } + if (/扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|比例|画幅|竖版|横版|竖图|横图|9:16|16:9|1:1/.test(normalizedText)) { + return "extend"; + } + if (/调整尺寸|裁剪|resize|crop|缩放|放大|缩小/.test(normalizedText)) { + return "resize"; + } + if (/局部|框选|选区|区域|涂抹|蒙版/.test(normalizedText)) { + return "local_edit"; + } + if (/高清|清晰|锐化|降噪|提升质量|修复|清晰化/.test(normalizedText)) { + return "enhance"; + } + if (hasCanvasAgentActionableImageEditIntent(text)) { + return "generic_edit"; + } + return null; +} + +export function resolveCanvasAgentRequestPolicy(params: { + composerMode?: string | null; + agentEntryMode?: string | null; + selectedChatModel?: string | null; + hasCanvasControlIntentFastPath?: boolean; +}): CanvasAgentRequestPolicy { + const composerMode = String(params.composerMode || "").trim(); + const agentEntryMode = String(params.agentEntryMode || "").trim(); + const selectedChatModel = String(params.selectedChatModel || "").trim() || "auto"; + const isAgentAutoComposer = composerMode === "agent" && agentEntryMode !== "preset"; + const shouldForceToolOrchestration = + isAgentAutoComposer || Boolean(params.hasCanvasControlIntentFastPath); + + if (isAgentAutoComposer) { + return { + effectiveSelectedChatModel: "auto", + shouldForceToolOrchestration: true, + reason: "agent_auto_composer", + }; + } + + if (params.hasCanvasControlIntentFastPath) { + return { + effectiveSelectedChatModel: selectedChatModel, + shouldForceToolOrchestration: true, + reason: "canvas_control_fast_path", + }; + } + + return { + effectiveSelectedChatModel: selectedChatModel, + shouldForceToolOrchestration, + reason: null, + }; +} + +export function resolveCanvasAgentTargetPreference(params: { + text: string; + selectedImageCount: number; + latestResultImageCount: number; + workingMemoryTargetImageCount: number; +}): CanvasAgentTargetPreference { + const hasDeicticTarget = hasCanvasAgentDeicticTarget(params.text); + const hasEditIntent = hasCanvasAgentActionableImageEditIntent(params.text); + const selectedImageCount = Math.max(0, Math.round(params.selectedImageCount || 0)); + const latestResultImageCount = Math.max( + 0, + Math.round(params.latestResultImageCount || 0), + ); + const workingMemoryTargetImageCount = Math.max( + 0, + Math.round(params.workingMemoryTargetImageCount || 0), + ); + + if (!hasDeicticTarget || !hasEditIntent || selectedImageCount > 0) { + return { + shouldPreferLatestResult: false, + shouldPreferWorkingMemoryTarget: false, + confidence: 0, + reason: null, + }; + } + + if (latestResultImageCount > 0) { + return { + shouldPreferLatestResult: true, + shouldPreferWorkingMemoryTarget: false, + confidence: 90, + reason: "deictic_edit_prefers_latest_result", + }; + } + + if (workingMemoryTargetImageCount > 0) { + return { + shouldPreferLatestResult: false, + shouldPreferWorkingMemoryTarget: true, + confidence: 86, + reason: "deictic_edit_uses_working_memory_target", + }; + } + + return { + shouldPreferLatestResult: false, + shouldPreferWorkingMemoryTarget: false, + confidence: 0, + reason: null, + }; +} diff --git a/lib/ai/runtime/intent-arbiter.ts b/lib/ai/runtime/intent-arbiter.ts index cfd463d3b..ce1081ef1 100644 --- a/lib/ai/runtime/intent-arbiter.ts +++ b/lib/ai/runtime/intent-arbiter.ts @@ -5,6 +5,10 @@ import type { ResolvedTargetAssets } from "@/lib/ai/context-memory/types"; import type { AnalysisResult } from "@/lib/ai/smart-analyzer"; import type { TaskBoundaryDecision } from "@/lib/ai/runtime/task-boundary-classifier"; import { hasDirectAgentLocalEditIntent } from "@/lib/ai/runtime/local-edit-options"; +import { + hasCanvasAgentActionableImageEditIntent, + inferCanvasAgentImageEditCapability, +} from "@/lib/ai/runtime/canvas-agent-kernel"; export type IntentArbiterMode = | "respond" @@ -116,23 +120,21 @@ function isExplicitImageGenerationRequest(text: string): boolean { } function isLikelyImageEditRequest(text: string): boolean { - const normalizedText = String(text || "").toLowerCase(); - return hasDirectAgentLocalEditIntent(text) || /抠图|去背景|透明背景|去背|扣图|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|换成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|改成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|比例|画幅|竖版|横版|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|转.*风格|变.*风格|改.*风格|调色|调整颜色|亮度|对比度|饱和度|色调|曝光|滤镜|改成.*色|换成.*色|变成.*色|颜色改成|颜色换成|颜色变成|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调/.test( - normalizedText, - ); + return hasDirectAgentLocalEditIntent(text) || hasCanvasAgentActionableImageEditIntent(text); } function inferDefaultImageEditSubIntent(text: string): string { - const lowerText = String(text || "").toLowerCase(); - if (/去水印|水印|去logo|去\s*logo|移除logo|去除logo/.test(lowerText)) return "remove_watermark"; - if (/抠图|去背景|透明背景|去背|扣图|移除背景/.test(lowerText)) return "remove_background"; - if (/换背景|改背景|背景换成|背景改成|白底|透明底/.test(lowerText)) return "replace_background"; - if (/多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位/.test(lowerText)) return "angle_variant"; + const inferredCapability = inferCanvasAgentImageEditCapability(text); + if ( + inferredCapability && + inferredCapability !== "generic_edit" && + inferredCapability !== "generate_image" && + inferredCapability !== "generate_video" && + inferredCapability !== "analyze" + ) { + return inferredCapability; + } if (hasDirectAgentLocalEditIntent(text)) return "local_edit"; - if (/扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|比例|画幅|竖版|横版|竖图|横图|9:16|16:9|1:1/.test(lowerText)) return "extend"; - if (/风格|卡通|动漫|油画|像素风|写实|插画/.test(lowerText)) return "style_transfer"; - if (/颜色|调色|亮度|对比度|饱和度|改成.*色|换成.*色/.test(lowerText)) return "color_adjust"; - if (/去除|消除|擦掉|删除|移除|p掉|重绘/.test(lowerText)) return "inpaint"; return "enhance"; } diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index c4d257b53..1ed8f6a5a 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -45,6 +45,10 @@ import { } from "@/lib/canvas-toolbar-config"; import { shouldBypassCanvasAgentMissingTargetClarification } from "@/lib/ai/runtime/canvas-agent-clarification"; import { hasCanvasAgentRoutingContext } from "@/lib/ai/canvas-agent-routing"; +import { + resolveCanvasAgentRequestPolicy, + resolveCanvasAgentTargetPreference, +} from "@/lib/ai/runtime/canvas-agent-kernel"; import { inferAgentImageCountFromText } from "@/lib/ai/runtime/image-count-intent"; import { isAgentModeScopedChatId, @@ -128,6 +132,7 @@ import { getDirectAgentToolSuccessMessage, hasExplicitDirectAgentBatchImageEditIntent, isDirectAgentBatchImageEditCapability, + resolveDirectAgentToolContext, resolveDirectAgentToolExecution, shouldRunDirectAgentBatchImageEdit, } from "@/lib/ai/runtime/direct-agent-execution"; @@ -1205,6 +1210,95 @@ test.describe("canvas chat pure helpers", () => { expect(editText).toContain("替换背景"); }); + test("resolves deictic canvas edit requests to latest results and direct tools", () => { + const latestResultUrl = "https://cdn.example.com/latest-cat-result.png"; + const requestPolicy = resolveCanvasAgentRequestPolicy({ + composerMode: "agent", + selectedChatModel: "conversation-model-id", + }); + + expect(requestPolicy.effectiveSelectedChatModel).toBe("auto"); + expect(requestPolicy.shouldForceToolOrchestration).toBe(true); + + const targetPreference = resolveCanvasAgentTargetPreference({ + text: "将这只猫从图中扣图扣出来", + selectedImageCount: 0, + latestResultImageCount: 1, + workingMemoryTargetImageCount: 1, + }); + + expect(targetPreference.shouldPreferLatestResult).toBe(true); + + const mediaInput = { + imageRefs: [], + currentMessageImageRefs: [], + selectedImageRefs: [], + canvasImageRefs: [], + historyUserImageRefs: [], + historyAssistantImageRefs: [ + { + url: latestResultUrl, + normalizedUrl: latestResultUrl, + source: "history_assistant_result", + role: "history_result", + }, + ], + resolvedImageRefs: [], + currentMessageImageUrls: [], + selectedImageUrls: [], + historyUserImageUrls: [], + historyAssistantImageUrls: [latestResultUrl], + resolvedImageUrls: [latestResultUrl], + selectedAssetIds: [], + candidateAssetIds: [], + uploadedAssetIds: [], + hasImage: true, + source: "history", + fromHistory: true, + } as any; + const workingState = { + lastGeneratedImageUrls: [latestResultUrl], + lastResolvedTargetImageUrls: [latestResultUrl], + }; + const targetResolution = { + targetRefs: [], + candidateRefs: [], + targetImageUrls: [latestResultUrl], + targetAssetIds: [], + candidateImageUrls: [], + candidateAssetIds: [], + resolutionMode: "working_memory", + confidence: targetPreference.confidence, + needsClarification: false, + reason: targetPreference.reason, + fromHistory: true, + } as any; + + const directContext = resolveDirectAgentToolContext({ + execution: { + mode: "edit_image", + routeIntent: "image_edit", + routeSubIntent: "remove_background", + targetSource: targetResolution.resolutionMode, + preferredCapability: "remove_background", + shouldUseStructuredReply: true, + shouldOptimizePrompt: true, + shouldApplyImagePipeline: true, + shouldApplyVideoPipeline: false, + shouldStayConversational: false, + shouldPublishToCanvas: false, + toolCalls: [], + availableTools: ["removeBackground"], + } as any, + requestResolvedMediaInput: mediaInput, + requestTargetResolution: targetResolution, + requestWorkingState: workingState, + }); + + expect(directContext?.execution.toolName).toBe("removeBackground"); + expect(directContext?.targetImageUrl).toBe(latestResultUrl); + }); + test("only runs direct image edit batches for explicit safe batch requests", () => { expect( shouldRunDirectAgentBatchImageEdit({ From f88ada378e79a29dedb1c17b40a72ea491f1bbfb Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 15:42:54 +0800 Subject: [PATCH 07/29] feat: add canvas agent progress timeline --- components/canvas/CanvasChatPanel.tsx | 165 ++++++++++++++---- .../canvas/chat-panel/canvas-agent-stream.ts | 111 +++++++++++- tests/routes/canvas-chat-helpers.test.ts | 40 +++++ 3 files changed, 282 insertions(+), 34 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 0c1439f39..d5e82e3d0 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -144,15 +144,16 @@ import { type CanvasToolbarItemKey, } from "@/lib/canvas-toolbar-config"; import { - AGENT_PROGRESS_STEPS, type AgentProgressStreamPayload, type AgentTargetLockRefPreview, type AgentTargetLockStreamPayload, + buildAgentProgressNodeSteps, type CanvasOperationStreamPayload, type CanvasViewOperationStreamPayload, type CanvasMediaStreamPayload, filterCanvasMediaPayloadForUnhandledItems, getAgentProgressFallbackTitle, + getAgentProgressStepLabel, getAgentTargetLockTitle, getAgentTargetResolutionLabel, getCanvasMediaPayloadHandledItemIds, @@ -1623,6 +1624,130 @@ function CanvasAssistantTypingPlaceholder({ hint }: { hint?: string | null }) { ); } +function CanvasAgentProgressTimeline({ + progress, +}: { + progress?: AgentProgressStreamPayload | null; +}) { + const steps = buildAgentProgressNodeSteps(progress); + const title = progress?.title?.trim() || getAgentProgressFallbackTitle(progress); + const isFailed = progress?.stage === "failed"; + const isCompleted = progress?.stage === "completed"; + const isClarify = progress?.stage === "clarify"; + + return ( +
+
+
+ + {isFailed ? ( + + ) : isCompleted ? ( + + ) : ( + + )} + + + {title} + +
+ +
+
+ {steps.map((step, index) => { + const isStepCompleted = step.state === "completed"; + const isStepCurrent = step.state === "current"; + const isStepFailed = step.state === "failed"; + const lineIsActive = + isStepCompleted || isStepCurrent || isStepFailed; + + return ( +
+
+ + {isStepCompleted ? ( + + ) : isStepFailed ? ( + + ) : isStepCurrent ? ( + + ) : ( + + )} + {isStepCurrent ? ( + + ) : null} + + + {step.label} + +
+ {index < steps.length - 1 ? ( + + ) : null} +
+ ); + })} +
+
+
+
+ ); +} + function CanvasComposerUploadProgressDialog({ progress, }: { @@ -12318,26 +12443,10 @@ export function CanvasChatPanel({ activeAgentProgress?.title?.trim() || getAgentProgressFallbackTitle(activeAgentProgress); const agentProgressMessage = activeAgentProgress?.message?.trim() || "我正在根据当前上下文持续推进这一步。"; - const agentProgressSteps = useMemo(() => { - const currentStepIndex = Math.max( - 0, - AGENT_PROGRESS_STEPS.findIndex((step) => step.key === activeAgentProgress?.currentStep) - ); - return AGENT_PROGRESS_STEPS.map((step, index) => { - let state: "upcoming" | "current" | "completed" | "failed" = "upcoming"; - if (activeAgentProgress?.stage === "failed") { - state = index < currentStepIndex ? "completed" : index === currentStepIndex ? "failed" : "upcoming"; - } else if (activeAgentProgress?.stage === "completed") { - state = "completed"; - } else { - state = index < currentStepIndex ? "completed" : index === currentStepIndex ? "current" : "upcoming"; - } - return { - ...step, - state, - }; - }); - }, [activeAgentProgress]); + const agentProgressSteps = useMemo( + () => buildAgentProgressNodeSteps(activeAgentProgress), + [activeAgentProgress] + ); const renderModelSelectContent = () => ( -
- - 分析中 -
- + )}
@@ -14660,9 +14764,10 @@ export function CanvasChatPanel({ {agentProgressTitle} - {AGENT_PROGRESS_STEPS.find( - (step) => step.key === activeAgentProgress.currentStep - )?.label || "处理中"} + {getAgentProgressStepLabel( + activeAgentProgress.currentStep || "lock_target", + activeAgentProgress + )}
diff --git a/components/canvas/chat-panel/canvas-agent-stream.ts b/components/canvas/chat-panel/canvas-agent-stream.ts index 3e2480894..e7a6246a2 100644 --- a/components/canvas/chat-panel/canvas-agent-stream.ts +++ b/components/canvas/chat-panel/canvas-agent-stream.ts @@ -206,14 +206,26 @@ export type AgentProgressStreamPayload = { capability?: string; }; +export type AgentProgressStepState = + | "upcoming" + | "current" + | "completed" + | "failed"; + +export type AgentProgressNodeStep = { + key: NonNullable; + label: string; + state: AgentProgressStepState; +}; + export const AGENT_PROGRESS_STEPS: Array<{ key: NonNullable; label: string; }> = [ - { key: "lock_target", label: "整理素材" }, - { key: "analyze", label: "理解需求" }, - { key: "select_tool", label: "优化提示" }, - { key: "execute", label: "提交生成" }, + { key: "lock_target", label: "理解用户需求" }, + { key: "analyze", label: "分析使用工具" }, + { key: "select_tool", label: "确认执行工具" }, + { key: "execute", label: "执行中" }, { key: "finalize", label: "整理结果" }, ]; @@ -260,3 +272,94 @@ export function getAgentProgressFallbackTitle(payload?: AgentProgressStreamPaylo return "正在理解需求"; } } + +export function getAgentProgressActionLabel( + payload?: AgentProgressStreamPayload | null +) { + switch (payload?.capability) { + case "analyze": + return "图片分析"; + case "generic_edit": + return "修图"; + case "remove_background": + return "抠图"; + case "remove_watermark": + return "去水印"; + case "enhance": + return "图像增强"; + case "resize": + return "尺寸调整"; + case "extend": + return "扩图"; + case "angle_variant": + return "多视角"; + case "local_edit": + return "局部编辑"; + case "box_cutout": + return "框选抠图"; + case "generate_image": + return "生图"; + case "generate_video": + return "视频生成"; + default: + return "工具"; + } +} + +export function getAgentProgressStepLabel( + stepKey: NonNullable, + payload?: AgentProgressStreamPayload | null +) { + const actionLabel = getAgentProgressActionLabel(payload); + switch (stepKey) { + case "lock_target": + return "理解用户需求"; + case "analyze": + return payload?.capability === "analyze" ? "分析图片" : "分析使用工具"; + case "select_tool": + return actionLabel === "工具" ? "确认执行工具" : `确认${actionLabel}工具`; + case "execute": + return actionLabel === "工具" ? "执行中" : `${actionLabel}中`; + case "finalize": + return "整理结果"; + default: + return "处理中"; + } +} + +export function buildAgentProgressNodeSteps( + payload?: AgentProgressStreamPayload | null +): AgentProgressNodeStep[] { + const currentStep = payload?.currentStep || "lock_target"; + const currentStepIndex = Math.max( + 0, + AGENT_PROGRESS_STEPS.findIndex((step) => step.key === currentStep) + ); + + return AGENT_PROGRESS_STEPS.map((step, index) => { + let state: AgentProgressStepState = "upcoming"; + if (payload?.stage === "failed") { + state = + index < currentStepIndex + ? "completed" + : index === currentStepIndex + ? "failed" + : "upcoming"; + } else if (payload?.stage === "completed") { + state = "completed"; + } else { + state = + index < currentStepIndex + ? "completed" + : index === currentStepIndex + ? "current" + : "upcoming"; + } + + return { + key: step.key, + label: getAgentProgressStepLabel(step.key, payload), + state, + }; + }); +} diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index 1ed8f6a5a..2504c581c 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -9,8 +9,10 @@ import { } from "@/components/canvas/chat-panel/canvas-chat-media"; import { filterCanvasMediaPayloadForUnhandledItems, + buildAgentProgressNodeSteps, getCanvasMediaPayloadHandledItemIds, getCanvasOperationHandledMediaItemIds, + getAgentProgressStepLabel, isCanvasAgentViewOperationClientEnabled, normalizeCanvasAgentClientBoolean, shouldRetryCanvasViewOperationAfterRefresh, @@ -1210,6 +1212,44 @@ test.describe("canvas chat pure helpers", () => { expect(editText).toContain("替换背景"); }); + test("builds capability-aware agent progress node labels", () => { + const selectingSteps = buildAgentProgressNodeSteps({ + stage: "planning", + currentStep: "select_tool", + capability: "remove_background", + }); + + expect(selectingSteps.map((step) => step.label)).toEqual([ + "理解用户需求", + "分析使用工具", + "确认抠图工具", + "抠图中", + "整理结果", + ]); + expect(selectingSteps.map((step) => step.state)).toEqual([ + "completed", + "completed", + "current", + "upcoming", + "upcoming", + ]); + + const executingSteps = buildAgentProgressNodeSteps({ + stage: "executing", + currentStep: "execute", + capability: "remove_background", + }); + + expect(executingSteps[2]?.state).toBe("completed"); + expect(executingSteps[3]).toMatchObject({ + label: "抠图中", + state: "current", + }); + expect(getAgentProgressStepLabel("execute", { capability: "generate_video" })).toBe( + "视频生成中" + ); + }); + test("resolves deictic canvas edit requests to latest results and direct tools", () => { const latestResultUrl = "https://cdn.example.com/latest-cat-result.png"; const requestPolicy = resolveCanvasAgentRequestPolicy({ From 4b9f3a25c9b1aa428e6f2d13da8252e6de80cf5e Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 16:02:33 +0800 Subject: [PATCH 08/29] fix: resolve unselected canvas image targets --- components/canvas/CanvasChatPanel.tsx | 22 ++++++-- lib/ai/context-memory/media-input.ts | 1 + lib/ai/context-memory/target-resolution.ts | 27 ++++++++++ lib/ai/context-memory/types.ts | 1 + lib/ai/runtime/direct-agent-execution.ts | 1 + lib/canvas/local-upload-state.ts | 9 +++- tests/routes/canvas-chat-helpers.test.ts | 60 ++++++++++++++++++++++ 7 files changed, 115 insertions(+), 6 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index d5e82e3d0..cdd55e1e2 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -857,6 +857,18 @@ function isInternalCanvasImageGenerationFailureText(parts: Array) { ); } +function getCanvasImageNodeUrl(node: CanvasNode | null | undefined) { + if (!node || node.type !== "image") return ""; + const data = (node.data || {}) as Record; + return String( + data.src || + data.previewImage || + data.imageUrl || + data.renderArtifacts?.screenshotUrl || + "" + ).trim(); +} + function findCanvasImageAnchorNode( nodes: CanvasNode[], params: { @@ -873,7 +885,7 @@ function findCanvasImageAnchorNode( if (sourceKeys.size > 0) { const matchedNode = nodes.find((node) => { if (node.type !== "image") return false; - const src = String((node.data as any)?.src || "").trim(); + const src = getCanvasImageNodeUrl(node); return sourceKeys.has(normalizeImageIdentityUrl(src)); }); if (matchedNode) return matchedNode; @@ -7871,7 +7883,7 @@ export function CanvasChatPanel({ pendingTarget: pendingCanvasAgentAnnotationEditTargetRef.current, isEligibleNode: (node) => node.type === "image" && - isValidChatHttpUrl(String((node.data as any)?.src || "").trim()), + isValidChatHttpUrl(getCanvasImageNodeUrl(node)), }); if ( pendingCanvasAgentAnnotationEditTargetRef.current && @@ -7888,7 +7900,7 @@ export function CanvasChatPanel({ const imageNodes = nodes.filter( (node) => node.type === "image" && - isValidChatHttpUrl(String((node.data as any)?.src || "").trim()), + isValidChatHttpUrl(getCanvasImageNodeUrl(node)), ); const effectiveComposerMode = activeComposerModeRef.current || activeComposerMode; @@ -7923,7 +7935,7 @@ export function CanvasChatPanel({ new Map( [ ...selectedImageNodes.filter((node) => - isValidChatHttpUrl(String((node.data as any)?.src || "").trim()) + isValidChatHttpUrl(getCanvasImageNodeUrl(node)) ), ...(pendingAnnotationTargetNode ? [pendingAnnotationTargetNode] : []), ].map((node) => [node.id, node]) @@ -8201,7 +8213,7 @@ export function CanvasChatPanel({ assetId: isValidChatUuid((node.data as any)?.assetId) ? String((node.data as any).assetId).trim() : undefined, - url: String((node.data as any)?.src || "").trim(), + url: getCanvasImageNodeUrl(node), title: typeof (node.data as any)?.title === "string" ? String((node.data as any).title).slice(0, 256) diff --git a/lib/ai/context-memory/media-input.ts b/lib/ai/context-memory/media-input.ts index 6d06e1697..228c24391 100644 --- a/lib/ai/context-memory/media-input.ts +++ b/lib/ai/context-memory/media-input.ts @@ -308,6 +308,7 @@ export function resolveChatMediaInput( resolvedImageRefs, currentMessageImageUrls: currentMessageImageRefs.map((ref) => ref.url), selectedImageUrls: selectedImageRefs.map((ref) => ref.url), + canvasImageUrls: canvasImageRefs.map((ref) => ref.url), historyUserImageUrls: history.latestUser.map((ref) => ref.url), historyAssistantImageUrls: history.latestAssistant.map((ref) => ref.url), resolvedImageUrls: resolvedImageRefs.map((ref) => ref.url), diff --git a/lib/ai/context-memory/target-resolution.ts b/lib/ai/context-memory/target-resolution.ts index 6c69dd7ef..fb253758b 100644 --- a/lib/ai/context-memory/target-resolution.ts +++ b/lib/ai/context-memory/target-resolution.ts @@ -497,6 +497,21 @@ export function resolveTargetAssets( }); } + if ( + canvasRefs.length === 1 && + (hasCanvasAgentActionableImageEditIntent(text) || focusPolicy === "auto") + ) { + return buildResolvedTargetAssets({ + targetRefs: [canvasRefs[0]], + candidateRefs, + resolutionMode: "text_reference", + confidence: 84, + needsClarification: false, + reason: "用户使用画布/图片指代表达,且当前画布仅有一张可处理图片", + fromHistory: true, + }); + } + const allowsImplicitHistoryTarget = IMPLICIT_HISTORY_TARGET_REGEX.test(text) && (hasCanvasAgentActionableImageEditIntent(text) || @@ -559,6 +574,18 @@ export function resolveTargetAssets( } if (hasCanvasAgentActionableImageEditIntent(text)) { + if (canvasRefs.length === 1) { + return buildResolvedTargetAssets({ + targetRefs: [canvasRefs[0]], + candidateRefs, + resolutionMode: "text_reference", + confidence: 82, + needsClarification: false, + reason: "用户表达了图片编辑意图,且当前画布仅有一张可处理图片", + fromHistory: true, + }); + } + return buildResolvedTargetAssets({ targetRefs: [], candidateRefs, diff --git a/lib/ai/context-memory/types.ts b/lib/ai/context-memory/types.ts index d183534fe..bc6cafdb4 100644 --- a/lib/ai/context-memory/types.ts +++ b/lib/ai/context-memory/types.ts @@ -57,6 +57,7 @@ export interface ResolvedChatMediaInput { resolvedImageRefs: ResolvedImageRef[]; currentMessageImageUrls: string[]; selectedImageUrls: string[]; + canvasImageUrls: string[]; historyUserImageUrls: string[]; historyAssistantImageUrls: string[]; resolvedImageUrls: string[]; diff --git a/lib/ai/runtime/direct-agent-execution.ts b/lib/ai/runtime/direct-agent-execution.ts index bd507cb55..79a6f6642 100644 --- a/lib/ai/runtime/direct-agent-execution.ts +++ b/lib/ai/runtime/direct-agent-execution.ts @@ -653,6 +653,7 @@ export function pickAgentSourceImageUrls(params: { params.requestTargetResolution?.targetImageUrls || [], params.requestResolvedMediaInput?.selectedImageUrls || [], params.requestResolvedMediaInput?.currentMessageImageUrls || [], + params.requestResolvedMediaInput?.canvasImageUrls || [], params.requestWorkingState?.lastResolvedTargetImageUrls || [], params.requestWorkingState?.lastGeneratedImageUrls || [], params.requestResolvedMediaInput?.historyAssistantImageUrls || [], diff --git a/lib/canvas/local-upload-state.ts b/lib/canvas/local-upload-state.ts index 7845f4766..0f1cf4b6c 100644 --- a/lib/canvas/local-upload-state.ts +++ b/lib/canvas/local-upload-state.ts @@ -29,6 +29,13 @@ export function isCanvasImageReadyForAi(node: CanvasNode | null | undefined) { return false; } - const src = String(((node.data as Record)?.src || "")).trim(); + const data = (node.data || {}) as Record; + const src = String( + data.src || + data.previewImage || + data.imageUrl || + data.renderArtifacts?.screenshotUrl || + "" + ).trim(); return /^https?:\/\//i.test(src); } diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index 2504c581c..1888fa834 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -1339,6 +1339,66 @@ test.describe("canvas chat pure helpers", () => { expect(directContext?.targetImageUrl).toBe(latestResultUrl); }); + test("falls back to canvas images for direct agent edit tools", () => { + const canvasImageUrl = "https://cdn.example.com/canvas-cat.png"; + const mediaInput = { + imageRefs: [], + currentMessageImageRefs: [], + selectedImageRefs: [], + canvasImageRefs: [ + { + url: canvasImageUrl, + normalizedUrl: canvasImageUrl, + nodeId: "cat-node", + source: "canvas_context", + role: "reference", + x: 120, + y: 80, + width: 640, + height: 640, + isSelected: false, + }, + ], + historyUserImageRefs: [], + historyAssistantImageRefs: [], + resolvedImageRefs: [], + currentMessageImageUrls: [], + selectedImageUrls: [], + canvasImageUrls: [canvasImageUrl], + historyUserImageUrls: [], + historyAssistantImageUrls: [], + resolvedImageUrls: [], + selectedAssetIds: [], + candidateAssetIds: [], + uploadedAssetIds: [], + hasImage: false, + source: "none", + fromHistory: false, + } as any; + + const directContext = resolveDirectAgentToolContext({ + execution: { + mode: "edit_image", + routeIntent: "image_edit", + routeSubIntent: "remove_background", + targetSource: "text_reference", + preferredCapability: "remove_background", + shouldUseStructuredReply: true, + shouldOptimizePrompt: true, + shouldApplyImagePipeline: true, + shouldApplyVideoPipeline: false, + shouldStayConversational: false, + shouldPublishToCanvas: false, + toolCalls: [], + availableTools: ["removeBackground"], + } as any, + requestResolvedMediaInput: mediaInput, + }); + + expect(directContext?.execution.toolName).toBe("removeBackground"); + expect(directContext?.targetImageUrl).toBe(canvasImageUrl); + }); + test("only runs direct image edit batches for explicit safe batch requests", () => { expect( shouldRunDirectAgentBatchImageEdit({ From 8c159a3828fa922934bd33b5e7d59d7a35318427 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 16:30:03 +0800 Subject: [PATCH 09/29] fix: remove agent progress bubble and add dialogue memory --- app/(chat)/api/chat/route.ts | 91 ++++++++++---- components/canvas/CanvasChatPanel.tsx | 128 -------------------- lib/ai/runtime/recent-dialogue-memory.ts | 146 +++++++++++++++++++++++ tests/routes/canvas-chat-helpers.test.ts | 56 +++++++++ 4 files changed, 268 insertions(+), 153 deletions(-) create mode 100644 lib/ai/runtime/recent-dialogue-memory.ts diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index c3be7a608..5b901905b 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -250,6 +250,7 @@ import { pruneTaskBoundaryContext, pruneTaskBoundaryHistoryMessages, } from "@/lib/ai/runtime/task-boundary-context-pruner"; +import { buildRecentDialogueMemory } from "@/lib/ai/runtime/recent-dialogue-memory"; import { resolveAgentModelSlotDescriptor, upsertAgentModelSlot, @@ -1085,6 +1086,10 @@ export async function POST(request: Request) { let confirmedPromptForConversationState: string | undefined; let smartAutoHistoryMessagesFromDb: DBMessage[] = []; let smartAutoMediaHistoryMessagesFromDb: DBMessage[] = []; + let recentDialogueMemory = buildRecentDialogueMemory({ + messages: [], + currentText: requestTextContent, + }); let preferredAgentModelId: string | undefined; let configuredAgentConversationModelId: string | undefined; let agentModelSlots: AgentModelSlots = {}; @@ -1489,6 +1494,17 @@ export async function POST(request: Request) { taskType: taskBoundaryDecision.taskType, taskMode: taskBoundaryDecision.taskMode, }); + recentDialogueMemory = buildRecentDialogueMemory({ + messages: loadedHistoryMessages, + currentText: smartAutoInputText, + maxEntries: taskBoundaryDecision.taskType === "chat" ? 6 : 4, + maxTotalChars: taskBoundaryDecision.taskType === "chat" ? 1000 : 700, + }); + chatApiLogger.info("[RecentDialogueMemory] Smart auto recall:", { + entries: recentDialogueMemory.entries.length, + isRecallRequest: recentDialogueMemory.isRecallRequest, + taskType: taskBoundaryDecision.taskType, + }); autoTextForFallback = smartAutoInputText; if (!requestWorkingState && !shouldIsolateDirectComposerContext) { @@ -1563,23 +1579,12 @@ export async function POST(request: Request) { resolutionConfidence: requestTargetResolution.confidence, }); - // 🆕 从历史消息中提取对话文本(用于上下文理解) - const historyMessages: { role: "user" | "assistant"; content: string }[] = []; - for (const msg of smartAutoHistoryMessagesFromDb.slice(-10)) { // 最多取最近10条 - const parts = msg.parts as any[]; - if (parts && parts.length > 0) { - // 提取文本内容 - const textParts = parts.filter((p: any) => p.type === 'text'); - const content = textParts.map((p: any) => p.text || '').join(' ').trim(); - if (content) { - historyMessages.push({ - role: msg.role as "user" | "assistant", - content: content.substring(0, 300), // 限制长度 - }); - } - } - } - chatApiLogger.info("[Smart Auto Mode] History context:", historyMessages.length, "messages"); + const historyMessages: { role: "user" | "assistant"; content: string }[] = + recentDialogueMemory.entries.map((entry) => ({ + role: entry.role, + content: entry.content, + })); + chatApiLogger.info("[Smart Auto Mode] History context:", historyMessages.length, "memory entries"); // 2. 使用 LangGraph 驱动的自动模式工作流 const { runAutoAgentGraph } = await import("@/lib/ai/auto-agent-graph"); @@ -1612,8 +1617,15 @@ export async function POST(request: Request) { workflowState: composedConversationState.threadState.workflowState, memoryHints: composedConversationState.threadState.memoryHints, contextSummary: composedConversationState.threadState.contextSummary, + recentDialogueMemory: recentDialogueMemory.contextSummary, }, }); + const agentGraphContext = [ + composedConversationState.composedConversationMemory.contextSummary, + recentDialogueMemory.contextSummary, + ] + .filter(Boolean) + .join("\n"); const autoGraphResult = await withOperationTimeout( runAutoAgentGraph({ text: smartAutoInputText, @@ -1641,10 +1653,7 @@ export async function POST(request: Request) { requestResolvedMediaInput.historyUserImageUrls.length, currentUploadImageCount: requestResolvedMediaInput.currentMessageImageUrls.length, historyMessages, - context: - composedConversationState.composedConversationMemory.contextSummary || - effectiveAutoContextText || - undefined, + context: agentGraphContext || effectiveAutoContextText || undefined, preferredModelId: preferredAgentModelId, threadState: composedConversationState.threadState, }), @@ -2747,6 +2756,21 @@ export async function POST(request: Request) { purpose: "media", hasCurrentImageInput: hasImageInputForConversationAction, }); + recentDialogueMemory = shouldIsolateDirectComposerContext + ? recentDialogueMemory + : buildRecentDialogueMemory({ + messages: loadedMessagesForBoundary, + currentText: requestTextContent, + maxEntries: taskBoundaryDecision.taskType === "chat" ? 6 : 4, + maxTotalChars: taskBoundaryDecision.taskType === "chat" ? 1000 : 700, + }); + if (recentDialogueMemory.entries.length > 0) { + chatApiLogger.info("[RecentDialogueMemory] Request recall:", { + entries: recentDialogueMemory.entries.length, + isRecallRequest: recentDialogueMemory.isRecallRequest, + taskType: taskBoundaryDecision.taskType, + }); + } if (!requestWorkingState && !shouldIsolateDirectComposerContext) { requestWorkingState = await getConversationWorkingStateByChatId({ @@ -8591,16 +8615,33 @@ export async function POST(request: Request) { resolvedRuntimeModelLookupId = actualModelId; } - const effectiveConversationSystemPrompt = shouldRunAgentConversation - ? `${await buildAgentRoleIdentityInstruction({ + const recentDialogueSystemContext = recentDialogueMemory.contextSummary + ? [ + recentDialogueMemory.contextSummary, + ...recentDialogueMemory.memoryHints, + ].join("\n") + : ""; + const baseConversationSystemPrompt = systemPrompt({ + selectedChatModel: finalModelId, + requestHints, + }); + const agentIdentityInstruction = shouldRunAgentConversation + ? await buildAgentRoleIdentityInstruction({ allowVideoGeneration: allowAgentVideoGeneration, hasCanvasContext: Boolean( effectiveContextPayload?.source === "canvas" || effectiveContextPayload?.selectedNodeIds?.length || effectiveContextPayload?.canvasImageNodes?.length, ), - })}\n\n${systemPrompt({ selectedChatModel: finalModelId, requestHints })}` - : systemPrompt({ selectedChatModel: finalModelId, requestHints }); + }) + : ""; + const effectiveConversationSystemPrompt = [ + agentIdentityInstruction, + recentDialogueSystemContext, + baseConversationSystemPrompt, + ] + .filter(Boolean) + .join("\n\n"); const activeRuntimeModelDescriptor = await resolveAgentModelSlotDescriptor( resolvedRuntimeModelLookupId, diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index cdd55e1e2..ac5ffeb94 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -1636,130 +1636,6 @@ function CanvasAssistantTypingPlaceholder({ hint }: { hint?: string | null }) { ); } -function CanvasAgentProgressTimeline({ - progress, -}: { - progress?: AgentProgressStreamPayload | null; -}) { - const steps = buildAgentProgressNodeSteps(progress); - const title = progress?.title?.trim() || getAgentProgressFallbackTitle(progress); - const isFailed = progress?.stage === "failed"; - const isCompleted = progress?.stage === "completed"; - const isClarify = progress?.stage === "clarify"; - - return ( -
-
-
- - {isFailed ? ( - - ) : isCompleted ? ( - - ) : ( - - )} - - - {title} - -
- -
-
- {steps.map((step, index) => { - const isStepCompleted = step.state === "completed"; - const isStepCurrent = step.state === "current"; - const isStepFailed = step.state === "failed"; - const lineIsActive = - isStepCompleted || isStepCurrent || isStepFailed; - - return ( -
-
- - {isStepCompleted ? ( - - ) : isStepFailed ? ( - - ) : isStepCurrent ? ( - - ) : ( - - )} - {isStepCurrent ? ( - - ) : null} - - - {step.label} - -
- {index < steps.length - 1 ? ( - - ) : null} -
- ); - })} -
-
-
-
- ); -} - function CanvasComposerUploadProgressDialog({ progress, }: { @@ -13672,10 +13548,6 @@ export function CanvasChatPanel({ ) : null} - {isLoading && !shouldRenderImageLoading && ( - - )} -
diff --git a/lib/ai/runtime/recent-dialogue-memory.ts b/lib/ai/runtime/recent-dialogue-memory.ts new file mode 100644 index 000000000..fa8dbd113 --- /dev/null +++ b/lib/ai/runtime/recent-dialogue-memory.ts @@ -0,0 +1,146 @@ +import type { DBMessage } from "@/lib/db/schema"; + +export interface RecentDialogueMemoryEntry { + role: "user" | "assistant"; + content: string; + messageId?: string; +} + +export interface RecentDialogueMemory { + entries: RecentDialogueMemoryEntry[]; + contextSummary: string; + memoryHints: string[]; + isRecallRequest: boolean; +} + +const USER_RECALL_PATTERN = + /(?:我|用户)?(?:刚才|刚刚|前面|之前|上面|上一(?:句|条|轮)|最近).{0,12}(?:说|发|问|讲|提|输入|发送).{0,12}(?:什么|啥|哪句|哪些|内容)|(?:我说了什么|我刚才说啥|我前面说啥|我之前说啥|我发了什么|我问了什么|记得我.{0,12}说|没有记忆)/i; + +const ASSISTANT_RECALL_PATTERN = + /(?:你|助手|ai|AI).{0,12}(?:刚才|刚刚|前面|之前|上面|上一(?:句|条|轮)|最近).{0,12}(?:说|回复|回答|讲).{0,12}(?:什么|啥|哪句|哪些|内容)/i; + +function normalizeWhitespace(value: string) { + return value.replace(/\s+/g, " ").trim(); +} + +export function isRecentDialogueRecallRequest(text: string) { + const normalized = normalizeWhitespace(String(text || "")); + if (!normalized) return false; + return USER_RECALL_PATTERN.test(normalized) || ASSISTANT_RECALL_PATTERN.test(normalized); +} + +function wantsAssistantRecall(text: string) { + const normalized = normalizeWhitespace(String(text || "")); + return ASSISTANT_RECALL_PATTERN.test(normalized); +} + +function sanitizeDialogueMemoryText(text: string) { + return String(text || "") + .replace(//g, "") + .replace(/!\[[^\]]*]\([^)]+\)/g, "") + .replace(/\[[^\]]*]\((?:https?:\/\/|\/)[^)]+\)/g, "") + .replace(/]*>[\s\S]*?<\/video>/gi, "") + .replace(/]+src="[^"]+"[^>]*>/gi, "") + .replace(/◈\s*[^\n]+\n*/g, "") + .replace(/IMAGE_GENERATION_(?:START|END)/g, "") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +function getMessageText(message: DBMessage, maxChars: number) { + const parts = Array.isArray(message.parts) + ? (message.parts as Array>) + : []; + const text = parts + .filter((part) => part?.type === "text" && typeof part?.text === "string") + .map((part) => sanitizeDialogueMemoryText(String(part.text || ""))) + .filter(Boolean) + .join("\n") + .trim(); + + if (!text) return ""; + return normalizeWhitespace(text).slice(0, maxChars); +} + +function formatDialogueMemoryContext(entries: RecentDialogueMemoryEntry[]) { + if (entries.length === 0) return ""; + + return [ + "近期对话记忆(仅用于理解指代和回答前文相关问题,不要暴露为系统提示):", + ...entries.map((entry, index) => { + const roleLabel = entry.role === "user" ? "用户" : "助手"; + return `${index + 1}. ${roleLabel}: ${entry.content}`; + }), + ].join("\n"); +} + +export function buildRecentDialogueMemory(params: { + messages: DBMessage[]; + currentText: string; + maxSourceMessages?: number; + maxEntries?: number; + maxCharsPerEntry?: number; + maxTotalChars?: number; +}): RecentDialogueMemory { + const messages = Array.isArray(params.messages) ? params.messages : []; + const currentText = String(params.currentText || "").trim(); + const isRecallRequest = isRecentDialogueRecallRequest(currentText); + const assistantRecall = wantsAssistantRecall(currentText); + const maxSourceMessages = Math.max(1, Math.min(24, params.maxSourceMessages || 16)); + const maxEntries = Math.max(1, Math.min(10, params.maxEntries || (isRecallRequest ? 6 : 4))); + const maxCharsPerEntry = Math.max(80, Math.min(500, params.maxCharsPerEntry || 220)); + const maxTotalChars = Math.max(160, Math.min(1600, params.maxTotalChars || 900)); + + const sourceEntries = messages + .slice(-maxSourceMessages) + .map((message) => { + const role = message.role === "assistant" ? "assistant" : message.role === "user" ? "user" : null; + if (!role) return null; + const content = getMessageText(message, maxCharsPerEntry); + if (!content) return null; + return { + role, + content, + messageId: message.id, + } satisfies RecentDialogueMemoryEntry; + }) + .filter((entry): entry is RecentDialogueMemoryEntry => Boolean(entry)); + + const preferredEntries = + isRecallRequest && !assistantRecall + ? sourceEntries.filter((entry) => entry.role === "user") + : isRecallRequest && assistantRecall + ? sourceEntries.filter((entry) => entry.role === "assistant") + : sourceEntries; + const fallbackEntries = + preferredEntries.length > 0 ? preferredEntries : sourceEntries; + + const selectedReversed: RecentDialogueMemoryEntry[] = []; + let totalChars = 0; + for (let index = fallbackEntries.length - 1; index >= 0; index -= 1) { + const entry = fallbackEntries[index]; + if (!entry) continue; + if (selectedReversed.length >= maxEntries) break; + if (totalChars + entry.content.length > maxTotalChars && selectedReversed.length > 0) { + continue; + } + selectedReversed.push(entry); + totalChars += entry.content.length; + } + + const entries = selectedReversed.reverse(); + const memoryHints = entries.length + ? [ + isRecallRequest + ? "用户正在询问前文或记忆,应优先根据近期对话记忆回答,不要声称没有上下文。" + : "近期对话记忆只用于理解指代和延续语境,不要逐字复述,除非用户明确询问前文。", + ] + : []; + + return { + entries, + contextSummary: formatDialogueMemoryContext(entries), + memoryHints, + isRecallRequest, + }; +} diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index 1888fa834..6b0027ab4 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -52,6 +52,10 @@ import { resolveCanvasAgentTargetPreference, } from "@/lib/ai/runtime/canvas-agent-kernel"; import { inferAgentImageCountFromText } from "@/lib/ai/runtime/image-count-intent"; +import { + buildRecentDialogueMemory, + isRecentDialogueRecallRequest, +} from "@/lib/ai/runtime/recent-dialogue-memory"; import { isAgentModeScopedChatId, isScopedEmptyHistoryRequest, @@ -221,6 +225,19 @@ import { import type { PickedObjectAttachment } from "@/components/canvas/chat-panel/canvas-chat-session"; import type { CanvasAgentContext } from "@/types/canvas/agent-protocol"; import type { ChatMessage } from "@/lib/types"; +import type { DBMessage } from "@/lib/db/schema"; + +function dbTextMessage( + id: string, + role: "user" | "assistant", + text: string, +): DBMessage { + return { + id, + role, + parts: [{ type: "text", text }], + } as unknown as DBMessage; +} test.describe("canvas chat pure helpers", () => { test("keeps optimistic messages without timestamps after persisted history", () => { @@ -309,6 +326,45 @@ test.describe("canvas chat pure helpers", () => { expect(upstream).toContain("| SKU | 销量 |"); }); + test("builds bounded recent dialogue memory for user recall requests", () => { + const memory = buildRecentDialogueMemory({ + messages: [ + dbTextMessage("m1", "user", "你好"), + dbTextMessage("m2", "assistant", "你好,我在。"), + dbTextMessage("m3", "user", "你是一个小可爱"), + dbTextMessage("m4", "assistant", "嘿嘿,谢谢你的夸奖。"), + ], + currentText: "我前面说了什么?", + }); + + expect(isRecentDialogueRecallRequest("我前面说了什么?")).toBe(true); + expect(memory.isRecallRequest).toBe(true); + expect(memory.entries.map((entry) => entry.role)).toEqual(["user", "user"]); + expect(memory.entries.at(-1)?.content).toBe("你是一个小可爱"); + expect(memory.contextSummary).toContain("用户: 你是一个小可爱"); + expect(memory.memoryHints.join(" ")).toContain("不要声称没有上下文"); + }); + + test("sanitizes media markup from recent dialogue memory", () => { + const memory = buildRecentDialogueMemory({ + messages: [ + dbTextMessage("m1", "user", "生成一只小猫"), + dbTextMessage( + "m2", + "assistant", + "\n![原图](https://example.com/cat.png)\n已完成本次生成" + ), + ], + currentText: "你刚才回复了什么?", + }); + + expect(memory.entries).toHaveLength(1); + expect(memory.entries[0].role).toBe("assistant"); + expect(memory.entries[0].content).toBe("已完成本次生成"); + expect(memory.contextSummary).not.toContain("https://example.com"); + expect(memory.contextSummary).not.toContain("IMAGE_GENERATION_START"); + }); + test("infers explicit agent image counts from user text", () => { expect(inferAgentImageCountFromText("再出三版")).toBe(3); expect(inferAgentImageCountFromText("基于这张图再来 3 张")).toBe(3); From 8c719c44acf04d8f91040767f9a82f328d503957 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 16:33:03 +0800 Subject: [PATCH 10/29] fix: stabilize recent dialogue memory typing --- lib/ai/runtime/recent-dialogue-memory.ts | 28 ++++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/ai/runtime/recent-dialogue-memory.ts b/lib/ai/runtime/recent-dialogue-memory.ts index fa8dbd113..b6b5640fd 100644 --- a/lib/ai/runtime/recent-dialogue-memory.ts +++ b/lib/ai/runtime/recent-dialogue-memory.ts @@ -91,20 +91,20 @@ export function buildRecentDialogueMemory(params: { const maxCharsPerEntry = Math.max(80, Math.min(500, params.maxCharsPerEntry || 220)); const maxTotalChars = Math.max(160, Math.min(1600, params.maxTotalChars || 900)); - const sourceEntries = messages - .slice(-maxSourceMessages) - .map((message) => { - const role = message.role === "assistant" ? "assistant" : message.role === "user" ? "user" : null; - if (!role) return null; - const content = getMessageText(message, maxCharsPerEntry); - if (!content) return null; - return { - role, - content, - messageId: message.id, - } satisfies RecentDialogueMemoryEntry; - }) - .filter((entry): entry is RecentDialogueMemoryEntry => Boolean(entry)); + const sourceEntries: RecentDialogueMemoryEntry[] = []; + for (const message of messages.slice(-maxSourceMessages)) { + const role = message.role === "assistant" ? "assistant" : message.role === "user" ? "user" : null; + if (!role) continue; + + const content = getMessageText(message, maxCharsPerEntry); + if (!content) continue; + + sourceEntries.push({ + role, + content, + messageId: message.id, + }); + } const preferredEntries = isRecallRequest && !assistantRecall From 2e4cb0cf7310243c2182f7c21cb91e58cd3973b4 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 16:54:43 +0800 Subject: [PATCH 11/29] fix: keep canvas user message visible while pending --- components/canvas/CanvasChatPanel.tsx | 49 +++++++++++++++++++-------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index ac5ffeb94..40964a6df 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -7041,8 +7041,7 @@ export function CanvasChatPanel({ inFlightRawChatIdRef.current = rawChatId; const launchUserMessageId = generateUUID(); const launchCreatedAt = new Date(); - - sendMessage({ + const launchUserMessage = { id: launchUserMessageId, role: "user", parts, @@ -7052,7 +7051,15 @@ export function CanvasChatPanel({ composerMode: activeComposerModeRef.current || activeComposerMode, modelId: selectedModelId, }, - } as any); + } as ChatMessage; + + sendMessage(launchUserMessage as any); + setMessages((previousMessages) => + sortCanvasMessagesByCreatedAt([ + ...previousMessages.filter((message) => message.id !== launchUserMessageId), + launchUserMessage, + ]) + ); hasHydratedHistoryRef.current = true; pendingLaunchRef.current = null; @@ -7065,7 +7072,7 @@ export function CanvasChatPanel({ if (editableDiv) { editableDiv.innerHTML = ""; } - }, [activeChatId, rawChatId, selectedModelId, status, sendMessage, clearSelection, launchAutoSendTick, activeComposerMode]); + }, [activeChatId, rawChatId, selectedModelId, status, sendMessage, setMessages, clearSelection, launchAutoSendTick, activeComposerMode]); // 当历史消息加载完成后,更新消息列表(支持同一会话的增量刷新) const loadedHistorySignatureRef = useRef(""); @@ -7083,6 +7090,12 @@ export function CanvasChatPanel({ ) { return; } + const hasActiveRegularSubmission = + inFlightChatIdRef.current === activeChatId || + inFlightRawChatIdRef.current === rawChatId; + if (hasActiveRegularSubmission && !shouldForceHydrate) { + return; + } const historyMessages = historyData.messages || []; const signature = buildCanvasHistoryMessagesSignature(rawChatId, historyMessages); @@ -7112,7 +7125,7 @@ export function CanvasChatPanel({ } }; } - }, [historyData, isClawdSubmitting, rawChatId, setMessages, status]); + }, [activeChatId, historyData, isClawdSubmitting, rawChatId, setMessages, status]); useEffect(() => { const streamState = streamImageGenerationStateByChatId[activeChatId]; @@ -10999,15 +11012,23 @@ export function CanvasChatPanel({ }); } - // 使用与 multimodal-input 相同的格式发送消息 - try { - sendMessage({ - id: userMessageId, - role: "user", - parts: parts, - createdAt: optimisticCreatedAt, - metadata: optimisticUserMetadata, - } as any); + const optimisticUserMessage: ChatMessage = { + id: userMessageId, + role: "user", + parts, + createdAt: optimisticCreatedAt, + metadata: optimisticUserMetadata, + } as ChatMessage; + + // 使用与 multimodal-input 相同的格式发送消息 + try { + sendMessage(optimisticUserMessage as any); + setMessages((previousMessages) => + sortCanvasMessagesByCreatedAt([ + ...previousMessages.filter((message) => message.id !== userMessageId), + optimisticUserMessage, + ]) + ); } catch (error) { releaseSendGuard(activeChatId); if (shouldShowOptimisticImageGeneration) { From 5923149dd63649d1a27e5e0b5324e09a65fd3244 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 20:36:18 +0800 Subject: [PATCH 12/29] fix: restore canvas pending feedback and scoped capabilities --- app/(chat)/api/chat/route.ts | 47 +++++++++++++--- components/canvas/CanvasChatPanel.tsx | 62 +++++++++++----------- lib/ai/runtime/task-boundary-classifier.ts | 5 +- lib/ai/runtime/task-boundary-text.ts | 12 +++++ tests/routes/canvas-chat-helpers.test.ts | 8 +++ 5 files changed, 93 insertions(+), 41 deletions(-) create mode 100644 lib/ai/runtime/task-boundary-text.ts diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index 5b901905b..67e892f9b 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -257,6 +257,7 @@ import { type AgentModelSlots, } from "@/lib/ai/runtime/agent-model-slots"; import { isPureGreetingTurnRequest } from "@/lib/ai/runtime/task-boundary-classifier"; +import { isCapabilityQuestionTurnRequest } from "@/lib/ai/runtime/task-boundary-text"; import { getProviderHealthSnapshot, recordProviderHealthFailure, @@ -846,6 +847,19 @@ const DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS = 12_000; const CHAT_CREATION_LOOKUP_RETRY_DELAYS_MS = [60, 180, 360] as const; const DETAIL_REPLACEMENT_PROMPT_PACK_REQUIRED_MESSAGE = "请先在「风格化提示词配置」里选择提示词组合,再执行详情场景替换;缺少提示词组时系统不会处理。"; +const CANVAS_AGENT_GREETING_MESSAGE = + "你好,我在。你可以直接告诉我想做什么:生图、修图、生成视频、分析图片都可以。"; +const CANVAS_AGENT_CAPABILITY_MESSAGE = [ + "我主要帮你完成画布里的视觉创作任务:", + "", + "- 生图:按文字、参考图或画布选中内容生成图片。", + "- 修图:换背景、去元素、局部重绘、扩图、增强、抠图、改尺寸。", + "- 视频:文生视频、图生视频、分镜/镜头视频需求整理与生成。", + "- 图片分析:识别主体、风格、构图、材质、光线,并整理可执行提示词。", + "- 画布协作:读取当前画布选择、槽位、最近结果,继续生成、修改或写回画布。", + "", + "你可以直接说:把这张图换成白底、参考左边图片生成 3 张主图、让这张图动起来。", +].join("\n"); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -1234,9 +1248,20 @@ export async function POST(request: Request) { const hasCurrentMessageMediaInput = message.parts.some((part: any) => part?.type === "file" || part?.type === "image" || part?.type === "image_url" ); + const isGreetingTurnRequest = isPureGreetingTurnRequest(requestTextContent); + const isCapabilityQuestionRequest = + isCapabilityQuestionTurnRequest(requestTextContent); + const canvasFastPathMessage = isCapabilityQuestionRequest + ? CANVAS_AGENT_CAPABILITY_MESSAGE + : isGreetingTurnRequest + ? CANVAS_AGENT_GREETING_MESSAGE + : ""; if ( - shouldRunAgentConversation && - isPureGreetingTurnRequest(requestTextContent) && + (shouldRunAgentConversation || + isCanvasPageRequest || + contextPayload?.source === "canvas" || + Boolean(requestCanvasAgentContext)) && + canvasFastPathMessage && !hasCurrentMessageMediaInput ) { const session = await auth(); @@ -1245,7 +1270,6 @@ export async function POST(request: Request) { return new ChatSDKError("unauthorized:chat").toResponse(); } - const greetingMessage = "你好,我在。你可以直接告诉我想做什么:生图、修图、生成视频、分析图片都可以。"; const fastPathTitle = requestTextContent.trim().slice(0, 80) || "新对话"; await saveChat({ id, @@ -1266,7 +1290,12 @@ export async function POST(request: Request) { const greetingStream = createUIMessageStream({ execute: async ({ writer }) => { const messageId = generateUUID(); - writeAssistantTextChunk(writer, greetingMessage, "greeting-fast-path", messageId); + writeAssistantTextChunk( + writer, + canvasFastPathMessage, + isCapabilityQuestionRequest ? "capability-fast-path" : "greeting-fast-path", + messageId + ); await saveMessages({ messages: [ @@ -1287,7 +1316,7 @@ export async function POST(request: Request) { id: messageId, chatId: id, role: "assistant", - parts: [{ type: "text", text: greetingMessage }], + parts: [{ type: "text", text: canvasFastPathMessage }], attachments: [], createdAt: new Date(), videoStorageStatus: null, @@ -8625,10 +8654,16 @@ export async function POST(request: Request) { selectedChatModel: finalModelId, requestHints, }); - const agentIdentityInstruction = shouldRunAgentConversation + const shouldUseProductIdentityInstruction = + shouldRunAgentConversation || + isCanvasPageRequest || + contextPayload?.source === "canvas" || + Boolean(requestCanvasAgentContext); + const agentIdentityInstruction = shouldUseProductIdentityInstruction ? await buildAgentRoleIdentityInstruction({ allowVideoGeneration: allowAgentVideoGeneration, hasCanvasContext: Boolean( + isCanvasPageRequest || effectiveContextPayload?.source === "canvas" || effectiveContextPayload?.selectedNodeIds?.length || effectiveContextPayload?.canvasImageNodes?.length, diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 40964a6df..8b7e3f299 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -1595,21 +1595,15 @@ function OpenClawQuickActions({ ); } -function CanvasAssistantTypingPlaceholder({ hint }: { hint?: string | null }) { +function CanvasAssistantTypingPlaceholder({ + hint, + label = "分析中", +}: { + hint?: string | null; + label?: string; +}) { return (
-
{hint ? (
@@ -1617,19 +1611,11 @@ function CanvasAssistantTypingPlaceholder({ hint }: { hint?: string | null }) {
) : null}
- {[0, 1, 2].map((index) => ( - - ))} + + {label}
@@ -11910,9 +11896,11 @@ export function CanvasChatPanel({ ); const isLoading = status === 'streaming' || status === 'submitted'; + const activeChatSendGuard = getSendGuard(activeChatId); + const isActiveChatPending = isLoading || activeChatSendGuard.inFlight; const isComposerUploading = Boolean(composerUploadProgress); const isSubmitting = - isLoading || isDetailGenerating || isClawdSubmitting || isComposerUploading; + isActiveChatPending || isDetailGenerating || isClawdSubmitting || isComposerUploading; const hasInputOrAttachments = Boolean( input.trim() || attachments.length > 0 || (!isDetailGenerationMode && selectedSkillTag) ); @@ -12287,15 +12275,23 @@ export function CanvasChatPanel({ const isDetailEmptyState = isDetailGenerationMode && renderableVisibleMessages.length === 0 && - !isLoading && + !isActiveChatPending && !shouldShowImageLoading; const isPlainCanvasEmptyState = !isWorkspacePresentation && !isDetailGenerationMode && !isVideoWorkspace && renderableVisibleMessages.length === 0 && - !isLoading && + !isActiveChatPending && !shouldShowImageLoading; + const latestRenderableMessage = renderableVisibleMessages.at(-1); + const shouldRenderAssistantTypingPlaceholder = + !isClawdMode && + !isDetailGenerationMode && + !shouldRenderImageLoading && + !hasActiveTypewriter && + isActiveChatPending && + latestRenderableMessage?.role === "user"; const workspaceEmptyTitle = isClawdMode ? `开始 ${CLAW_MODE_LABEL} 对话` @@ -13490,9 +13486,7 @@ export function CanvasChatPanel({ shouldAnimateAnalysis || shouldAnimatePlainText || isClawdSubmitting || - getSendGuard(activeChatId).inFlight || - status === "streaming" || - status === "submitted" + isActiveChatPending } onAction={handleOpenClawQuickAction} /> @@ -13564,9 +13558,13 @@ export function CanvasChatPanel({ estimatedWaitMs={loadingEstimatedWaitMs} /> )} + + {shouldRenderAssistantTypingPlaceholder ? ( + + ) : null} {isClawdMode && isClawdSubmitting ? ( - + ) : null}
diff --git a/lib/ai/runtime/task-boundary-classifier.ts b/lib/ai/runtime/task-boundary-classifier.ts index a4dddf4a2..fe6991ed2 100644 --- a/lib/ai/runtime/task-boundary-classifier.ts +++ b/lib/ai/runtime/task-boundary-classifier.ts @@ -5,6 +5,7 @@ import type { PendingGridConfirmation, } from "@/lib/ai/conversation-action-resolver"; import { isExplicitPromptOptimizationRequest } from "@/lib/ai/smart-analyzer"; +import { isCapabilityQuestionTurnRequest } from "@/lib/ai/runtime/task-boundary-text"; import { detectStoryboardCommandIntent } from "@/lib/video-agent/storyboard-command-interpreter"; export type TaskBoundaryType = @@ -88,9 +89,7 @@ function isLikelyChatOnlyRequest(text: string): boolean { const normalized = normalizeCompactText(text); if (!normalized) return false; - return /你能做什么|你会什么|你可以做什么|你能帮我做什么|你能干什么|你可以帮我做什么|介绍一下你自己|介绍一下自己|说说你的能力|你有哪些功能|你有什么功能|怎么用|怎么玩|如何使用|帮助说明|帮助手册|功能介绍/.test( - normalized, - ); + return isCapabilityQuestionTurnRequest(normalized); } function isLikelyAnalysisOnlyRequest(text: string, hasImageContext: boolean): boolean { diff --git a/lib/ai/runtime/task-boundary-text.ts b/lib/ai/runtime/task-boundary-text.ts new file mode 100644 index 000000000..dad761f7f --- /dev/null +++ b/lib/ai/runtime/task-boundary-text.ts @@ -0,0 +1,12 @@ +export function normalizeCompactTaskBoundaryText(text: string) { + return String(text || "").toLowerCase().replace(/\s+/g, "").trim(); +} + +export function isCapabilityQuestionTurnRequest(text: string): boolean { + const normalized = normalizeCompactTaskBoundaryText(text); + if (!normalized) return false; + + return /你.*(?:能|会|可以|可|嫩)?.*(?:为我做什么|帮我做什么|帮我什么|做什么|干什么)|你.*(?:有哪些|有什么).*(?:功能|能力)|(?:介绍|说说).*(?:功能|能力|你自己|自己)|怎么用|怎么玩|如何使用|帮助说明|帮助手册|功能介绍/.test( + normalized, + ); +} diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index 6b0027ab4..bb5d878e7 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -56,6 +56,7 @@ import { buildRecentDialogueMemory, isRecentDialogueRecallRequest, } from "@/lib/ai/runtime/recent-dialogue-memory"; +import { isCapabilityQuestionTurnRequest } from "@/lib/ai/runtime/task-boundary-text"; import { isAgentModeScopedChatId, isScopedEmptyHistoryRequest, @@ -326,6 +327,13 @@ test.describe("canvas chat pure helpers", () => { expect(upstream).toContain("| SKU | 销量 |"); }); + test("recognizes canvas product capability questions with typo tolerance", () => { + expect(isCapabilityQuestionTurnRequest("你能为我做什么?")).toBe(true); + expect(isCapabilityQuestionTurnRequest("你嫩为我做什么?")).toBe(true); + expect(isCapabilityQuestionTurnRequest("你有哪些功能")).toBe(true); + expect(isCapabilityQuestionTurnRequest("帮我把这张图换成白底")).toBe(false); + }); + test("builds bounded recent dialogue memory for user recall requests", () => { const memory = buildRecentDialogueMemory({ messages: [ From 4ac4ac26cfa5f146e6d914a69e37d4382145101a Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 21:07:18 +0800 Subject: [PATCH 13/29] fix canvas agent image generation status --- app/(chat)/api/chat/route.ts | 31 +++++++++++++++++++++++++++ components/canvas/CanvasChatPanel.tsx | 22 ++++++++++++------- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/app/(chat)/api/chat/route.ts b/app/(chat)/api/chat/route.ts index 67e892f9b..fcbfd0b3d 100644 --- a/app/(chat)/api/chat/route.ts +++ b/app/(chat)/api/chat/route.ts @@ -7896,6 +7896,32 @@ export async function POST(request: Request) { operationLabel: "agent-generate-image", resultType: "image", }); + const directImageStatusPayload = { + providerType: requestedModelProviderType, + modelName: finalModelId, + imageCount: + effectiveImageParams?.imageCount || + defaultImageQualityParams.imageCount || + 1, + }; + const stopDirectImageKeepalive = startStreamKeepalive( + writer, + "agent:generate_image", + DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS, + ); + const stopDirectImageStatus = + contextPayload?.source === "canvas" + ? setInterval(() => { + writeImageGenerationStatusChunk( + writer, + { + phase: "processing", + ...directImageStatusPayload, + }, + "agent:generate_image:status-processing-keepalive", + ); + }, DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS) + : null; try { const directImageResult = await executeDirectAgentImageGeneration({ requestTextContent, @@ -8037,6 +8063,11 @@ export async function POST(request: Request) { "", "agent:generate_image:end-error", ); + } finally { + stopDirectImageKeepalive(); + if (stopDirectImageStatus) { + clearInterval(stopDirectImageStatus); + } } }, }); diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 8b7e3f299..c16e2d7a5 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -11006,16 +11006,20 @@ export function CanvasChatPanel({ metadata: optimisticUserMetadata, } as ChatMessage; + setMessages((previousMessages) => + sortCanvasMessagesByCreatedAt([ + ...previousMessages.filter((message) => message.id !== userMessageId), + optimisticUserMessage, + ]) + ); + // 使用与 multimodal-input 相同的格式发送消息 try { sendMessage(optimisticUserMessage as any); - setMessages((previousMessages) => - sortCanvasMessagesByCreatedAt([ - ...previousMessages.filter((message) => message.id !== userMessageId), - optimisticUserMessage, - ]) - ); } catch (error) { + setMessages((previousMessages) => + previousMessages.filter((message) => message.id !== userMessageId) + ); releaseSendGuard(activeChatId); if (shouldShowOptimisticImageGeneration) { clearStreamImageGenerationStateForChat(activeChatId); @@ -12010,8 +12014,10 @@ export function CanvasChatPanel({ ) ); const shouldShowImageLoading = - ((hasGenerationStart && !hasGenerationEnd) || Boolean(streamImageGenerationState)) && - !!currentModel; + Boolean(streamImageGenerationState) || + (hasGenerationStart && + !hasGenerationEnd && + Boolean(currentModel || activeComposerMode === "agent")); const hasActiveTypewriter = Object.keys(activeTypingSections).length > 0; const shouldRenderImageLoading = shouldShowImageLoading && !hasActiveTypewriter; const loadingImageCount = streamImageGenerationState?.imageCount || imageParams.imageCount || 1; From e2e373ce08a6ac9337fd1cc18c8b6556a25e3123 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 21:21:12 +0800 Subject: [PATCH 14/29] fix canvas agent duplicate user message --- components/canvas/CanvasChatPanel.tsx | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index c16e2d7a5..77179b7d1 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -11006,20 +11006,16 @@ export function CanvasChatPanel({ metadata: optimisticUserMetadata, } as ChatMessage; - setMessages((previousMessages) => - sortCanvasMessagesByCreatedAt([ - ...previousMessages.filter((message) => message.id !== userMessageId), - optimisticUserMessage, - ]) - ); - // 使用与 multimodal-input 相同的格式发送消息 try { sendMessage(optimisticUserMessage as any); - } catch (error) { setMessages((previousMessages) => - previousMessages.filter((message) => message.id !== userMessageId) + sortCanvasMessagesByCreatedAt([ + ...previousMessages.filter((message) => message.id !== userMessageId), + optimisticUserMessage, + ]) ); + } catch (error) { releaseSendGuard(activeChatId); if (shouldShowOptimisticImageGeneration) { clearStreamImageGenerationStateForChat(activeChatId); From 51283b81fb85523a524da4f468d353abc8424a64 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 21:38:24 +0800 Subject: [PATCH 15/29] fix canvas cutout intent routing --- lib/ai/runtime/canvas-agent-kernel.ts | 4 +- lib/ai/runtime/intent-arbiter.ts | 32 ++++++------- lib/ai/smart-analyzer.ts | 10 ++-- lib/ai/specialists/index.ts | 2 +- tests/routes/canvas-chat-helpers.test.ts | 60 ++++++++++++++++++++++++ 5 files changed, 82 insertions(+), 26 deletions(-) diff --git a/lib/ai/runtime/canvas-agent-kernel.ts b/lib/ai/runtime/canvas-agent-kernel.ts index 68467384f..6c5ae36f2 100644 --- a/lib/ai/runtime/canvas-agent-kernel.ts +++ b/lib/ai/runtime/canvas-agent-kernel.ts @@ -20,7 +20,7 @@ const DEICTIC_TARGET_REGEX = /(这张图|这只|这个|这款|这套|当前这张|当前这个|当前这只|这一张|这一只|这个产品|这个物体|这只猫|这只狗)/i; const ACTIONABLE_IMAGE_EDIT_REGEX = - /(抠图|去背景|透明背景|去背|扣图|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|调色|调整颜色|亮度|对比度|饱和度|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调|处理)/i; + /(抠图|去背景|透明背景|去背|扣图|抠出|扣出|抠出来|扣出来|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|调色|调整颜色|亮度|对比度|饱和度|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调|处理)/i; export function normalizeCanvasAgentRequestText(text: string) { return String(text || "").toLowerCase().replace(/\s+/g, "").trim(); @@ -42,7 +42,7 @@ export function inferCanvasAgentImageEditCapability( if (/去水印|水印|去logo|移除logo|去除logo/.test(normalizedText)) { return "remove_watermark"; } - if (/抠图|去背景|透明背景|去背|扣图|移除背景/.test(normalizedText)) { + if (/抠图|去背景|透明背景|去背|扣图|抠出|扣出|抠出来|扣出来|移除背景/.test(normalizedText)) { return "remove_background"; } if (/多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位/.test(normalizedText)) { diff --git a/lib/ai/runtime/intent-arbiter.ts b/lib/ai/runtime/intent-arbiter.ts index ce1081ef1..4cb6141b0 100644 --- a/lib/ai/runtime/intent-arbiter.ts +++ b/lib/ai/runtime/intent-arbiter.ts @@ -94,10 +94,10 @@ function isExplicitImageGenerationRequest(text: string): boolean { const visualTarget = "(?:图|图片|海报|头像|插画|场景|主图|产品图|商品图|电商图|壁纸|封面|logo|图标)"; const createVisualTarget = new RegExp( - `(?:生成|创作|创建|制作|设计|做|出|画|绘制)${countToken}?张?.{0,32}${visualTarget}`, + `(?:生成|创作|创建|制作|设计|做|出|画(?!布)|绘制)${countToken}?张?.{0,32}${visualTarget}`, ); const drawSubject = new RegExp( - `(?:画|绘制|生成|创作|创建)${countToken}?(?:只|个|位|幅|张)?.{0,24}(?:小猫|猫咪|猫|狗|人物|角色|ip|头像|logo|图标|插画)`, + `(?:画(?!布)|绘制|生成|创作|创建)${countToken}?(?:只|个|位|幅|张)?.{0,24}(?:小猫|猫咪|猫|狗|人物|角色|ip|头像|logo|图标|插画)`, ); const continueVariants = new RegExp( `(?:再来|再出|再做|再给我|补|多来|继续生成|继续出)${countToken}?张`, @@ -197,6 +197,9 @@ function buildExecutionFromAnalysis(params: { targetSource: ResolvedTargetAssets["resolutionMode"]; }): IntentArbiterExecution { const mode = mapIntentToMode(params.analysis.intent, params.analysis.needsClarification); + const shouldKeepPlannedToolCalls = + params.execution?.mode === mode && + params.execution?.routeIntent === params.analysis.intent; return { mode, @@ -218,7 +221,7 @@ function buildExecutionFromAnalysis(params: { shouldStayConversational: mode === "respond" || mode === "analyze_image" || mode === "clarify", shouldPublishToCanvas: params.execution?.shouldPublishToCanvas || false, - toolCalls: params.execution?.toolCalls || [], + toolCalls: shouldKeepPlannedToolCalls ? params.execution?.toolCalls || [] : [], availableTools: params.execution?.availableTools || [], }; } @@ -262,6 +265,14 @@ function resolvePolicyIntent(params: { }; } + if (hasUsableImage && likelyEdit) { + return { + intent: "image_edit", + subIntent: params.analysis.subIntent || inferDefaultImageEditSubIntent(params.text), + reason: "image_edit_policy_override", + }; + } + switch (params.actionResolution.kind) { case "image_edit_followup": return { @@ -292,13 +303,6 @@ function resolvePolicyIntent(params: { reason: "task_boundary_execution_video", }; case "execution_image": - if (hasUsableImage && likelyEdit && !explicitImageGen) { - return { - intent: "image_edit", - subIntent: params.analysis.subIntent || inferDefaultImageEditSubIntent(params.text), - reason: "task_boundary_execution_image_edit", - }; - } return { intent: "image_gen", reason: "task_boundary_execution_image_generate", @@ -329,14 +333,6 @@ function resolvePolicyIntent(params: { }; } - if (hasUsableImage && likelyEdit && params.analysis.intent === "chat") { - return { - intent: "image_edit", - subIntent: params.analysis.subIntent || inferDefaultImageEditSubIntent(params.text), - reason: "image_edit_policy_override", - }; - } - return { intent: params.analysis.intent, subIntent: diff --git a/lib/ai/smart-analyzer.ts b/lib/ai/smart-analyzer.ts index 3bde4b6ee..c22451481 100644 --- a/lib/ai/smart-analyzer.ts +++ b/lib/ai/smart-analyzer.ts @@ -33,7 +33,7 @@ export interface AnalysisResult { function inferDefaultImageEditSubIntent(text: string): AnalysisResult["subIntent"] { const lowerText = text.toLowerCase(); if (/去水印|水印|去logo|去\s*logo|移除logo|去除logo/.test(lowerText)) return "remove_watermark"; - if (/抠图|去背景|透明背景|去背|扣图|移除背景/.test(lowerText)) return "remove_background"; + if (/抠图|去背景|透明背景|去背|扣图|抠出|扣出|抠出来|扣出来|移除背景/.test(lowerText)) return "remove_background"; if (/换背景|改背景|背景换成|背景改成|白底|透明底/.test(lowerText)) return "replace_background"; if (/多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位/.test(lowerText)) return "angle_variant"; if (hasDirectAgentLocalEditIntent(text)) return "local_edit"; @@ -112,10 +112,10 @@ export function isExplicitImageGenerationRequest(text: string): boolean { const visualTarget = "(?:图|图片|海报|头像|插画|场景|主图|产品图|商品图|电商图|壁纸|封面|logo|图标)"; const createVisualTarget = new RegExp( - `(?:生成|创作|创建|制作|设计|做|出|画|绘制)${countToken}?张?.{0,32}${visualTarget}`, + `(?:生成|创作|创建|制作|设计|做|出|画(?!布)|绘制)${countToken}?张?.{0,32}${visualTarget}`, ); const drawSubject = new RegExp( - `(?:画|绘制|生成|创作|创建)${countToken}?(?:只|个|位|幅|张)?.{0,24}(?:小猫|猫咪|猫|狗|人物|角色|ip|头像|logo|图标|插画)`, + `(?:画(?!布)|绘制|生成|创作|创建)${countToken}?(?:只|个|位|幅|张)?.{0,24}(?:小猫|猫咪|猫|狗|人物|角色|ip|头像|logo|图标|插画)`, ); const continueVariants = new RegExp( `(?:再来|再出|再做|再给我|补|多来|继续生成|继续出)${countToken}?张`, @@ -141,7 +141,7 @@ export function isExplicitImageGenerationRequest(text: string): boolean { function isLikelyImageEditRequest(text: string): boolean { const normalizedText = text.toLowerCase(); - return hasDirectAgentLocalEditIntent(text) || /抠图|去背景|透明背景|去背|扣图|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|换成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|改成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|比例|画幅|竖版|横版|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|转.*风格|变.*风格|改.*风格|调色|调整颜色|亮度|对比度|饱和度|色调|曝光|滤镜|改成.*色|换成.*色|变成.*色|颜色改成|颜色换成|颜色变成|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调/.test( + return hasDirectAgentLocalEditIntent(text) || /抠图|去背景|透明背景|去背|扣图|抠出|扣出|抠出来|扣出来|移除背景|去水印|水印|去logo|去\s*logo|移除logo|去除logo|换背景|改背景|背景换成|背景改成|白底|纯色背景|替换.*背景|变清晰|高清|锐化|降噪|提升质量|修复|清晰化|扩展|拓展|延伸|扩图|outpainting|拓宽|扩大|换成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|改成.*(?:比例|竖版|横版|竖图|横图|9:16|16:9|1:1)|比例|画幅|竖版|横版|多视角|换视角|改视角|视角变体|新角度|换角度|改角度|侧面|侧视|背面|背后|俯视|俯拍|仰视|仰拍|低机位|高机位|去除|消除|擦掉|删除|移除|p掉|重绘|风格化|卡通化|动漫风|油画风|转.*风格|变.*风格|改.*风格|调色|调整颜色|亮度|对比度|饱和度|色调|曝光|滤镜|改成.*色|换成.*色|变成.*色|颜色改成|颜色换成|颜色变成|缩放|放大|缩小|调整尺寸|裁剪|resize|crop|修图|p图|改图|调图|编辑.*图|优化.*图|重做|再调整|继续改|继续调/.test( normalizedText, ); } @@ -2331,7 +2331,7 @@ export function fallbackKeywordAnalysis( } // 抠图/去背景 - if (/抠图|去背景|透明背景|去背|扣图|移除背景/.test(lowerText)) { + if (/抠图|去背景|透明背景|去背|扣图|抠出|扣出|抠出来|扣出来|移除背景/.test(lowerText)) { return { intent: "image_edit", subIntent: "remove_background", diff --git a/lib/ai/specialists/index.ts b/lib/ai/specialists/index.ts index f91793f61..75827ad67 100644 --- a/lib/ai/specialists/index.ts +++ b/lib/ai/specialists/index.ts @@ -250,7 +250,7 @@ function normalizeEditCapability( subIntent: "remove_watermark", }; } - if (subIntent === "remove_background" || /抠图|去背|去背景|透明底/.test(normalizedText)) { + if (subIntent === "remove_background" || /抠图|去背|去背景|透明底|抠出|扣出|抠出来|扣出来/.test(normalizedText)) { return { capability: "remove_background", toolName: "removeBackground", diff --git a/tests/routes/canvas-chat-helpers.test.ts b/tests/routes/canvas-chat-helpers.test.ts index bb5d878e7..ee23944a0 100644 --- a/tests/routes/canvas-chat-helpers.test.ts +++ b/tests/routes/canvas-chat-helpers.test.ts @@ -48,9 +48,11 @@ import { import { shouldBypassCanvasAgentMissingTargetClarification } from "@/lib/ai/runtime/canvas-agent-clarification"; import { hasCanvasAgentRoutingContext } from "@/lib/ai/canvas-agent-routing"; import { + inferCanvasAgentImageEditCapability, resolveCanvasAgentRequestPolicy, resolveCanvasAgentTargetPreference, } from "@/lib/ai/runtime/canvas-agent-kernel"; +import { isExplicitImageGenerationRequest } from "@/lib/ai/smart-analyzer"; import { inferAgentImageCountFromText } from "@/lib/ai/runtime/image-count-intent"; import { buildRecentDialogueMemory, @@ -1463,6 +1465,64 @@ test.describe("canvas chat pure helpers", () => { expect(directContext?.targetImageUrl).toBe(canvasImageUrl); }); + test("routes canvas subject cutout wording to remove background instead of image generation", () => { + const canvasImageUrl = "https://cdn.example.com/canvas-dog.png"; + const userText = "帮我将画布中的狗的图扣出来"; + + expect(isExplicitImageGenerationRequest(userText)).toBe(false); + expect(inferCanvasAgentImageEditCapability(userText)).toBe("remove_background"); + + const directContext = resolveDirectAgentToolContext({ + execution: { + mode: "edit_image", + routeIntent: "image_edit", + routeSubIntent: "remove_background", + targetSource: "text_reference", + preferredCapability: "remove_background", + shouldUseStructuredReply: true, + shouldOptimizePrompt: true, + shouldApplyImagePipeline: true, + shouldApplyVideoPipeline: false, + shouldStayConversational: false, + shouldPublishToCanvas: false, + toolCalls: [], + availableTools: ["resolveTargetImage", "removeBackground"], + } as any, + requestResolvedMediaInput: { + imageRefs: [], + currentMessageImageRefs: [], + selectedImageRefs: [], + canvasImageRefs: [ + { + url: canvasImageUrl, + normalizedUrl: canvasImageUrl, + nodeId: "dog-node", + source: "canvas_context", + role: "reference", + }, + ], + historyUserImageRefs: [], + historyAssistantImageRefs: [], + resolvedImageRefs: [], + currentMessageImageUrls: [], + selectedImageUrls: [], + canvasImageUrls: [canvasImageUrl], + historyUserImageUrls: [], + historyAssistantImageUrls: [], + resolvedImageUrls: [], + selectedAssetIds: [], + candidateAssetIds: [], + uploadedAssetIds: [], + hasImage: true, + source: "canvas_context", + fromHistory: false, + } as any, + }); + + expect(directContext?.execution.toolName).toBe("removeBackground"); + expect(directContext?.targetImageUrl).toBe(canvasImageUrl); + }); + test("only runs direct image edit batches for explicit safe batch requests", () => { expect( shouldRunDirectAgentBatchImageEdit({ From a03ea2cb479dd5bf98df61aea0256e68c851c5aa Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 22:13:39 +0800 Subject: [PATCH 16/29] fix: persist claw chat sessions --- components/canvas/CanvasChatPanel.tsx | 137 +++++++++++++++++++++++--- 1 file changed, 123 insertions(+), 14 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 77179b7d1..292dc228d 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -2432,6 +2432,33 @@ export function CanvasChatPanel({ ); }, [getSendGuard]); + const persistChatSessions = useCallback( + (sessions: CanvasChatSession[]) => { + const sessionStorageKey = getSessionStorageKey(canvasId, chatScope); + try { + localStorage.setItem(sessionStorageKey, JSON.stringify(sessions)); + setLoadedChatSessionStorageKey(sessionStorageKey); + } catch (error) { + console.error("[CanvasChat] Failed to save chat sessions:", error); + } + }, + [canvasId, chatScope] + ); + + const updateChatSessions = useCallback( + (updater: (previousSessions: CanvasChatSession[]) => CanvasChatSession[]) => { + setChatSessions((previousSessions) => { + const nextSessions = updater(previousSessions); + if (nextSessions === previousSessions) { + return previousSessions; + } + persistChatSessions(nextSessions); + return nextSessions; + }); + }, + [persistChatSessions] + ); + const startNewChatSession = useCallback( (options?: { mode?: CanvasComposerMode; @@ -2462,13 +2489,19 @@ export function CanvasChatPanel({ forceHistoryHydrationRef.current = null; releaseSendGuard(activeChatId); - setChatSessions((prevSessions) => [newSession, ...prevSessions]); + updateChatSessions((prevSessions) => [newSession, ...prevSessions]); setActiveChatId(newChatSessionId); replaceChatSessionQuery(newChatSessionId); toast.success(options?.toastMessage || "已新建聊天窗口"); return newChatSessionId; }, - [activeChatId, chatSessions, releaseSendGuard, replaceChatSessionQuery] + [ + activeChatId, + chatSessions, + releaseSendGuard, + replaceChatSessionQuery, + updateChatSessions, + ] ); const setSessionClawdSkillTag = useCallback( @@ -2479,11 +2512,12 @@ export function CanvasChatPanel({ ) => { if (!chatSessionId) return; const normalizedTagId = String(tagId || "").trim() || null; - setChatSessions((prevSessions) => + updateChatSessions((prevSessions) => prevSessions.map((session) => session.id === chatSessionId ? { ...session, + mode: "clawd", clawdSkillTagId: normalizedTagId, clawdSkillTagPromptApplied: normalizedTagId === null @@ -2495,17 +2529,18 @@ export function CanvasChatPanel({ ) ); }, - [] + [updateChatSessions] ); const markSessionClawdSkillTagPromptApplied = useCallback( (chatSessionId: string, tagId: string) => { if (!chatSessionId || !tagId) return; - setChatSessions((prevSessions) => + updateChatSessions((prevSessions) => prevSessions.map((session) => session.id === chatSessionId && session.clawdSkillTagId === tagId ? { ...session, + mode: "clawd", clawdSkillTagPromptApplied: true, updatedAt: Date.now(), } @@ -2513,7 +2548,7 @@ export function CanvasChatPanel({ ) ); }, - [] + [updateChatSessions] ); const handleTypewriterActiveChange = useCallback((typingKey: string, active: boolean) => { @@ -4510,12 +4545,84 @@ export function CanvasChatPanel({ activeChatSession, activeComposerMode ); + useEffect(() => { + if (activeChatSessionMode !== "clawd") return; + if (!isClawdModeEnabled) return; + if (activeComposerMode !== "clawd") { + setComposerModeOverride("clawd"); + } + if (isDetailGenerationMode) { + setIsDetailGenerationMode(false); + } + }, [ + activeChatSessionMode, + activeComposerMode, + isClawdModeEnabled, + isDetailGenerationMode, + ]); + + useEffect(() => { + if (!activeChatId) return; + const historyMessages = historyData?.messages || []; + if (historyMessages.length === 0) return; + if (!historyMessages.some(isClawdChatMessage)) return; + + updateChatSessions((prevSessions) => { + const currentIndex = prevSessions.findIndex( + (session) => session.id === activeChatId + ); + const now = Date.now(); + + if (currentIndex < 0) { + const title = + deriveSessionTitleFromMessages(historyMessages) || `${CLAW_MODE_LABEL} 对话`; + return [ + { + id: activeChatId, + title, + mode: "clawd", + createdAt: now, + updatedAt: now, + }, + ...prevSessions, + ]; + } + + const current = prevSessions[currentIndex]; + if (getCanvasChatSessionMode(current) === "clawd") { + return prevSessions; + } + + const nextSessions = [...prevSessions]; + nextSessions[currentIndex] = { + ...current, + mode: "clawd", + updatedAt: Math.max(Number(current.updatedAt) || 0, now), + }; + nextSessions.sort((a, b) => b.updatedAt - a.updatedAt); + return nextSessions; + }); + + if (isClawdModeEnabled && activeComposerMode !== "clawd") { + setComposerModeOverride("clawd"); + if (isDetailGenerationMode) { + setIsDetailGenerationMode(false); + } + } + }, [ + activeChatId, + activeComposerMode, + historyData?.messages, + isClawdModeEnabled, + isDetailGenerationMode, + updateChatSessions, + ]); const currentModeChatSessions = useMemo( () => chatSessions.filter( - (session) => getCanvasChatSessionMode(session) === activeComposerMode + (session) => getCanvasChatSessionMode(session) === activeChatSessionMode ), - [activeComposerMode, chatSessions] + [activeChatSessionMode, chatSessions] ); const agentSelectableModels = useMemo( () => @@ -5319,7 +5426,7 @@ export function CanvasChatPanel({ if (canReuseActiveEmptySession) { forceHistoryHydrationRef.current = null; targetChatSessionId = activeChatId; - setChatSessions((prevSessions) => + updateChatSessions((prevSessions) => prevSessions.map((session) => session.id === activeChatId ? { @@ -5404,6 +5511,7 @@ export function CanvasChatPanel({ releaseSendGuard, replaceChatSessionQuery, startNewChatSession, + updateChatSessions, ] ); @@ -7216,7 +7324,7 @@ export function CanvasChatPanel({ const derivedTitle = deriveSessionTitleFromMessages(messages); const now = Date.now(); - setChatSessions((prevSessions) => { + updateChatSessions((prevSessions) => { const currentIndex = prevSessions.findIndex( (session) => session.id === activeChatId ); @@ -7252,7 +7360,7 @@ export function CanvasChatPanel({ nextSessions.sort((a, b) => b.updatedAt - a.updatedAt); return nextSessions; }); - }, [activeChatId, messages]); + }, [activeChatId, messages, updateChatSessions]); useEffect(() => { if (activeChatSessionMode === "clawd") return; @@ -10550,7 +10658,7 @@ export function CanvasChatPanel({ }, } as ChatMessage; - setChatSessions((prevSessions) => + updateChatSessions((prevSessions) => prevSessions.map((session) => session.id === activeChatId ? { @@ -11096,6 +11204,7 @@ export function CanvasChatPanel({ status, mutate, markSessionClawdSkillTagPromptApplied, + updateChatSessions, buildHistoryMessagesUrl, workflowContext, messages, @@ -12473,8 +12582,8 @@ export function CanvasChatPanel({ ); const createNewChatSession = useCallback(() => { - startNewChatSession({ mode: activeComposerMode }); - }, [activeComposerMode, startNewChatSession]); + startNewChatSession({ mode: activeChatSessionMode }); + }, [activeChatSessionMode, startNewChatSession]); const switchToSession = useCallback((sessionId: string) => { if (!sessionId || sessionId === activeChatId) { From 6bc43ffc3f924a23541b3a015cc4f3c080be84ce Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 22:16:07 +0800 Subject: [PATCH 17/29] perf: improve home and canvas initial load --- .../[id]/CanvasEditorLegacyPageClient.tsx | 12 +++-- components/home/lovart-home.tsx | 46 +++++++++++++++++-- .../home/lovart/lovart-featured-gallery.tsx | 2 + .../home/lovart/lovart-hero-composer.tsx | 15 +++++- .../home/lovart/lovart-projects-section.tsx | 2 + 5 files changed, 68 insertions(+), 9 deletions(-) diff --git a/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx b/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx index 8e501117e..2a48e250c 100644 --- a/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx +++ b/app/canvas/[id]/CanvasEditorLegacyPageClient.tsx @@ -1976,7 +1976,7 @@ export default function CanvasEditorLegacyPage({ ); const [activeWorkflowExecutionTaskKey, setActiveWorkflowExecutionTaskKey] = useState(null); - const [isPanelOpen, setIsPanelOpen] = useState(() => !isVideoMode); + const [isPanelOpen, setIsPanelOpen] = useState(() => requestedAgentMode); const [floatingPanelWidth, setFloatingPanelWidth] = useState(FLOATING_PANEL_WIDTH); const [ @@ -3280,11 +3280,15 @@ export default function CanvasEditorLegacyPage({ }, [checkCanvasAuthSession]); useEffect(() => { + if (!isPanelOpen && !isVideoCanvasFileListOpen) { + return; + } + const timeoutId = window.setTimeout(() => { setAreSecondaryPanelsReady(true); - }, 800); + }, 120); return () => window.clearTimeout(timeoutId); - }, []); + }, [isPanelOpen, isVideoCanvasFileListOpen]); const hydrateCanvasProject = useCallback( (project: CanvasInitialProject) => { @@ -10844,7 +10848,7 @@ export default function CanvasEditorLegacyPage({
) : null}
- {!areSecondaryPanelsReady ? ( + {!isPanelOpen ? null : !areSecondaryPanelsReady ? ( ) : panelMode === "chat" ? ( // AI 对话内容 - 使用 key 强制在 id 变化时重新挂载 diff --git a/components/home/lovart-home.tsx b/components/home/lovart-home.tsx index 5c9565254..6751449a0 100644 --- a/components/home/lovart-home.tsx +++ b/components/home/lovart-home.tsx @@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useRouter } from "next/navigation"; -import { signIn, signOut } from "next-auth/react"; import { useTheme } from "next-themes"; import useSWR from "swr"; import useSWRInfinite from "swr/infinite"; @@ -60,7 +59,6 @@ import { getCanvasLaunchStorageKey, } from "@/lib/canvas-launch"; import type { MembershipConfig } from "@/lib/membership/config"; -import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry"; import { normalizeLovartHomeSidebarConfig, type LovartHomeSidebarItemKey, @@ -465,6 +463,7 @@ export function LovartHome({ const [previewCursorVisible, setPreviewCursorVisible] = useState(true); const [isSecondaryDataReady, setIsSecondaryDataReady] = useState(false); const [isFeaturedDataReady, setIsFeaturedDataReady] = useState(false); + const [isHomeAnimationReady, setIsHomeAnimationReady] = useState(false); const projectSectionRef = useRef(null); const featuredSectionRef = useRef(null); const featuredLoadMoreRef = useRef(null); @@ -535,6 +534,31 @@ export function LovartHome({ }; }, [isFeaturedDataReady]); + useEffect(() => { + if (typeof window === "undefined" || !isSecondaryDataReady) { + return; + } + + const loadHomeAnimation = () => setIsHomeAnimationReady(true); + const idleWindow = window as Window & { + cancelIdleCallback?: (handle: number) => void; + requestIdleCallback?: ( + callback: IdleRequestCallback, + options?: IdleRequestOptions + ) => number; + }; + + if (typeof idleWindow.requestIdleCallback === "function") { + const idleId = idleWindow.requestIdleCallback(loadHomeAnimation, { + timeout: 3200, + }); + return () => idleWindow.cancelIdleCallback?.(idleId); + } + + const timer = window.setTimeout(loadHomeAnimation, 1800); + return () => window.clearTimeout(timer); + }, [isSecondaryDataReady]); + const { data: canvasData, mutate: mutateCanvas } = useSWR<{ success: boolean; data: CanvasProject[]; @@ -671,7 +695,10 @@ export function LovartHome({ enabled?: boolean; htmlContent?: string; fileName?: string; - }>(isSecondaryDataReady ? "/api/home-animation" : null, fetcher); + }>( + isSecondaryDataReady && isHomeAnimationReady ? "/api/home-animation" : null, + fetcher + ); const membershipConfig = membershipData?.config; const membershipPlans = membershipConfig?.plans || []; @@ -896,6 +923,7 @@ export function LovartHome({ } catch (_error) {} try { + const { signOut } = await import("next-auth/react"); await signOut({ callbackUrl: "/", redirect: false, @@ -1109,6 +1137,9 @@ export function LovartHome({ }; const uploadSelectedFiles = async (): Promise => { + const { fetchUploadWithRetry } = await import( + "@/lib/client/upload-with-retry" + ); const result: CanvasLaunchAttachment[] = []; for (const item of files) { @@ -1146,6 +1177,7 @@ export function LovartHome({ setIsLoggingIn(true); try { + const { signIn } = await import("next-auth/react"); const result = await signIn("credentials", { email, password: loginPassword, @@ -1171,6 +1203,7 @@ export function LovartHome({ toast.error("Google 登录未启用"); return; } + const { signIn } = await import("next-auth/react"); await signIn("google", { callbackUrl: "/" }); }; @@ -1226,6 +1259,9 @@ export function LovartHome({ const blob = await response.blob(); const formData = new FormData(); formData.append("file", blob, `edited-${Date.now()}.png`); + const { fetchUploadWithRetry } = await import( + "@/lib/client/upload-with-retry" + ); const uploadResponse = await fetchUploadWithRetry(formData); if (!uploadResponse.ok) { @@ -1802,7 +1838,9 @@ export function LovartHome({ heroPromoText={heroPromoText} heroSubtitleText={heroSubtitleText} heroTitleText={heroTitleText} - homeAnimationData={homeAnimationData} + homeAnimationData={ + isHomeAnimationReady ? homeAnimationData : undefined + } isAgentModeActive={isComposerAgentModeActive} isMembershipEnabled={isMembershipEnabled} isSubmitting={isSubmitting} diff --git a/components/home/lovart/lovart-featured-gallery.tsx b/components/home/lovart/lovart-featured-gallery.tsx index f038c1dd1..456f594d6 100644 --- a/components/home/lovart/lovart-featured-gallery.tsx +++ b/components/home/lovart/lovart-featured-gallery.tsx @@ -62,6 +62,8 @@ export function LovartFeaturedGallery({ {item.prompt
diff --git a/components/home/lovart/lovart-hero-composer.tsx b/components/home/lovart/lovart-hero-composer.tsx index c5f491c59..9f5e73568 100644 --- a/components/home/lovart/lovart-hero-composer.tsx +++ b/components/home/lovart/lovart-hero-composer.tsx @@ -1,6 +1,6 @@ +import dynamic from "next/dynamic"; import { ArrowUp, Box, Lightbulb, Loader2, Plus, Sparkles } from "lucide-react"; import type { ChangeEvent } from "react"; -import { HomeAnimationEmbed } from "@/components/home/home-animation-embed"; import { Button } from "@/components/ui/button"; import { Select, @@ -12,6 +12,19 @@ import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; import type { ModelOption, UploadFileItem } from "./types"; +const HomeAnimationEmbed = dynamic( + () => + import("@/components/home/home-animation-embed").then( + (module) => module.HomeAnimationEmbed + ), + { + loading: () => ( +
+ ), + ssr: false, + } +); + type LovartHeroComposerProps = { composerPlaceholder: string; displayLogo: string; diff --git a/components/home/lovart/lovart-projects-section.tsx b/components/home/lovart/lovart-projects-section.tsx index 36ab66f87..28dad8ecf 100644 --- a/components/home/lovart/lovart-projects-section.tsx +++ b/components/home/lovart/lovart-projects-section.tsx @@ -76,6 +76,8 @@ export function LovartProjectsSection({ {item.title} ) : ( From ebfc7589a99b8db89770b8bec727c00b63fdc065 Mon Sep 17 00:00:00 2001 From: 134 Date: Tue, 7 Jul 2026 22:26:04 +0800 Subject: [PATCH 18/29] feat: add global claw chat history --- app/api/canvas/clawd-chat/history/route.ts | 42 +++ components/canvas/CanvasChatPanel.tsx | 321 +++++++++++++++++---- lib/db/queries.ts | 38 +++ 3 files changed, 341 insertions(+), 60 deletions(-) create mode 100644 app/api/canvas/clawd-chat/history/route.ts diff --git a/app/api/canvas/clawd-chat/history/route.ts b/app/api/canvas/clawd-chat/history/route.ts new file mode 100644 index 000000000..822587749 --- /dev/null +++ b/app/api/canvas/clawd-chat/history/route.ts @@ -0,0 +1,42 @@ +import { NextResponse } from "next/server"; +import { auth } from "@/app/(auth)/auth"; +import { getClawdChatsByUserId } from "@/lib/db/queries"; + +export const dynamic = "force-dynamic"; +export const revalidate = 0; + +export async function GET(request: Request) { + const session = await auth().catch(() => null); + + if (!session?.user?.id) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const url = new URL(request.url); + const limit = Math.max( + 1, + Math.min(100, Math.round(Number(url.searchParams.get("limit") || 50))) + ); + + const chats = await getClawdChatsByUserId({ + userId: session.user.id, + limit, + }); + + return NextResponse.json( + { + chats: chats.map((chat) => ({ + id: chat.id, + title: chat.title, + createdAt: chat.createdAt?.toISOString?.() || chat.createdAt, + updatedAt: chat.updatedAt?.toISOString?.() || chat.updatedAt, + messageCount: Number(chat.messageCount || 0), + })), + }, + { + headers: { + "Cache-Control": "no-store, max-age=0", + }, + } + ); +} diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index 292dc228d..24e6b11e8 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -1971,6 +1971,14 @@ interface CanvasChatSession { clawdSkillTagPromptApplied?: boolean; } +interface ClawdHistoryItem { + id: string; + title: string; + createdAt: string | Date; + updatedAt: string | Date; + messageCount: number; +} + const CANVAS_CHAT_QUERY_PARAM = "chat"; const CANVAS_IMAGE_NODE_MANUAL_UPLOAD_EVENT = "canvas:image-node-manual-upload"; @@ -2194,6 +2202,7 @@ export function CanvasChatPanel({ const inFlightRawChatIdRef = useRef(null); const [chatSessions, setChatSessions] = useState([]); const [isSessionMenuOpen, setIsSessionMenuOpen] = useState(false); + const [isClawdHistoryMenuOpen, setIsClawdHistoryMenuOpen] = useState(false); const [isComposerModeMenuOpen, setIsComposerModeMenuOpen] = useState(false); const [selectedSkillTagId, setSelectedSkillTagId] = useState(null); const [areCanvasSkillTagsExpanded, setAreCanvasSkillTagsExpanded] = useState(false); @@ -2239,6 +2248,7 @@ export function CanvasChatPanel({ ); const hasInitializedVideoWorkspaceRef = useRef(false); const sessionMenuRef = useRef(null); + const clawdHistoryMenuRef = useRef(null); const historyScrollTimerRef = useRef | null>(null); const forceHistoryHydrationRef = useRef(null); const copiedUserMessageRef = useRef(null); @@ -2963,6 +2973,17 @@ export function CanvasChatPanel({ return () => document.removeEventListener("mousedown", handleClickOutside); }, [isSessionMenuOpen]); + useEffect(() => { + if (!isClawdHistoryMenuOpen) return; + const handleClickOutside = (event: MouseEvent) => { + if (!clawdHistoryMenuRef.current?.contains(event.target as Node)) { + setIsClawdHistoryMenuOpen(false); + } + }; + document.addEventListener("mousedown", handleClickOutside); + return () => document.removeEventListener("mousedown", handleClickOutside); + }, [isClawdHistoryMenuOpen]); + useEffect(() => { const sessionStorageKey = getSessionStorageKey(canvasId, chatScope); if (loadedChatSessionStorageKey !== sessionStorageKey) return; @@ -4545,6 +4566,19 @@ export function CanvasChatPanel({ activeChatSession, activeComposerMode ); + const clawdHistorySWRKey = + isClawdMode && isClawdHistoryMenuOpen + ? "/api/canvas/clawd-chat/history?limit=80" + : null; + const { + data: clawdHistoryData, + isLoading: isClawdHistoryLoading, + mutate: mutateClawdHistory, + } = useSWR<{ chats: ClawdHistoryItem[] }>(clawdHistorySWRKey, fetcher, { + revalidateOnFocus: false, + revalidateOnReconnect: false, + dedupingInterval: 5000, + }); useEffect(() => { if (activeChatSessionMode !== "clawd") return; if (!isClawdModeEnabled) return; @@ -10785,6 +10819,7 @@ export function CanvasChatPanel({ if (rawChatId) { void mutate(buildHistoryMessagesUrl(rawChatId, { cacheBust: true })); } + void mutateClawdHistory(); hasHydratedHistoryRef.current = true; } catch (error) { console.error("[CanvasChat] Claw request failed:", error); @@ -11203,6 +11238,7 @@ export function CanvasChatPanel({ shouldBlockDuplicateSend, status, mutate, + mutateClawdHistory, markSessionClawdSkillTagPromptApplied, updateChatSessions, buildHistoryMessagesUrl, @@ -12598,6 +12634,70 @@ export function CanvasChatPanel({ toast.success("已切换聊天窗口"); }, [activeChatId, releaseSendGuard, replaceChatSessionQuery]); + const switchToClawdHistorySession = useCallback( + (historyItem: ClawdHistoryItem) => { + const sessionId = normalizeCanvasChatSessionId(historyItem.id); + if (!sessionId) return; + + const updatedAt = Date.parse(String(historyItem.updatedAt || "")) || Date.now(); + const createdAt = Date.parse(String(historyItem.createdAt || "")) || updatedAt; + const title = String(historyItem.title || "").trim() || `${CLAW_MODE_LABEL} 对话`; + + updateChatSessions((prevSessions) => { + const currentIndex = prevSessions.findIndex( + (session) => session.id === sessionId + ); + + if (currentIndex < 0) { + return [ + { + id: sessionId, + title, + mode: "clawd", + createdAt, + updatedAt, + }, + ...prevSessions, + ]; + } + + const nextSessions = [...prevSessions]; + nextSessions[currentIndex] = { + ...nextSessions[currentIndex], + title, + mode: "clawd", + updatedAt: Math.max( + Number(nextSessions[currentIndex]?.updatedAt) || 0, + updatedAt + ), + }; + nextSessions.sort((a, b) => b.updatedAt - a.updatedAt); + return nextSessions; + }); + + forceHistoryHydrationRef.current = toRawCanvasChatId(sessionId); + releaseSendGuard(activeChatId); + setActiveChatId(sessionId); + setComposerModeOverride("clawd"); + setIsDetailGenerationMode(false); + replaceChatSessionQuery(sessionId); + setIsClawdHistoryMenuOpen(false); + toast.success("已打开 Claw 历史对话"); + }, + [activeChatId, releaseSendGuard, replaceChatSessionQuery, updateChatSessions] + ); + + const formatClawdHistoryTime = useCallback((value: string | Date) => { + const timestamp = Date.parse(String(value || "")); + if (!Number.isFinite(timestamp)) return ""; + return new Date(timestamp).toLocaleString("zh-CN", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }); + }, []); + const activeSessionTitle = useMemo(() => { const current = chatSessions.find((session) => session.id === activeChatId); return String(current?.title || "").trim(); @@ -12726,72 +12826,173 @@ export function CanvasChatPanel({ > -
- - {isSessionMenuOpen && ( -
+ - ); - }) + + Claw + + {isClawdHistoryMenuOpen && ( +
+
+
+ Claw 对话历史 +
+ +
+
+ {isClawdHistoryLoading ? ( +
+ + 正在加载 Claw 历史 +
+ ) : (clawdHistoryData?.chats || []).length === 0 ? ( +
+ 暂无 Claw 历史 +
+ ) : ( + (clawdHistoryData?.chats || []).map((item) => { + const sessionId = normalizeCanvasChatSessionId(item.id); + const isActive = sessionId === activeChatId; + const timeLabel = formatClawdHistoryTime(item.updatedAt); + return ( + + ); + }) + )} +
-
- )} -
+ )} +
+ ) : ( +
+ + {isSessionMenuOpen && ( +
+
聊天窗口记录
+
+ {currentModeChatSessions.length === 0 ? ( +
暂无记录
+ ) : ( + currentModeChatSessions.map((session, index) => { + const isActive = session.id === activeChatId; + const timeLabel = new Date(session.updatedAt).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + }); + return ( + + ); + }) + )} +
+
+ )} +
+ )} + ) : null}
@@ -2259,6 +2286,10 @@ export function CanvasChatPanel({ useRef(null); const recentClawdSubmissionRef = useRef(null); + const clawdAbortControllerRef = useRef(null); + const pendingClawdRequestRestoreRef = + useRef(null); + const canceledClawdMessageIdsRef = useRef>(new Set()); const replaceChatSessionQuery = useCallback( (sessionId: string) => { @@ -7120,6 +7151,76 @@ export function CanvasChatPanel({ }, }); + const restorePendingClawdRequestToComposer = useCallback( + (snapshot: PendingClawdRequestRestoreSnapshot) => { + setMessages((previousMessages) => + previousMessages.filter((message) => message.id !== snapshot.userMessageId) + ); + setClawdTableFiles(snapshot.tableFiles); + setAttachments(snapshot.attachments); + + if (snapshot.skillTag && snapshot.shouldRestoreSkillTag) { + setSessionClawdSkillTag(snapshot.chatId, snapshot.skillTag.id, { + promptApplied: false, + }); + setSelectedSkillTagId(snapshot.skillTag.id); + pendingSelectedClawdSkillTagRef.current = snapshot.skillTag; + } + + composerUserEditedAtRef.current = Date.now(); + inputRef.current = snapshot.textContent; + setInput(snapshot.textContent); + + const editableDiv = textareaRef.current as HTMLDivElement | null; + if (editableDiv) { + editableDiv.innerHTML = ""; + editableDiv.textContent = snapshot.textContent; + window.setTimeout(() => { + snapshot.attachments.forEach((attachment, index) => { + if (!attachment.url) return; + insertImageTagInEditor( + attachment.url, + normalizeChatAttachmentName(attachment.name), + index + ); + }); + editableDiv.focus(); + }, 0); + } + }, + [insertImageTagInEditor, setMessages, setSessionClawdSkillTag] + ); + + const handleCancelClawdSubmission = useCallback(() => { + const snapshot = pendingClawdRequestRestoreRef.current; + if (!snapshot) return; + + canceledClawdMessageIdsRef.current.add(snapshot.userMessageId); + pendingClawdRequestRestoreRef.current = null; + pendingClawdSubmissionRef.current = null; + recentClawdSubmissionRef.current = null; + writeStoredClawdComposerSubmissionSnapshot(null); + + void fetch("/api/canvas/clawd-chat/cancel", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + id: snapshot.chatId, + userMessageId: snapshot.userMessageId, + }), + }).catch((error) => { + console.warn("[CanvasChat] Claw cancel request failed:", error); + }); + + clawdAbortControllerRef.current?.abort(); + clawdAbortControllerRef.current = null; + setIsClawdSubmitting(false); + setClawdProcessingHint(null); + releaseSendGuard(snapshot.chatId); + restorePendingClawdRequestToComposer(snapshot); + toast.message("已停止处理,可以重新编辑后再发送"); + }, [releaseSendGuard, restorePendingClawdRequestToComposer]); + useEffect(() => { activeMessagesRef.current = messages; }, [messages]); @@ -10731,6 +10832,19 @@ export function CanvasChatPanel({ pendingClawdSubmissionRef.current = clawdSubmissionSnapshot; recentClawdSubmissionRef.current = clawdSubmissionSnapshot; writeStoredClawdComposerSubmissionSnapshot(clawdSubmissionSnapshot); + const clawdAbortController = new AbortController(); + const clawdRequestRestoreSnapshot: PendingClawdRequestRestoreSnapshot = { + chatId: activeChatId, + userMessageId, + textContent, + tableFiles: tableFilesSnapshot, + attachments: attachmentsSnapshot, + skillTag: clawdSkillTagForRequest || null, + shouldRestoreSkillTag: hasPendingClawdSkillTagPrompt, + }; + canceledClawdMessageIdsRef.current.delete(userMessageId); + clawdAbortControllerRef.current = clawdAbortController; + pendingClawdRequestRestoreRef.current = clawdRequestRestoreSnapshot; setClawdProcessingHint(nextProcessingHint); setIsClawdSubmitting(true); setMessages((previousMessages) => @@ -10773,8 +10887,13 @@ export function CanvasChatPanel({ const response = await fetch("/api/canvas/clawd-chat", { method: "POST", body: formData, + signal: clawdAbortController.signal, }); const responseData = await response.json().catch(() => null); + if (response.status === 499 || responseData?.canceled === true) { + canceledClawdMessageIdsRef.current.add(userMessageId); + throw new DOMException("Claw request canceled", "AbortError"); + } if (!response.ok) { console.error("[CanvasChat] Claw API returned error:", { status: response.status, @@ -10824,6 +10943,17 @@ export function CanvasChatPanel({ void mutateClawdHistory(); hasHydratedHistoryRef.current = true; } catch (error) { + const wasCanceled = + canceledClawdMessageIdsRef.current.has(userMessageId) || + (error instanceof Error && error.name === "AbortError"); + if (wasCanceled) { + if (pendingClawdRequestRestoreRef.current === clawdRequestRestoreSnapshot) { + pendingClawdRequestRestoreRef.current = null; + restorePendingClawdRequestToComposer(clawdRequestRestoreSnapshot); + toast.message("已停止处理,可以重新编辑后再发送"); + } + return; + } console.error("[CanvasChat] Claw request failed:", error); pendingClawdSubmissionRef.current = null; if (recentClawdSubmissionRef.current === clawdSubmissionSnapshot) { @@ -10865,13 +10995,25 @@ export function CanvasChatPanel({ } } finally { pendingClawdSubmissionRef.current = null; + if (pendingClawdRequestRestoreRef.current === clawdRequestRestoreSnapshot) { + pendingClawdRequestRestoreRef.current = null; + } + if (clawdAbortControllerRef.current === clawdAbortController) { + clawdAbortControllerRef.current = null; + } + const wasCanceled = canceledClawdMessageIdsRef.current.delete(userMessageId); if (recentClawdSubmissionRef.current === clawdSubmissionSnapshot) { + if (wasCanceled) { + recentClawdSubmissionRef.current = null; + writeStoredClawdComposerSubmissionSnapshot(null); + } else { const refreshedSubmissionSnapshot = { ...clawdSubmissionSnapshot, expiresAt: Date.now() + CLAWD_SUBMITTED_COMPOSER_RECOVERY_TTL_MS, }; recentClawdSubmissionRef.current = refreshedSubmissionSnapshot; writeStoredClawdComposerSubmissionSnapshot(refreshedSubmissionSnapshot); + } } setIsClawdSubmitting(false); setClawdProcessingHint(null); @@ -11244,6 +11386,7 @@ export function CanvasChatPanel({ markSessionClawdSkillTagPromptApplied, updateChatSessions, buildHistoryMessagesUrl, + restorePendingClawdRequestToComposer, workflowContext, messages, ]); @@ -12092,6 +12235,7 @@ export function CanvasChatPanel({ isClawdMode && activeClawdSkillTag ? activeClawdSkillTag.placeholder?.trim() || "" : ""; + const isClawdStopAvailable = isClawdMode && isClawdSubmitting; const handleClawdPresetPlaceholderDoubleClick = useCallback( (event: ReactMouseEvent) => { if (isSubmitting || !isClawdMode || !clawdEditablePresetPlaceholder) return; @@ -13878,7 +14022,12 @@ export function CanvasChatPanel({ ) : null} {isClawdMode && isClawdSubmitting ? ( - + ) : null}
@@ -15756,7 +15905,9 @@ export function CanvasChatPanel({ isWorkspacePresentation ? "h-10 rounded-full px-4 transition-all duration-200 flex-shrink-0" : "h-8 w-8 rounded-full transition-all duration-200 flex-shrink-0", - isVideoToolbarDark + isClawdStopAvailable + ? "bg-rose-500 text-white shadow-sm hover:bg-rose-600 dark:bg-rose-500 dark:text-white dark:hover:bg-rose-400" + : isVideoToolbarDark ? canSend ? "border border-[#e7ff1a]/20 bg-[#e7ff1a] text-zinc-950 shadow-sm hover:bg-[#dff40f]" : "border border-white/10 bg-[#242529] text-zinc-500 hover:bg-[#2c2d33]" @@ -15768,15 +15919,28 @@ export function CanvasChatPanel({ ? "bg-[#eef0f3] text-[#20242a] shadow-sm ring-1 ring-inset ring-[#d5dae2] hover:bg-[#e4e7ec] dark:bg-white dark:text-zinc-950 dark:ring-white/15 dark:hover:bg-zinc-100" : "bg-[#f1f1f2] text-[#b6bac2] hover:bg-[#ececee] dark:bg-[#242529] dark:text-[#777d88] dark:hover:bg-[#2c2d33]" )} - onClick={() => void handleSend()} - disabled={isSubmitting || !canSend} + onClick={() => { + if (isClawdStopAvailable) { + handleCancelClawdSubmission(); + return; + } + void handleSend(); + }} + disabled={isClawdStopAvailable ? false : isSubmitting || !canSend} title={ - isWorkspacePresentation || isDetailGenerationMode + isClawdStopAvailable + ? "停止处理并重新编辑" + : isWorkspacePresentation || isDetailGenerationMode ? getToolbarItem("chatStartGeneration").label : getToolbarItem("chatSend").label } > - {isSubmitting ? ( + {isClawdStopAvailable ? ( + <> + + {isWorkspacePresentation ? 停止 : null} + + ) : isSubmitting ? ( <> {isWorkspacePresentation ? 生成中 : null} diff --git a/lib/openclaw-chat/cancel-registry.ts b/lib/openclaw-chat/cancel-registry.ts new file mode 100644 index 000000000..8896d37be --- /dev/null +++ b/lib/openclaw-chat/cancel-registry.ts @@ -0,0 +1,76 @@ +const CANCELED_REQUEST_TTL_MS = 10 * 60 * 1000; + +type ActiveClawdRequest = { + controller: AbortController; + expiresAt: number; +}; + +const activeRequests = new Map(); +const canceledRequests = new Map(); + +function cleanupExpiredClawdRequests(now = Date.now()) { + for (const [key, request] of activeRequests.entries()) { + if (request.expiresAt <= now) { + activeRequests.delete(key); + } + } + + for (const [key, expiresAt] of canceledRequests.entries()) { + if (expiresAt <= now) { + canceledRequests.delete(key); + } + } +} + +export function buildClawdCancelKey({ + userId, + chatId, + userMessageId, +}: { + userId: string; + chatId: string; + userMessageId: string; +}) { + return `${userId}:${chatId}:${userMessageId}`; +} + +export function registerActiveClawdRequest( + key: string, + controller: AbortController, + timeoutMs: number +) { + cleanupExpiredClawdRequests(); + activeRequests.set(key, { + controller, + expiresAt: Date.now() + Math.max(timeoutMs, CANCELED_REQUEST_TTL_MS), + }); +} + +export function unregisterActiveClawdRequest(key: string) { + activeRequests.delete(key); +} + +export function cancelClawdRequest(key: string) { + cleanupExpiredClawdRequests(); + canceledRequests.set(key, Date.now() + CANCELED_REQUEST_TTL_MS); + const activeRequest = activeRequests.get(key); + if (activeRequest && !activeRequest.controller.signal.aborted) { + activeRequest.controller.abort(); + } + return Boolean(activeRequest); +} + +export function isClawdRequestCanceled(key: string) { + cleanupExpiredClawdRequests(); + const expiresAt = canceledRequests.get(key); + if (!expiresAt) return false; + if (expiresAt <= Date.now()) { + canceledRequests.delete(key); + return false; + } + return true; +} + +export function clearClawdRequestCancellation(key: string) { + canceledRequests.delete(key); +} From accaaad8f1bbfa7ac0a765d46fe195aa1bd9a3c2 Mon Sep 17 00:00:00 2001 From: 134 Date: Wed, 8 Jul 2026 22:42:41 +0800 Subject: [PATCH 24/29] fix: avoid route refresh when switching claw history --- components/canvas/CanvasChatPanel.tsx | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index a20bc46e5..a95e017c3 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -4,7 +4,7 @@ import { useChat } from "@ai-sdk/react"; import { DefaultChatTransport } from "ai"; import { useEffect, useRef, useState, useCallback, useMemo, type ClipboardEvent as ReactClipboardEvent, type DragEvent as ReactDragEvent, type MouseEvent as ReactMouseEvent } from "react"; import { useSession } from "next-auth/react"; -import { usePathname, useRouter, useSearchParams } from "next/navigation"; +import { useSearchParams } from "next/navigation"; import { createPortal } from "react-dom"; import type { DetailUiProtocol } from "@/lib/detail-ui-protocol"; import type { DetailUiScreenReviewPatch } from "@/lib/detail-ui-protocol"; @@ -2148,8 +2148,6 @@ export function CanvasChatPanel({ ); const effectiveAgentEnabled = agentEnabled && !isVideoWorkspace; const { data: session } = useSession(); - const router = useRouter(); - const pathname = usePathname(); const searchParams = useSearchParams(); const requestedChatSessionId = useMemo( () => normalizeCanvasChatSessionId(searchParams.get(CANVAS_CHAT_QUERY_PARAM)), @@ -2296,15 +2294,11 @@ export function CanvasChatPanel({ const normalized = normalizeCanvasChatSessionId(sessionId); if (!normalized || typeof window === "undefined") return; - const params = new URLSearchParams(window.location.search); - params.set(CANVAS_CHAT_QUERY_PARAM, normalized); - const query = params.toString(); - const hash = window.location.hash || ""; - router.replace(`${pathname}${query ? `?${query}` : ""}${hash}`, { - scroll: false, - }); + const url = new URL(window.location.href); + url.searchParams.set(CANVAS_CHAT_QUERY_PARAM, normalized); + window.history.replaceState(window.history.state, "", url); }, - [pathname, router] + [] ); // 🆕 标签悬停预览状态 From c9ed6628097d51d0dfe9853754ce7dbc7deeb05d Mon Sep 17 00:00:00 2001 From: 134 Date: Thu, 9 Jul 2026 12:00:42 +0800 Subject: [PATCH 25/29] Fix canvas scale adjust local edit build --- app/api/canvas/local-edit/route.ts | 143 ++++++++++++++++++++++++++++- 1 file changed, 139 insertions(+), 4 deletions(-) diff --git a/app/api/canvas/local-edit/route.ts b/app/api/canvas/local-edit/route.ts index 28be69d65..24cc075ed 100644 --- a/app/api/canvas/local-edit/route.ts +++ b/app/api/canvas/local-edit/route.ts @@ -199,6 +199,32 @@ function inferClosestAspectRatio(width: number, height: number) { return closest; } +function inferScaleAdjustPatchAspectRatio(width: number, height: number) { + if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) { + return "1:1"; + } + const sourceRatio = width / height; + const providerSafeRatios = [ + "1:1", + "2:3", + "3:2", + "3:4", + "4:3", + "9:16", + "16:9", + ] as const; + let closest: (typeof providerSafeRatios)[number] = "1:1"; + let closestDiff = Number.POSITIVE_INFINITY; + for (const candidate of providerSafeRatios) { + const diff = Math.abs(parseAspectRatioValue(candidate) - sourceRatio); + if (diff < closestDiff) { + closest = candidate; + closestDiff = diff; + } + } + return closest; +} + function resolveLocalEditAspectRatio(input: unknown, sourceWidth: number, sourceHeight: number) { const requested = String(input || "").trim(); if ( @@ -339,7 +365,26 @@ function isScaleAdjustFalNanoBananaEditModel( const label = `${entry.model.displayName || ""} ${entry.model.modelId || ""}` .toLowerCase() .replace(/\s+/g, " "); - return label.includes("/edit") || /\bedit\b/.test(label); + const capabilities = + entry.model.capabilities && typeof entry.model.capabilities === "object" + ? (entry.model.capabilities as Record) + : {}; + const defaultParams = + entry.model.defaultParams && typeof entry.model.defaultParams === "object" + ? (entry.model.defaultParams as Record) + : {}; + const editEndpoint = + typeof capabilities.editEndpoint === "string" + ? capabilities.editEndpoint + : typeof defaultParams.editEndpoint === "string" + ? defaultParams.editEndpoint + : ""; + return ( + label.includes("/edit") || + /\bedit\b/.test(label) || + capabilities.autoRouteEditEndpoint === true || + editEndpoint.toLowerCase().includes("/edit") + ); } function isScaleAdjustHealthyModel( @@ -761,6 +806,51 @@ function expandRectWithMargins( }; } +function expandRectToProviderAspectLimit( + rect: NormalizedLocalEditRegion["rect"], + sourceWidth: number, + sourceHeight: number, + maxAspectRatio = 3 +) { + if ( + !Number.isFinite(sourceWidth) || + !Number.isFinite(sourceHeight) || + sourceWidth <= 0 || + sourceHeight <= 0 || + maxAspectRatio <= 1 + ) { + return rect; + } + + const pixelWidth = rect.width * sourceWidth; + const pixelHeight = rect.height * sourceHeight; + if (pixelWidth <= 0 || pixelHeight <= 0) return rect; + + const ratio = pixelWidth / pixelHeight; + let nextWidth = rect.width; + let nextHeight = rect.height; + + if (ratio > maxAspectRatio) { + nextHeight = Math.min(1, pixelWidth / maxAspectRatio / sourceHeight); + } else if (ratio < 1 / maxAspectRatio) { + nextWidth = Math.min(1, (pixelHeight / maxAspectRatio) / sourceWidth); + } else { + return rect; + } + + const centerX = rect.x + rect.width / 2; + const centerY = rect.y + rect.height / 2; + const x = clamp(centerX - nextWidth / 2, 0, Math.max(0, 1 - nextWidth)); + const y = clamp(centerY - nextHeight / 2, 0, Math.max(0, 1 - nextHeight)); + + return { + x, + y, + width: nextWidth, + height: nextHeight, + }; +} + function getRectUnion( leftRect: NormalizedLocalEditRegion["rect"], rightRect: NormalizedLocalEditRegion["rect"] @@ -938,6 +1028,40 @@ function getScaleAdjustPatchWorkspaceRect( return workspaceRects.reduce((combined, rect) => getRectUnion(combined, rect)); } +function shouldUseScaleAdjustEdgeLockedFullFrameReference(params: { + regions: NormalizedLocalEditRegion[]; + scalePercent?: ScaleAdjustPercent | null; + sourceHeight: number; + sourceWidth: number; +}) { + const { regions, scalePercent, sourceHeight, sourceWidth } = params; + if (!regions.length || !hasScaleAdjustShrinkTarget(regions, scalePercent)) { + return false; + } + if (!regions.some((region) => isScaleAdjustFurnitureProductLikePrompt(region.prompt))) { + return false; + } + + const workspaceRect = expandRectToProviderAspectLimit( + getScaleAdjustPatchWorkspaceRect(regions, scalePercent), + sourceWidth, + sourceHeight + ); + const pixelWidth = workspaceRect.width * sourceWidth; + const pixelHeight = workspaceRect.height * sourceHeight; + if (pixelWidth <= 0 || pixelHeight <= 0) return false; + + const ratio = pixelWidth / pixelHeight; + const touchesCanvasEdge = + workspaceRect.x <= 0.002 || + workspaceRect.y <= 0.002 || + workspaceRect.x + workspaceRect.width >= 0.998 || + workspaceRect.y + workspaceRect.height >= 0.998; + const nearProviderAspectLimit = ratio <= 0.42 || ratio >= 2.4; + + return touchesCanvasEdge && nearProviderAspectLimit; +} + function expandPixelRectForCrop(params: { height: number; pixelRect: NormalizedLocalEditRegion["pixelRect"]; @@ -1336,6 +1460,13 @@ function isScaleAdjustPersonLikePrompt(prompt: string) { ); } +function isScaleAdjustFurnitureProductLikePrompt(prompt: string) { + const text = normalizeScaleAdjustModelText(prompt); + return /furniture|product|commodity|goods|object|item|subject|sofa|couch|chair|table|desk|cabinet|shelf|bed|bench|lamp|basket|rack|stool|drawer|wardrobe|主物体|主体|物体|商品|产品|家具|沙发|椅|桌|柜|架|床|凳|灯|篮|抽屉|衣柜/.test( + text + ); +} + function hasScaleAdjustPersonPixelSignal(params: { box: { left: number; top: number; width: number; height: number }; raw: Buffer; @@ -2781,7 +2912,11 @@ async function createScaleAdjustPatchReference(params: { sourceWidth, userId, } = params; - const workspaceRect = getScaleAdjustPatchWorkspaceRect(regions, scalePercent); + const workspaceRect = expandRectToProviderAspectLimit( + getScaleAdjustPatchWorkspaceRect(regions, scalePercent), + sourceWidth, + sourceHeight + ); const workspacePixelRect = rectToPixels(workspaceRect, sourceWidth, sourceHeight); const shouldUseStructureLockedDraft = hasScaleAdjustStructureTarget( regions, @@ -3890,7 +4025,7 @@ export async function POST(request: NextRequest) { const useFalScaleAdjustCoordinatePrompt = useScaleAdjustCoordinatePrompt && resolvedScaleAdjustModelEntry?.provider?.type === "fal-image" && - !useScaleAdjustFullFrameFalEdit; + getScaleAdjustModelFamily(resolvedScaleAdjustModelEntry) === "nano-banana-2"; const useScaleAdjustVisualLayoutGuide = useScaleAdjustCoordinatePrompt && !useFalScaleAdjustCoordinatePrompt && @@ -4152,7 +4287,7 @@ export async function POST(request: NextRequest) { const imageRequest: CanvasGenerateImageRequest = { allowFailover: isScaleAdjustOperation ? false : undefined, aspectRatio: scaleAdjustPatchReference - ? inferClosestAspectRatio( + ? inferScaleAdjustPatchAspectRatio( scaleAdjustPatchReference.workspacePixelRect.width, scaleAdjustPatchReference.workspacePixelRect.height ) From 72b1f8f1cf075008e8086f140ae98fd05df94826 Mon Sep 17 00:00:00 2001 From: 134 Date: Thu, 9 Jul 2026 14:39:38 +0800 Subject: [PATCH 26/29] fix: keep image attachment add button visible --- components/canvas/CanvasChatPanel.tsx | 62 +++++++++++++++------------ 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/components/canvas/CanvasChatPanel.tsx b/components/canvas/CanvasChatPanel.tsx index a95e017c3..d9030fc5a 100644 --- a/components/canvas/CanvasChatPanel.tsx +++ b/components/canvas/CanvasChatPanel.tsx @@ -15265,33 +15265,41 @@ export function CanvasChatPanel({
) : null} {!isWorkspacePresentation && !isDetailGenerationMode && !isVideoWorkspace && activeComposerMode === "image" ? ( - +
+ {attachments.map((attachment, index) => ( +
+ {attachment.name { + if (event.currentTarget.src !== attachment.url) { + event.currentTarget.src = attachment.url; + } + }} + /> +
+ ))} + +
) : null} {isClawdMode && clawdTableFiles.length > 0 ? (
From 65f5a13f13c526c9dc69aa982faf40c363b8c8bc Mon Sep 17 00:00:00 2001 From: 134 Date: Thu, 9 Jul 2026 14:47:18 +0800 Subject: [PATCH 27/29] Rewrite canvas scale adjust local edit --- app/api/canvas/local-edit/route.ts | 3926 ++-------------------------- 1 file changed, 149 insertions(+), 3777 deletions(-) diff --git a/app/api/canvas/local-edit/route.ts b/app/api/canvas/local-edit/route.ts index 24cc075ed..ea8771892 100644 --- a/app/api/canvas/local-edit/route.ts +++ b/app/api/canvas/local-edit/route.ts @@ -2,10 +2,7 @@ import { NextRequest, NextResponse } from "next/server"; import sharp from "sharp"; import { auth } from "@/app/(auth)/auth"; -import { - executeRmbgJob, - fetchImageBufferFromUrl, -} from "@/lib/ai/rmbg/service"; +import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service"; import { createCanvasImageTask, enqueueCanvasImageTask, @@ -13,14 +10,9 @@ import { } from "@/lib/canvas/image-task-queue"; import type { CanvasGenerateImageRequest } from "@/lib/canvas/generate-image"; import { - getEnabledAiModelsWithProvider, getPointsSystemConfig, getSiteSettings, } from "@/lib/db/queries"; -import { - modelLacksReferenceImageInputSupport, -} from "@/lib/ai/reference-image-capability"; -import { isFalGptImage2EditModelId } from "@/lib/ai/providers/fal-image"; import { getImageToolCreditCost } from "@/lib/points/config"; import { prepareFeaturePointsCharge } from "@/lib/points/feature-charge"; import { uploadFile } from "@/lib/storage/service"; @@ -101,48 +93,12 @@ type NormalizedLocalEditRegion = { const MAX_LOCAL_EDIT_REGIONS = 8; const MAX_REFERENCE_IMAGES_PER_REGION = 3; -const MAX_SCALE_ADJUST_CROP_REFERENCES = 4; -const SCALE_ADJUST_CROP_PADDING_RATIO = 0.18; -const SCALE_ADJUST_CROP_MAX_EDGE = 1536; -const SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN = 0.045; -const SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN = 0.18; -const SCALE_ADJUST_LAYOUT_GUIDE_WASH_COLOR = "#f5f7fb"; -const SCALE_ADJUST_LAYOUT_GUIDE_WASH_OPACITY = 0.46; -const SCALE_ADJUST_STRUCTURE_LOCK_MIN_MASK_RATIO = 0.006; -const SCALE_ADJUST_STRUCTURE_LOCK_COMPONENT_MIN_RATIO = 0.00018; -const SCALE_ADJUST_RMBG_MIN_ALPHA_RATIO = 0.012; -const SCALE_ADJUST_RMBG_MAX_SOLID_ALPHA_RATIO = 0.92; -const SCALE_ADJUST_RMBG_ALPHA_CLEAN_THRESHOLD = 42; const MIN_REGION_EDGE_PX = 24; const SCALE_ADJUST_OPERATION = "scale-adjust"; type LocalEditOperation = "local-edit" | typeof SCALE_ADJUST_OPERATION; const MIN_SCALE_ADJUST_PERCENT = -80; const MAX_SCALE_ADJUST_PERCENT = 200; type ScaleAdjustPercent = number; -type ScaleAdjustCropReference = { - regionIndex: number; - url: string; -}; -type ScaleAdjustPatchReference = { - sourceCropUrl: string; - structureLockedDraft?: boolean; - targetDraftUrl: string; - workspaceRect: NormalizedLocalEditRegion["rect"]; - workspacePixelRect: { - left: number; - top: number; - width: number; - height: number; - }; -}; -type ScaleAdjustStructureLockedComposite = { - method?: "rmbg-cutout" | "pixel-mask"; - overlay: { input: Buffer; left: number; top: number }; - wash: { input: Buffer; left: number; top: number }; -}; -type AiModelWithProviderForSelection = Awaited< - ReturnType ->[number]; const DEFAULT_REGION_COLORS = [ "#ff3b30", "#1677ff", @@ -199,32 +155,6 @@ function inferClosestAspectRatio(width: number, height: number) { return closest; } -function inferScaleAdjustPatchAspectRatio(width: number, height: number) { - if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) { - return "1:1"; - } - const sourceRatio = width / height; - const providerSafeRatios = [ - "1:1", - "2:3", - "3:2", - "3:4", - "4:3", - "9:16", - "16:9", - ] as const; - let closest: (typeof providerSafeRatios)[number] = "1:1"; - let closestDiff = Number.POSITIVE_INFINITY; - for (const candidate of providerSafeRatios) { - const diff = Math.abs(parseAspectRatioValue(candidate) - sourceRatio); - if (diff < closestDiff) { - closest = candidate; - closestDiff = diff; - } - } - return closest; -} - function resolveLocalEditAspectRatio(input: unknown, sourceWidth: number, sourceHeight: number) { const requested = String(input || "").trim(); if ( @@ -259,336 +189,6 @@ function normalizeHexColor(input: unknown, fallback: string) { return /^#[0-9a-f]{6}$/i.test(expanded) ? expanded.toLowerCase() : fallback; } -function findModelSelectionEntry( - models: AiModelWithProviderForSelection[], - modelRef: string -) { - const normalizedRef = String(modelRef || "").trim(); - if (!normalizedRef) return null; - return ( - models.find( - (entry) => - entry.model.id === normalizedRef || entry.model.modelId === normalizedRef - ) || null - ); -} - -function isScaleAdjustDedicatedDetailModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - if ( - !entry?.model?.supportsImageGen || - modelLacksReferenceImageInputSupport(entry.model, entry.provider) - ) { - return false; - } - const label = `${entry.model.displayName || ""} ${entry.model.modelId || ""}` - .toLowerCase() - .replace(/\s+/g, ""); - return label.includes("详情专线"); -} - -function normalizeScaleAdjustModelText(input: unknown) { - return String(input || "") - .trim() - .toLowerCase() - .normalize("NFKC") - .replace(/[「」『』【】[\]()(){}]/g, " ") - .replace(/[_/|::,,.。+]+/g, "-") - .replace(/\s+/g, " "); -} - -function resolveScaleAdjustModelFamilyFromText(input: unknown) { - const normalized = normalizeScaleAdjustModelText(input); - const compact = normalized.replace(/[^a-z0-9]+/g, ""); - if (!normalized && !compact) return ""; - if ( - normalized.includes("gemini-3.1-flash-image-preview") || - normalized.includes("nano-banana-2") || - compact.includes("nanobanana2") - ) { - return "nano-banana-2"; - } - if ( - normalized.includes("gemini-3-pro-image-preview") || - normalized.includes("nano-banana-pro") || - compact.includes("nanobananapro") - ) { - return "nano-banana-pro"; - } - if (normalized.includes("gpt-image-2") || compact.includes("gptimage2")) { - return "gpt-image-2"; - } - return ""; -} - -function getScaleAdjustModelFamily( - entry: AiModelWithProviderForSelection | null | undefined -) { - if (!entry) return ""; - return ( - resolveScaleAdjustModelFamilyFromText(entry.model.modelId) || - resolveScaleAdjustModelFamilyFromText(entry.model.displayName) || - resolveScaleAdjustModelFamilyFromText(entry.model.id) - ); -} - -function isScaleAdjustMaskCapableModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - if (!entry || getScaleAdjustModelFamily(entry) !== "gpt-image-2") { - return false; - } - if (entry.provider.type === "openai-image") return true; - if (entry.provider.type === "fal-image") { - return isFalGptImage2EditModelId(entry.model.modelId || ""); - } - return false; -} - -function isScaleAdjustCoordinateGuideModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - return getScaleAdjustModelFamily(entry) === "nano-banana-2"; -} - -function isScaleAdjustFalNanoBananaEditModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - if ( - !entry || - entry.provider.type !== "fal-image" || - getScaleAdjustModelFamily(entry) !== "nano-banana-2" - ) { - return false; - } - const label = `${entry.model.displayName || ""} ${entry.model.modelId || ""}` - .toLowerCase() - .replace(/\s+/g, " "); - const capabilities = - entry.model.capabilities && typeof entry.model.capabilities === "object" - ? (entry.model.capabilities as Record) - : {}; - const defaultParams = - entry.model.defaultParams && typeof entry.model.defaultParams === "object" - ? (entry.model.defaultParams as Record) - : {}; - const editEndpoint = - typeof capabilities.editEndpoint === "string" - ? capabilities.editEndpoint - : typeof defaultParams.editEndpoint === "string" - ? defaultParams.editEndpoint - : ""; - return ( - label.includes("/edit") || - /\bedit\b/.test(label) || - capabilities.autoRouteEditEndpoint === true || - editEndpoint.toLowerCase().includes("/edit") - ); -} - -function isScaleAdjustHealthyModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - return !entry?.model?.healthStatus || entry.model.healthStatus === "healthy"; -} - -function getScaleAdjustProviderPriority(providerType: string) { - switch (providerType) { - case "ruxa-image": - return 10; - case "snapgen-image": - return 20; - case "krea": - return 30; - case "gemini": - case "grsai-gpt-image": - return 40; - case "alibaba-image": - case "bfl-image": - case "openai-image": - case "stepfun-image": - case "volcano-vision": - return 60; - case "fal-image": - return 1000; - default: - return 80; - } -} - -function getScaleAdjustModelHealthPenalty( - healthStatus: string | null | undefined -) { - if (healthStatus === "degraded") return 25; - if (healthStatus === "auto_disabled") return 200; - return 0; -} - -function getScaleAdjustCandidatePriority(entry: AiModelWithProviderForSelection) { - return ( - getScaleAdjustProviderPriority(entry.provider.type) + - getScaleAdjustModelHealthPenalty(entry.model.healthStatus) - ); -} - -function isScaleAdjustUsableImageEditModel( - entry: AiModelWithProviderForSelection | null | undefined -) { - return Boolean( - entry?.model?.supportsImageGen && - !modelLacksReferenceImageInputSupport(entry.model, entry.provider) - ); -} - -function compareScaleAdjustProviderCandidates( - left: AiModelWithProviderForSelection, - right: AiModelWithProviderForSelection, - preferredModelRef: string -) { - const leftPriority = getScaleAdjustCandidatePriority(left); - const rightPriority = getScaleAdjustCandidatePriority(right); - if (leftPriority !== rightPriority) return leftPriority - rightPriority; - - const leftDedicated = isScaleAdjustDedicatedDetailModel(left); - const rightDedicated = isScaleAdjustDedicatedDetailModel(right); - if (leftDedicated !== rightDedicated) return leftDedicated ? -1 : 1; - - const leftExact = - left.model.id === preferredModelRef || left.model.modelId === preferredModelRef; - const rightExact = - right.model.id === preferredModelRef || right.model.modelId === preferredModelRef; - if (leftExact !== rightExact) return leftExact ? -1 : 1; - - return 0; -} - -function resolveScaleAdjustPreferredModelId(params: { - configuredModelId: string; - honorRequestedModelBeforeGpt?: boolean; - preferFalNanoBananaEdit?: boolean; - preferMaskCapableGpt?: boolean; - preferProviderTypes?: string[]; - requestedModelId: string; - models: AiModelWithProviderForSelection[]; -}) { - const requestedModel = findModelSelectionEntry( - params.models, - params.requestedModelId - ); - const configuredModel = findModelSelectionEntry( - params.models, - params.configuredModelId - ); - if ( - params.honorRequestedModelBeforeGpt && - requestedModel && - isScaleAdjustUsableImageEditModel(requestedModel) - ) { - return requestedModel.model.id || params.requestedModelId; - } - - const gptImage2Candidates = params.models - .filter((entry) => isScaleAdjustUsableImageEditModel(entry)) - .filter((entry) => getScaleAdjustModelFamily(entry) === "gpt-image-2") - .sort((left, right) => - compareScaleAdjustProviderCandidates( - left, - right, - params.requestedModelId || params.configuredModelId - ) - ); - if (params.preferMaskCapableGpt) { - const maskCapableGptImage2 = gptImage2Candidates - .filter(isScaleAdjustMaskCapableModel) - .filter(isScaleAdjustHealthyModel); - if (maskCapableGptImage2[0]) { - return maskCapableGptImage2[0].model.id; - } - } - for (const providerType of params.preferProviderTypes || []) { - const providerCandidate = gptImage2Candidates.find( - (entry) => - entry.provider.type === providerType && isScaleAdjustHealthyModel(entry) - ); - if (providerCandidate) { - return providerCandidate.model.id; - } - } - if (params.preferFalNanoBananaEdit) { - const falEditCandidate = params.models - .filter((entry) => isScaleAdjustUsableImageEditModel(entry)) - .filter(isScaleAdjustFalNanoBananaEditModel) - .filter(isScaleAdjustHealthyModel) - .sort((left, right) => - compareScaleAdjustProviderCandidates( - left, - right, - params.requestedModelId || params.configuredModelId - ) - )[0]; - if (falEditCandidate) { - return falEditCandidate.model.id; - } - } - if (gptImage2Candidates[0]) { - return gptImage2Candidates[0].model.id; - } - - if ( - isScaleAdjustUsableImageEditModel(requestedModel) && - requestedModel && - getScaleAdjustModelFamily(requestedModel) !== "nano-banana-2" && - requestedModel.provider.type !== "alibaba-image" - ) { - return requestedModel.model.id || params.requestedModelId; - } - - const autoDetailModel = params.models.find(isScaleAdjustDedicatedDetailModel); - const preferredModel = - (isScaleAdjustDedicatedDetailModel(requestedModel) ? requestedModel : null) || - (isScaleAdjustDedicatedDetailModel(configuredModel) ? configuredModel : null) || - autoDetailModel || - configuredModel || - requestedModel || - null; - const preferredModelRef = - preferredModel?.model.id || - preferredModel?.model.modelId || - params.configuredModelId || - params.requestedModelId; - const preferredFamily = - getScaleAdjustModelFamily(preferredModel) || - resolveScaleAdjustModelFamilyFromText(params.configuredModelId) || - resolveScaleAdjustModelFamilyFromText(params.requestedModelId); - - if (preferredFamily) { - const sameFamilyCandidates = params.models - .filter((entry) => isScaleAdjustUsableImageEditModel(entry)) - .filter((entry) => getScaleAdjustModelFamily(entry) === preferredFamily) - .sort((left, right) => - compareScaleAdjustProviderCandidates(left, right, preferredModelRef) - ); - if (sameFamilyCandidates[0]) { - return sameFamilyCandidates[0].model.id; - } - } - - if (isScaleAdjustDedicatedDetailModel(requestedModel)) { - return requestedModel?.model.id || params.requestedModelId; - } - - if (isScaleAdjustDedicatedDetailModel(configuredModel)) { - return configuredModel?.model.id || params.configuredModelId; - } - - if (autoDetailModel) { - return autoDetailModel.model.id; - } - - return params.configuredModelId || params.requestedModelId; -} - function normalizeHttpImageUrl(input: unknown) { const raw = String(input || "").trim(); if (!/^https?:\/\//i.test(raw)) return ""; @@ -741,2230 +341,6 @@ function getScaleAdjustTargetRect( return region.rect; } -function hasScaleAdjustEnlargeTarget( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.some((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; - return widthFactor > 1.08 || heightFactor > 1.08; - }); -} - -function hasScaleAdjustShrinkTarget( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.some((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; - return widthFactor < 0.92 || heightFactor < 0.92; - }); -} - -function hasScaleAdjustStructureTarget( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.some((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; - return ( - widthFactor > 1.08 || - heightFactor > 1.08 || - widthFactor < 0.92 || - heightFactor < 0.92 - ); - }); -} - -function expandRectWithMargins( - rect: NormalizedLocalEditRegion["rect"], - marginX: number, - marginY: number -) { - const left = clamp(rect.x - marginX, 0, 1); - const top = clamp(rect.y - marginY, 0, 1); - const right = clamp(rect.x + rect.width + marginX, left + 0.001, 1); - const bottom = clamp(rect.y + rect.height + marginY, top + 0.001, 1); - - return { - x: left, - y: top, - width: Math.max(0.001, right - left), - height: Math.max(0.001, bottom - top), - }; -} - -function expandRectToProviderAspectLimit( - rect: NormalizedLocalEditRegion["rect"], - sourceWidth: number, - sourceHeight: number, - maxAspectRatio = 3 -) { - if ( - !Number.isFinite(sourceWidth) || - !Number.isFinite(sourceHeight) || - sourceWidth <= 0 || - sourceHeight <= 0 || - maxAspectRatio <= 1 - ) { - return rect; - } - - const pixelWidth = rect.width * sourceWidth; - const pixelHeight = rect.height * sourceHeight; - if (pixelWidth <= 0 || pixelHeight <= 0) return rect; - - const ratio = pixelWidth / pixelHeight; - let nextWidth = rect.width; - let nextHeight = rect.height; - - if (ratio > maxAspectRatio) { - nextHeight = Math.min(1, pixelWidth / maxAspectRatio / sourceHeight); - } else if (ratio < 1 / maxAspectRatio) { - nextWidth = Math.min(1, (pixelHeight / maxAspectRatio) / sourceWidth); - } else { - return rect; - } - - const centerX = rect.x + rect.width / 2; - const centerY = rect.y + rect.height / 2; - const x = clamp(centerX - nextWidth / 2, 0, Math.max(0, 1 - nextWidth)); - const y = clamp(centerY - nextHeight / 2, 0, Math.max(0, 1 - nextHeight)); - - return { - x, - y, - width: nextWidth, - height: nextHeight, - }; -} - -function getRectUnion( - leftRect: NormalizedLocalEditRegion["rect"], - rightRect: NormalizedLocalEditRegion["rect"] -) { - const left = Math.min(leftRect.x, rightRect.x); - const top = Math.min(leftRect.y, rightRect.y); - const right = Math.max( - leftRect.x + leftRect.width, - rightRect.x + rightRect.width - ); - const bottom = Math.max( - leftRect.y + leftRect.height, - rightRect.y + rightRect.height - ); - return { - x: clamp(left, 0, 1), - y: clamp(top, 0, 1), - width: Math.max(0.001, clamp(right, 0, 1) - clamp(left, 0, 1)), - height: Math.max(0.001, clamp(bottom, 0, 1) - clamp(top, 0, 1)), - }; -} - -function rectsDifferMeaningfully( - leftRect: NormalizedLocalEditRegion["rect"], - rightRect: NormalizedLocalEditRegion["rect"], - epsilon = 0.0005 -) { - return ( - Math.abs(leftRect.x - rightRect.x) > epsilon || - Math.abs(leftRect.y - rightRect.y) > epsilon || - Math.abs(leftRect.width - rightRect.width) > epsilon || - Math.abs(leftRect.height - rightRect.height) > epsilon - ); -} - -function getScaleAdjustWorkspaceRect( - sourceRect: NormalizedLocalEditRegion["rect"], - targetRect: NormalizedLocalEditRegion["rect"], - scalePercent?: ScaleAdjustPercent | null -) { - const sourceWidth = Math.max(0.0001, sourceRect.width); - const sourceHeight = Math.max(0.0001, sourceRect.height); - const widthDeltaRatio = Math.abs(targetRect.width / sourceWidth - 1); - const heightDeltaRatio = Math.abs(targetRect.height / sourceHeight - 1); - const areaDeltaRatio = Math.abs( - Math.sqrt( - Math.max(0.0001, targetRect.width * targetRect.height) / - Math.max(0.0001, sourceWidth * sourceHeight) - ) - 1 - ); - const sourceCenterX = sourceRect.x + sourceRect.width / 2; - const sourceCenterY = sourceRect.y + sourceRect.height / 2; - const targetCenterX = targetRect.x + targetRect.width / 2; - const targetCenterY = targetRect.y + targetRect.height / 2; - const movementRatioX = Math.abs(targetCenterX - sourceCenterX) / sourceWidth; - const movementRatioY = Math.abs(targetCenterY - sourceCenterY) / sourceHeight; - const explicitChangeRatio = Math.max( - widthDeltaRatio, - heightDeltaRatio, - areaDeltaRatio, - movementRatioX, - movementRatioY - ); - const fallbackScaleRatio = - typeof scalePercent === "number" && Number.isFinite(scalePercent) - ? Math.min(1, Math.abs(scalePercent) / 100) - : 0; - const changeRatio = Math.max(explicitChangeRatio, fallbackScaleRatio); - const unionRect = getRectUnion(sourceRect, targetRect); - if (changeRatio <= 0 && !rectsDifferMeaningfully(unionRect, targetRect)) { - return targetRect; - } - - const marginX = Math.min( - 0.16, - Math.max( - 0.018, - unionRect.width * 0.04, - sourceRect.width * changeRatio * 0.24 - ) - ); - const marginY = Math.min( - 0.16, - Math.max( - 0.018, - unionRect.height * 0.04, - sourceRect.height * changeRatio * 0.24 - ) - ); - - return expandRectWithMargins(unionRect, marginX, marginY); -} - -function buildScaleAdjustCompositeRegions( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.flatMap((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const workspaceRect = getScaleAdjustWorkspaceRect( - region.rect, - targetRect, - scalePercent - ); - return rectsDifferMeaningfully(workspaceRect, targetRect) && - rectsDifferMeaningfully(workspaceRect, region.rect) - ? [region.rect, targetRect, workspaceRect] - : [region.rect, targetRect]; - }); -} - -function buildScaleAdjustPatchCompositeRegions( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.flatMap((region) => [ - region.rect, - getScaleAdjustTargetRect(region, scalePercent), - ]); -} - -function buildScaleAdjustProtectedChangeRegions( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - return regions.flatMap((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const unionRect = getRectUnion(region.rect, targetRect); - const marginX = Math.min( - 0.045, - Math.max(0.012, unionRect.width * 0.08) - ); - const marginY = Math.min( - 0.045, - Math.max(0.012, unionRect.height * 0.08) - ); - - return [ - expandRectWithMargins(region.rect, marginX, marginY), - expandRectWithMargins(targetRect, marginX, marginY), - ]; - }); -} - -function getScaleAdjustPatchWorkspaceRect( - regions: NormalizedLocalEditRegion[], - scalePercent?: ScaleAdjustPercent | null -) { - const workspaceRects = regions.map((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const baseWorkspace = getScaleAdjustWorkspaceRect( - region.rect, - targetRect, - scalePercent - ); - const marginX = Math.min( - SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN, - Math.max( - SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN, - baseWorkspace.width * 0.22, - region.rect.width * 0.18 - ) - ); - const marginY = Math.min( - SCALE_ADJUST_PATCH_WORKSPACE_MAX_MARGIN, - Math.max( - SCALE_ADJUST_PATCH_WORKSPACE_MIN_MARGIN, - baseWorkspace.height * 0.22, - region.rect.height * 0.18 - ) - ); - return expandRectWithMargins(baseWorkspace, marginX, marginY); - }); - - return workspaceRects.reduce((combined, rect) => getRectUnion(combined, rect)); -} - -function shouldUseScaleAdjustEdgeLockedFullFrameReference(params: { - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; - sourceHeight: number; - sourceWidth: number; -}) { - const { regions, scalePercent, sourceHeight, sourceWidth } = params; - if (!regions.length || !hasScaleAdjustShrinkTarget(regions, scalePercent)) { - return false; - } - if (!regions.some((region) => isScaleAdjustFurnitureProductLikePrompt(region.prompt))) { - return false; - } - - const workspaceRect = expandRectToProviderAspectLimit( - getScaleAdjustPatchWorkspaceRect(regions, scalePercent), - sourceWidth, - sourceHeight - ); - const pixelWidth = workspaceRect.width * sourceWidth; - const pixelHeight = workspaceRect.height * sourceHeight; - if (pixelWidth <= 0 || pixelHeight <= 0) return false; - - const ratio = pixelWidth / pixelHeight; - const touchesCanvasEdge = - workspaceRect.x <= 0.002 || - workspaceRect.y <= 0.002 || - workspaceRect.x + workspaceRect.width >= 0.998 || - workspaceRect.y + workspaceRect.height >= 0.998; - const nearProviderAspectLimit = ratio <= 0.42 || ratio >= 2.4; - - return touchesCanvasEdge && nearProviderAspectLimit; -} - -function expandPixelRectForCrop(params: { - height: number; - pixelRect: NormalizedLocalEditRegion["pixelRect"]; - width: number; -}) { - const { height, pixelRect, width } = params; - const padX = Math.round(pixelRect.width * SCALE_ADJUST_CROP_PADDING_RATIO); - const padY = Math.round(pixelRect.height * SCALE_ADJUST_CROP_PADDING_RATIO); - const left = clamp(pixelRect.left - padX, 0, Math.max(0, width - 1)); - const top = clamp(pixelRect.top - padY, 0, Math.max(0, height - 1)); - const right = clamp( - pixelRect.left + pixelRect.width + padX, - left + 1, - width - ); - const bottom = clamp( - pixelRect.top + pixelRect.height + padY, - top + 1, - height - ); - - return { - left, - top, - width: Math.max(1, right - left), - height: Math.max(1, bottom - top), - }; -} - -async function createScaleAdjustCropReferences(params: { - regions: NormalizedLocalEditRegion[]; - sourceBuffer: Buffer; - sourceHeight: number; - sourceWidth: number; -}): Promise { - const references: ScaleAdjustCropReference[] = []; - const regionsForCrop = params.regions.slice(0, MAX_SCALE_ADJUST_CROP_REFERENCES); - - for (const region of regionsForCrop) { - const focusBox = getScaleAdjustFocusedSourceBox({ - region, - sourceBox: region.pixelRect, - }); - const cropBox = getScaleAdjustFocusDirection(region) - ? focusBox - : expandPixelRectForCrop({ - height: params.sourceHeight, - pixelRect: region.pixelRect, - width: params.sourceWidth, - }); - const cropBuffer = await sharp(params.sourceBuffer, { failOn: "none" }) - .extract(cropBox) - .resize({ - fit: "inside", - height: SCALE_ADJUST_CROP_MAX_EDGE, - withoutEnlargement: true, - width: SCALE_ADJUST_CROP_MAX_EDGE, - }) - .png({ compressionLevel: 6 }) - .toBuffer(); - const upload = await uploadFile( - `canvas-scale-adjust-crop-r${region.index}-${Date.now()}-${Math.random() - .toString(36) - .slice(2, 8)}.png`, - toArrayBuffer(cropBuffer) - ); - references.push({ - regionIndex: region.index, - url: upload.url, - }); - } - - return references; -} - -function getScaleAdjustVisualGuidePlacement(params: { - height: number; - region: NormalizedLocalEditRegion; - scalePercent?: ScaleAdjustPercent | null; - width: number; -}) { - const { height, region, scalePercent, width } = params; - const source = region.pixelRect; - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const target = region.targetPixelRect || rectToPixels(targetRect, width, height); - const sourceLeft = clamp(source.left, 0, Math.max(0, width - 1)); - const sourceTop = clamp(source.top, 0, Math.max(0, height - 1)); - const sourceRight = clamp( - source.left + source.width, - sourceLeft + 1, - width - ); - const sourceBottom = clamp( - source.top + source.height, - sourceTop + 1, - height - ); - const sourceFootprintBox = { - left: Math.round(sourceLeft), - top: Math.round(sourceTop), - width: Math.max(1, Math.round(sourceRight - sourceLeft)), - height: Math.max(1, Math.round(sourceBottom - sourceTop)), - }; - const sourceBox = getScaleAdjustFocusedSourceBox({ - region, - sourceBox: sourceFootprintBox, - }); - const sourceWidth = sourceBox.width; - const sourceHeight = sourceBox.height; - const widthScale = target.width / Math.max(1, sourceWidth); - const heightScale = target.height / Math.max(1, sourceHeight); - const uniformScale = Math.max( - 0.05, - Math.min( - Number.isFinite(widthScale) && widthScale > 0 ? widthScale : 1, - Number.isFinite(heightScale) && heightScale > 0 ? heightScale : 1 - ) - ); - const placedWidth = clamp( - Math.round(sourceWidth * uniformScale), - 1, - Math.max(1, width) - ); - const placedHeight = clamp( - Math.round(sourceHeight * uniformScale), - 1, - Math.max(1, height) - ); - const targetCenterX = target.left + target.width / 2; - const targetCenterY = target.top + target.height / 2; - const placedLeft = clamp( - Math.round(targetCenterX - placedWidth / 2), - 0, - Math.max(0, width - placedWidth) - ); - const placedTop = clamp( - Math.round(targetCenterY - placedHeight / 2), - 0, - Math.max(0, height - placedHeight) - ); - - return { - placedHeight: Math.max(1, Math.round(placedHeight)), - placedLeft: Math.max(0, Math.round(placedLeft)), - placedTop: Math.max(0, Math.round(placedTop)), - placedWidth: Math.max(1, Math.round(placedWidth)), - sourceBox: { - left: sourceBox.left, - top: sourceBox.top, - width: sourceWidth, - height: sourceHeight, - }, - sourceFootprintBox, - targetBox: target, - uniformScale, - }; -} - -function getScaleAdjustFocusDirection(region: NormalizedLocalEditRegion) { - const text = normalizeScaleAdjustModelText(region.prompt); - const compact = text.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, ""); - if (text.includes("left") || compact.includes("左")) return "left"; - if (text.includes("right") || compact.includes("右")) return "right"; - if (text.includes("top") || compact.includes("上")) return "top"; - if (text.includes("bottom") || compact.includes("下")) return "bottom"; - return ""; -} - -function getScaleAdjustFocusedSourceBox(params: { - region: NormalizedLocalEditRegion; - sourceBox: { left: number; top: number; width: number; height: number }; -}) { - const { region, sourceBox } = params; - const direction = getScaleAdjustFocusDirection(region); - if (!direction) return sourceBox; - - const minWidth = Math.max(1, Math.round(sourceBox.width * 0.42)); - const minHeight = Math.max(1, Math.round(sourceBox.height * 0.42)); - let left = sourceBox.left; - let top = sourceBox.top; - let width = sourceBox.width; - let height = sourceBox.height; - - if (direction === "left") { - width = Math.max(minWidth, Math.round(sourceBox.width * 0.68)); - } else if (direction === "right") { - const nextWidth = Math.max(minWidth, Math.round(sourceBox.width * 0.68)); - left = sourceBox.left + sourceBox.width - nextWidth; - width = nextWidth; - } else if (direction === "top") { - height = Math.max(minHeight, Math.round(sourceBox.height * 0.72)); - } else if (direction === "bottom") { - const nextHeight = Math.max(minHeight, Math.round(sourceBox.height * 0.72)); - top = sourceBox.top + sourceBox.height - nextHeight; - height = nextHeight; - } - - return { - left, - top, - width, - height, - }; -} - -function buildScaleAdjustPatchMaskSvg(params: { height: number; width: number }) { - const { height, width } = params; - const blur = Math.max(2, Math.min(14, Math.round(Math.min(width, height) * 0.035))); - const inset = Math.min( - Math.floor(Math.min(width, height) / 8), - Math.max(1, Math.round(blur * 0.7)) - ); - const rectWidth = Math.max(1, width - inset * 2); - const rectHeight = Math.max(1, height - inset * 2); - - return Buffer.from( - ` - - - - - - - ` - ); -} - -function formatScaleAdjustWashColor( - background?: { b: number; g: number; r: number } | null -) { - if (!background) return SCALE_ADJUST_LAYOUT_GUIDE_WASH_COLOR; - const r = clamp(Math.round(background.r), 24, 242); - const g = clamp(Math.round(background.g), 24, 242); - const b = clamp(Math.round(background.b), 24, 242); - return `rgb(${r}, ${g}, ${b})`; -} - -function buildScaleAdjustSourceFootprintWashSvg(params: { - boxes: Array<{ - background?: { b: number; g: number; r: number } | null; - left: number; - top: number; - width: number; - height: number; - }>; - height: number; - width: number; -}) { - const { boxes, height, width } = params; - const defs = boxes - .map((box, index) => { - const blur = Math.max( - 14, - Math.min(72, Math.round(Math.min(box.width, box.height) * 0.14)) - ); - return ` - - `; - }) - .join(""); - const rects = boxes - .map((box, index) => { - const blur = Math.max( - 14, - Math.min(72, Math.round(Math.min(box.width, box.height) * 0.14)) - ); - const pad = Math.max(blur, Math.round(Math.min(box.width, box.height) * 0.055)); - const left = Math.max(0, box.left - blur); - const top = Math.max(0, box.top - blur); - const right = Math.min(width, box.left + box.width + blur); - const bottom = Math.min(height, box.top + box.height + blur); - const rectWidth = Math.max(1, right - left); - const rectHeight = Math.max(1, bottom - top); - const radius = Math.max( - 8, - Math.min(Math.round(blur * 1.8), Math.round(rectWidth / 3), Math.round(rectHeight / 3)) - ); - const innerLeft = Math.max(0, box.left + pad); - const innerTop = Math.max(0, box.top + pad); - const innerRight = Math.min(width, box.left + box.width - pad); - const innerBottom = Math.min(height, box.top + box.height - pad); - const fill = formatScaleAdjustWashColor(box.background); - const inner = - innerRight > innerLeft + 4 && innerBottom > innerTop + 4 - ? `` - : ""; - return `${inner}`; - }) - .join(""); - - return Buffer.from( - ` - - ${defs} - - ${rects} - ` - ); -} - -function buildScaleAdjustTargetFootprintShadowSvg(params: { - height: number; - placements: Array>; - width: number; -}) { - const { height, placements, width } = params; - const minSide = Math.max(1, Math.min(width, height)); - const blur = Math.max(4, Math.min(18, Math.round(minSide * 0.014))); - const rects = placements - .map((placement) => { - const pad = Math.max(2, Math.round(blur * 0.45)); - const left = clamp( - placement.placedLeft - pad, - 0, - Math.max(0, width - 1) - ); - const top = clamp( - placement.placedTop - pad, - 0, - Math.max(0, height - 1) - ); - const right = clamp( - placement.placedLeft + placement.placedWidth + pad, - left + 1, - width - ); - const bottom = clamp( - placement.placedTop + placement.placedHeight + pad, - top + 1, - height - ); - const radius = Math.max(4, Math.round(blur * 1.2)); - return ``; - }) - .join(""); - - return Buffer.from( - ` - - - - - - ${rects} - ` - ); -} - -function getScaleAdjustRawPixelIndex(width: number, x: number, y: number) { - return (y * width + x) * 3; -} - -function getScaleAdjustPixelLuma(r: number, g: number, b: number) { - return r * 0.299 + g * 0.587 + b * 0.114; -} - -function getScaleAdjustPixelStats(r: number, g: number, b: number) { - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - return { - luma: getScaleAdjustPixelLuma(r, g, b), - saturation: max > 0 ? (max - min) / max : 0, - }; -} - -function isScaleAdjustLikelySkinPixel(r: number, g: number, b: number) { - return ( - r > 132 && - g > 82 && - b > 58 && - r > g * 1.06 && - g > b * 1.03 && - r - b < 135 - ); -} - -function isScaleAdjustLikelyWhiteFabricPixel( - r: number, - g: number, - b: number, - luma: number, - saturation: number -) { - return ( - luma > 158 && - saturation < 0.3 && - Math.abs(r - g) < 34 && - Math.abs(g - b) < 44 - ); -} - -function isScaleAdjustPersonLikePrompt(prompt: string) { - const text = normalizeScaleAdjustModelText(prompt); - return /person|people|human|woman|man|girl|boy|model|face|body|hand|arm|leg|clothing|人物|人像|真人|模特|女人|男人|女孩|男孩|小孩|脸|身体|手|胳膊|腿|衣服/.test( - text - ); -} - -function isScaleAdjustFurnitureProductLikePrompt(prompt: string) { - const text = normalizeScaleAdjustModelText(prompt); - return /furniture|product|commodity|goods|object|item|subject|sofa|couch|chair|table|desk|cabinet|shelf|bed|bench|lamp|basket|rack|stool|drawer|wardrobe|主物体|主体|物体|商品|产品|家具|沙发|椅|桌|柜|架|床|凳|灯|篮|抽屉|衣柜/.test( - text - ); -} - -function hasScaleAdjustPersonPixelSignal(params: { - box: { left: number; top: number; width: number; height: number }; - raw: Buffer; - width: number; -}) { - const { box, raw, width } = params; - let sampled = 0; - let skin = 0; - let whiteFabric = 0; - const step = Math.max(1, Math.floor(Math.min(box.width, box.height) / 260)); - - for (let localY = 0; localY < box.height; localY += step) { - const y = box.top + localY; - for (let localX = 0; localX < box.width; localX += step) { - const x = box.left + localX; - const rawIndex = getScaleAdjustRawPixelIndex(width, x, y); - const r = raw[rawIndex] || 0; - const g = raw[rawIndex + 1] || 0; - const b = raw[rawIndex + 2] || 0; - const { luma, saturation } = getScaleAdjustPixelStats(r, g, b); - sampled += 1; - if (isScaleAdjustLikelySkinPixel(r, g, b)) { - skin += 1; - } else if ( - isScaleAdjustLikelyWhiteFabricPixel(r, g, b, luma, saturation) && - luma < 242 - ) { - whiteFabric += 1; - } - } - } - - if (sampled <= 0) return false; - const skinRatio = skin / sampled; - const fabricRatio = whiteFabric / sampled; - return skin >= 18 && skinRatio >= 0.0025 && fabricRatio >= 0.035; -} - -function estimateScaleAdjustBoxBackground(params: { - box: { left: number; top: number; width: number; height: number }; - raw: Buffer; - width: number; -}) { - const { box, raw, width } = params; - const samples: Array<{ b: number; g: number; luma: number; r: number }> = []; - const borderX = Math.max(2, Math.round(box.width * 0.08)); - const borderY = Math.max(2, Math.round(box.height * 0.08)); - - for (let localY = 0; localY < box.height; localY += 1) { - const y = box.top + localY; - const isBorderY = localY < borderY || localY >= box.height - borderY; - for (let localX = 0; localX < box.width; localX += 1) { - const isBorderX = localX < borderX || localX >= box.width - borderX; - if (!isBorderX && !isBorderY) continue; - const x = box.left + localX; - const rawIndex = getScaleAdjustRawPixelIndex(width, x, y); - const r = raw[rawIndex] || 0; - const g = raw[rawIndex + 1] || 0; - const b = raw[rawIndex + 2] || 0; - const { luma, saturation } = getScaleAdjustPixelStats(r, g, b); - if (isScaleAdjustLikelySkinPixel(r, g, b)) continue; - if (saturation > 0.42 && luma < 185) continue; - samples.push({ b, g, luma, r }); - } - } - - if (samples.length === 0) { - return { b: 245, g: 247, luma: 246, r: 245 }; - } - - samples.sort((left, right) => right.luma - left.luma); - const kept = samples.slice(0, Math.max(12, Math.ceil(samples.length * 0.38))); - const totals = kept.reduce( - (acc, sample) => { - acc.r += sample.r; - acc.g += sample.g; - acc.b += sample.b; - acc.luma += sample.luma; - return acc; - }, - { b: 0, g: 0, luma: 0, r: 0 } - ); - - return { - b: totals.b / kept.length, - g: totals.g / kept.length, - luma: totals.luma / kept.length, - r: totals.r / kept.length, - }; -} - -function dilateScaleAdjustStructureMask(params: { - height: number; - mask: Uint8Array; - radius: number; - width: number; -}) { - const { height, mask, radius, width } = params; - if (radius <= 0) return mask; - const output = new Uint8Array(mask.length); - for (let y = 0; y < height; y += 1) { - for (let x = 0; x < width; x += 1) { - if (mask[y * width + x] === 0) continue; - const left = Math.max(0, x - radius); - const right = Math.min(width - 1, x + radius); - const top = Math.max(0, y - radius); - const bottom = Math.min(height - 1, y + radius); - for (let yy = top; yy <= bottom; yy += 1) { - for (let xx = left; xx <= right; xx += 1) { - output[yy * width + xx] = 255; - } - } - } - } - return output; -} - -function buildScaleAdjustStructureInitialMask(params: { - box: { left: number; top: number; width: number; height: number }; - includePersonPixels?: boolean; - raw: Buffer; - width: number; -}) { - const { box, includePersonPixels = false, raw, width } = params; - const background = estimateScaleAdjustBoxBackground(params); - const mask = new Uint8Array(box.width * box.height); - - for (let localY = 0; localY < box.height; localY += 1) { - const y = box.top + localY; - for (let localX = 0; localX < box.width; localX += 1) { - const x = box.left + localX; - const rawIndex = getScaleAdjustRawPixelIndex(width, x, y); - const r = raw[rawIndex] || 0; - const g = raw[rawIndex + 1] || 0; - const b = raw[rawIndex + 2] || 0; - const { luma, saturation } = getScaleAdjustPixelStats(r, g, b); - const likelySkin = isScaleAdjustLikelySkinPixel(r, g, b); - const likelyWhiteFabric = isScaleAdjustLikelyWhiteFabricPixel( - r, - g, - b, - luma, - saturation - ); - const colorDistance = Math.sqrt( - (r - background.r) ** 2 + - (g - background.g) ** 2 + - (b - background.b) ** 2 - ); - - if (includePersonPixels && likelySkin) { - mask[localY * box.width + localX] = 255; - continue; - } - if ( - includePersonPixels && - likelyWhiteFabric && - luma < 246 && - (colorDistance > 12 || luma < background.luma - 4) - ) { - mask[localY * box.width + localX] = 255; - continue; - } - if (likelySkin) continue; - if (likelyWhiteFabric) { - continue; - } - - const darkStructure = luma < Math.min(136, background.luma - 38); - const saturatedStructure = - saturation > 0.16 && luma < 218 && colorDistance > 38; - const woodOrCaneStructure = - r > 46 && - g > 26 && - b < 132 && - r >= g * 0.9 && - g >= b * 1.02 && - saturation > 0.18 && - luma < 218; - - if (darkStructure || saturatedStructure || woodOrCaneStructure) { - mask[localY * box.width + localX] = 255; - } - } - } - - return dilateScaleAdjustStructureMask({ - height: box.height, - mask, - radius: Math.max(1, Math.round(Math.min(box.width, box.height) * 0.004)), - width: box.width, - }); -} - -function filterScaleAdjustStructureComponents(params: { - box: { width: number; height: number }; - mask: Uint8Array; -}) { - const { box, mask } = params; - const width = box.width; - const height = box.height; - const visited = new Uint8Array(mask.length); - const output = new Uint8Array(mask.length); - const queueX: number[] = []; - const queueY: number[] = []; - const minComponentArea = Math.max( - 10, - Math.round(width * height * SCALE_ADJUST_STRUCTURE_LOCK_COMPONENT_MIN_RATIO) - ); - - for (let y = 0; y < height; y += 1) { - for (let x = 0; x < width; x += 1) { - const startIndex = y * width + x; - if (mask[startIndex] === 0 || visited[startIndex]) continue; - - queueX.length = 0; - queueY.length = 0; - queueX.push(x); - queueY.push(y); - visited[startIndex] = 1; - let head = 0; - let area = 0; - let minX = x; - let minY = y; - let maxX = x; - let maxY = y; - - while (head < queueX.length) { - const cx = queueX[head] || 0; - const cy = queueY[head] || 0; - head += 1; - area += 1; - minX = Math.min(minX, cx); - minY = Math.min(minY, cy); - maxX = Math.max(maxX, cx); - maxY = Math.max(maxY, cy); - - for (let dy = -1; dy <= 1; dy += 1) { - for (let dx = -1; dx <= 1; dx += 1) { - if (dx === 0 && dy === 0) continue; - const nx = cx + dx; - const ny = cy + dy; - if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue; - const nextIndex = ny * width + nx; - if (mask[nextIndex] === 0 || visited[nextIndex]) continue; - visited[nextIndex] = 1; - queueX.push(nx); - queueY.push(ny); - } - } - } - - const componentWidth = maxX - minX + 1; - const componentHeight = maxY - minY + 1; - const componentBoxArea = Math.max(1, componentWidth * componentHeight); - const componentDensity = area / componentBoxArea; - const centerXRatio = (minX + componentWidth / 2) / width; - const centerYRatio = (minY + componentHeight / 2) / height; - const touchesTop = minY <= height * 0.04; - const touchesRight = maxX >= width * 0.88; - const edgeSliver = touchesRight && componentWidth < width * 0.18; - const broadTopBackground = - touchesTop && - centerYRatio <= 0.45 && - componentWidth >= width * 0.42 && - componentHeight >= height * 0.18 && - componentDensity >= 0.18; - const elongated = - componentHeight > componentWidth * 2.4 || - componentWidth > componentHeight * 2.4; - const likelyStructure = - area >= minComponentArea || - (elongated && area >= Math.max(8, minComponentArea * 0.4)); - const centeredEnough = centerXRatio >= 0.04 && centerXRatio <= 0.88; - const fillSurfaceComponent = - componentWidth >= width * 0.14 && - componentHeight >= height * 0.045 && - componentWidth <= width * 0.82 && - componentHeight <= height * 0.42 && - componentDensity >= 0.035 && - componentDensity <= 0.72; - - if ( - likelyStructure && - centeredEnough && - !edgeSliver && - !broadTopBackground - ) { - if (fillSurfaceComponent) { - for (let fillY = minY; fillY <= maxY; fillY += 1) { - for (let fillX = minX; fillX <= maxX; fillX += 1) { - output[fillY * width + fillX] = 255; - } - } - } else { - for (let index = 0; index < queueX.length; index += 1) { - output[(queueY[index] || 0) * width + (queueX[index] || 0)] = 255; - } - } - } - } - } - - return dilateScaleAdjustStructureMask({ - height, - mask: output, - radius: Math.max(1, Math.round(Math.min(width, height) * 0.006)), - width, - }); -} - -function solidifyScaleAdjustStructureMask(params: { - box: { width: number; height: number }; - mask: Uint8Array; -}) { - const { box, mask } = params; - const width = box.width; - const height = box.height; - const bridgeGap = Math.max(2, Math.round(Math.min(width, height) * 0.006)); - const output = dilateScaleAdjustStructureMask({ - height, - mask, - radius: Math.max(1, Math.round(Math.min(width, height) * 0.004)), - width, - }); - - for (let y = 0; y < height; y += 1) { - let x = 0; - while (x < width) { - while (x < width && output[y * width + x] !== 0) x += 1; - const gapStart = x; - while (x < width && output[y * width + x] === 0) x += 1; - const gapEnd = x - 1; - const gapLength = gapEnd - gapStart + 1; - if ( - gapLength > 0 && - gapLength <= bridgeGap && - gapStart > 0 && - gapEnd < width - 1 && - output[y * width + gapStart - 1] !== 0 && - output[y * width + gapEnd + 1] !== 0 - ) { - for (let fillX = gapStart; fillX <= gapEnd; fillX += 1) { - output[y * width + fillX] = 255; - } - } - } - } - - for (let x = 0; x < width; x += 1) { - let y = 0; - while (y < height) { - while (y < height && output[y * width + x] !== 0) y += 1; - const gapStart = y; - while (y < height && output[y * width + x] === 0) y += 1; - const gapEnd = y - 1; - const gapLength = gapEnd - gapStart + 1; - if ( - gapLength > 0 && - gapLength <= bridgeGap && - gapStart > 0 && - gapEnd < height - 1 && - output[(gapStart - 1) * width + x] !== 0 && - output[(gapEnd + 1) * width + x] !== 0 - ) { - for (let fillY = gapStart; fillY <= gapEnd; fillY += 1) { - output[fillY * width + x] = 255; - } - } - } - } - - const panelRowThreshold = Math.max(8, Math.round(width * 0.055)); - const panelMinHeight = Math.max(12, Math.round(height * 0.035)); - const panelMaxGap = Math.max(1, Math.round(height * 0.006)); - let panelStart = -1; - let panelGap = 0; - const getRowMarkedCount = (rowY: number) => { - let count = 0; - for (let rowX = 0; rowX < width; rowX += 1) { - if (output[rowY * width + rowX] !== 0) count += 1; - } - return count; - }; - const fillPanelBand = (startY: number, endY: number) => { - const bandHeight = endY - startY + 1; - if (bandHeight < panelMinHeight) return; - let minX = width; - let maxX = -1; - let marked = 0; - for (let bandY = startY; bandY <= endY; bandY += 1) { - for (let bandX = 0; bandX < width; bandX += 1) { - if (output[bandY * width + bandX] === 0) continue; - minX = Math.min(minX, bandX); - maxX = Math.max(maxX, bandX); - marked += 1; - } - } - if (maxX < minX) return; - const span = maxX - minX + 1; - const density = marked / Math.max(1, span * bandHeight); - if ( - span < width * 0.16 || - span > width * 0.86 || - density < 0.025 || - density > 0.78 - ) { - return; - } - for (let fillY = startY; fillY <= endY; fillY += 1) { - for (let fillX = minX; fillX <= maxX; fillX += 1) { - output[fillY * width + fillX] = 255; - } - } - }; - - for (let y = 0; y < height; y += 1) { - const hasPanelRow = getRowMarkedCount(y) >= panelRowThreshold; - if (hasPanelRow) { - if (panelStart < 0) panelStart = y; - panelGap = 0; - continue; - } - if (panelStart < 0) continue; - panelGap += 1; - if (panelGap <= panelMaxGap) continue; - fillPanelBand(panelStart, y - panelGap); - panelStart = -1; - panelGap = 0; - } - if (panelStart >= 0) { - fillPanelBand(panelStart, height - 1 - panelGap); - } - - return dilateScaleAdjustStructureMask({ - height, - mask: output, - radius: Math.max(1, Math.round(Math.min(width, height) * 0.004)), - width, - }); -} - -function getScaleAdjustMaskBoundingBox(params: { - height: number; - mask: Uint8Array; - width: number; -}) { - const { height, mask, width } = params; - let left = width; - let top = height; - let right = -1; - let bottom = -1; - let count = 0; - - for (let y = 0; y < height; y += 1) { - for (let x = 0; x < width; x += 1) { - if (mask[y * width + x] === 0) continue; - left = Math.min(left, x); - top = Math.min(top, y); - right = Math.max(right, x); - bottom = Math.max(bottom, y); - count += 1; - } - } - - if (right < left || bottom < top) return null; - return { - count, - left, - top, - width: right - left + 1, - height: bottom - top + 1, - }; -} - -function extractScaleAdjustMaskBuffer(params: { - box: { left: number; top: number; width: number; height: number }; - mask: Uint8Array; - maskWidth: number; -}) { - const { box, mask, maskWidth } = params; - const output = Buffer.alloc(box.width * box.height); - for (let y = 0; y < box.height; y += 1) { - const sourceStart = (box.top + y) * maskWidth + box.left; - const targetStart = y * box.width; - for (let x = 0; x < box.width; x += 1) { - output[targetStart + x] = mask[sourceStart + x] || 0; - } - } - return output; -} - -async function buildScaleAdjustMaskWashPatch(params: { - background: { b: number; g: number; r: number }; - box: { width: number; height: number }; - maskBuffer: Buffer; -}) { - const { background, box, maskBuffer } = params; - const alpha = await sharp(maskBuffer, { - raw: { channels: 1, height: box.height, width: box.width }, - }) - .blur(Math.max(1.2, Math.min(box.width, box.height) * 0.018)) - .raw() - .toBuffer(); - const rgba = Buffer.alloc(box.width * box.height * 4); - for (let index = 0; index < box.width * box.height; index += 1) { - const offset = index * 4; - rgba[offset] = Math.round(background.r); - rgba[offset + 1] = Math.round(background.g); - rgba[offset + 2] = Math.round(background.b); - rgba[offset + 3] = Math.round((alpha[index] || 0) * 0.9); - } - return sharp(rgba, { - raw: { channels: 4, height: box.height, width: box.width }, - }) - .png({ compressionLevel: 6 }) - .toBuffer(); -} - -function getScaleAdjustAlphaBoundingBox(params: { - height: number; - rawRgba: Buffer; - threshold?: number; - width: number; -}) { - const { height, rawRgba, threshold = 18, width } = params; - let left = width; - let top = height; - let right = -1; - let bottom = -1; - let count = 0; - - for (let y = 0; y < height; y += 1) { - for (let x = 0; x < width; x += 1) { - const alpha = rawRgba[(y * width + x) * 4 + 3] || 0; - if (alpha < threshold) continue; - left = Math.min(left, x); - top = Math.min(top, y); - right = Math.max(right, x); - bottom = Math.max(bottom, y); - count += 1; - } - } - - if (right < left || bottom < top) return null; - return { - count, - left, - top, - width: right - left + 1, - height: bottom - top + 1, - }; -} - -function thresholdScaleAdjustAlphaMask(params: { - maskBuffer: Buffer | Uint8Array; - threshold?: number; -}) { - const { maskBuffer, threshold = 96 } = params; - const output = new Uint8Array(maskBuffer.length); - for (let index = 0; index < maskBuffer.length; index += 1) { - output[index] = (maskBuffer[index] || 0) >= threshold ? 255 : 0; - } - return output; -} - -async function applyScaleAdjustAlphaMaskToRgba(params: { - alphaMask: Uint8Array; - height: number; - rawRgba: Buffer; - width: number; -}) { - const { alphaMask, height, rawRgba, width } = params; - const blur = Math.max(0.45, Math.min(width, height) * 0.0035); - const softenedAlpha = await sharp(Buffer.from(alphaMask), { - raw: { channels: 1, height, width }, - }) - .blur(blur) - .raw() - .toBuffer(); - const output = Buffer.from(rawRgba); - const pixelCount = Math.min(alphaMask.length, Math.floor(output.length / 4)); - for (let index = 0; index < pixelCount; index += 1) { - output[index * 4 + 3] = softenedAlpha[index] || 0; - } - return output; -} - -function getScaleAdjustAlphaBandingStats(params: { - height: number; - maskBuffer: Buffer | Uint8Array; - threshold?: number; - width: number; -}) { - const { height, maskBuffer, threshold = 24, width } = params; - const mask = thresholdScaleAdjustAlphaMask({ maskBuffer, threshold }); - const bbox = getScaleAdjustMaskBoundingBox({ height, mask, width }); - if (!bbox) { - return { - activeRowRatio: 0, - bboxHeightRatio: 0, - bboxWidthRatio: 0, - detected: false, - transitionRatio: 0, - wideRowRatio: 0, - }; - } - - let activeRows = 0; - let transitions = 0; - let wideRows = 0; - let previousCoverage: number | null = null; - for (let y = bbox.top; y < bbox.top + bbox.height; y += 1) { - let rowCount = 0; - for (let x = bbox.left; x < bbox.left + bbox.width; x += 1) { - if (mask[y * width + x] !== 0) rowCount += 1; - } - const coverage = rowCount / Math.max(1, bbox.width); - if (coverage >= 0.08) activeRows += 1; - if (coverage >= 0.45) wideRows += 1; - if ( - previousCoverage !== null && - Math.abs(coverage - previousCoverage) >= 0.28 - ) { - transitions += 1; - } - previousCoverage = coverage; - } - - const bboxHeightRatio = bbox.height / Math.max(1, height); - const bboxWidthRatio = bbox.width / Math.max(1, width); - const activeRowRatio = activeRows / Math.max(1, bbox.height); - const transitionRatio = transitions / Math.max(1, bbox.height - 1); - const wideRowRatio = wideRows / Math.max(1, bbox.height); - const detected = - (bboxWidthRatio >= 0.38 && - bboxHeightRatio >= 0.22 && - wideRowRatio >= 0.18 && - transitionRatio >= 0.12) || - (bboxWidthRatio >= 0.55 && - activeRowRatio >= 0.45 && - transitionRatio >= 0.09); - - return { - activeRowRatio: Number(activeRowRatio.toFixed(3)), - bboxHeightRatio: Number(bboxHeightRatio.toFixed(3)), - bboxWidthRatio: Number(bboxWidthRatio.toFixed(3)), - detected, - transitionRatio: Number(transitionRatio.toFixed(3)), - wideRowRatio: Number(wideRowRatio.toFixed(3)), - }; -} - -async function cleanScaleAdjustAlphaChannel(params: { - height: number; - referenceRawRgb?: Buffer | null; - rawRgba: Buffer; - threshold?: number; - width: number; -}) { - const { - height, - referenceRawRgb = null, - rawRgba, - threshold = SCALE_ADJUST_RMBG_ALPHA_CLEAN_THRESHOLD, - width, - } = params; - const pixelCount = Math.floor(rawRgba.length / 4); - const cleanedRaw = Buffer.from(rawRgba); - const cleanedAlpha = Buffer.alloc(pixelCount); - const range = Math.max(1, 255 - threshold); - const hasReference = - referenceRawRgb && referenceRawRgb.length >= pixelCount * 3; - - for (let index = 0; index < pixelCount; index += 1) { - const colorIndex = index * 4; - const alphaIndex = index * 4 + 3; - const sourceAlpha = rawRgba[alphaIndex] || 0; - let matteArtifact = false; - if (hasReference && sourceAlpha >= threshold) { - const r = rawRgba[colorIndex] || 0; - const g = rawRgba[colorIndex + 1] || 0; - const b = rawRgba[colorIndex + 2] || 0; - const luma = getScaleAdjustPixelLuma(r, g, b); - const channelSpread = Math.max(r, g, b) - Math.min(r, g, b); - const refIndex = index * 3; - const refLuma = getScaleAdjustPixelLuma( - referenceRawRgb?.[refIndex] || 0, - referenceRawRgb?.[refIndex + 1] || 0, - referenceRawRgb?.[refIndex + 2] || 0 - ); - matteArtifact = luma <= 18 && channelSpread <= 18 && refLuma >= 42; - } - const nextAlpha = - sourceAlpha < threshold || matteArtifact - ? 0 - : Math.max(0, Math.min(255, Math.round(((sourceAlpha - threshold) / range) * 255))); - cleanedRaw[alphaIndex] = nextAlpha; - cleanedAlpha[index] = nextAlpha; - } - - return { cleanedAlpha, cleanedRaw }; -} - -async function resizeScaleAdjustAlphaMask(params: { - height: number; - maskBuffer: Buffer; - targetHeight: number; - targetWidth: number; - width: number; -}) { - const { height, maskBuffer, targetHeight, targetWidth, width } = params; - const { data, info } = await sharp(maskBuffer, { - raw: { channels: 1, height, width }, - }) - .resize(targetWidth, targetHeight, { - background: { alpha: 1, b: 0, g: 0, r: 0 }, - fit: "contain", - kernel: sharp.kernel.lanczos3, - }) - .greyscale() - .raw() - .toBuffer({ resolveWithObject: true }); - if (info.channels === 1) return Buffer.from(data); - - const output = Buffer.alloc(targetWidth * targetHeight); - for (let index = 0; index < targetWidth * targetHeight; index += 1) { - output[index] = data[index * info.channels] || 0; - } - return output; -} - -async function buildScaleAdjustRmbgStructureLockedComposite(params: { - placement: ReturnType; - raw: Buffer; - sourceBuffer: Buffer; - sourceImageUrl?: string; - sourceWidth: number; - userId?: string; -}): Promise { - const { - placement, - raw, - sourceBuffer, - sourceImageUrl, - sourceWidth, - userId, - } = params; - if (!userId) return null; - - try { - const sourceCropBuffer = await sharp(sourceBuffer, { failOn: "none" }) - .extract(placement.sourceBox) - .png({ compressionLevel: 6 }) - .toBuffer(); - const cutoutResult = await executeRmbgJob({ - userId, - imageBase64: sourceCropBuffer.toString("base64"), - imageBuffer: sourceCropBuffer, - prompt: "比例调整主体抠图:只保留框选的目标人物/家具/商品主体,输出透明背景 PNG", - skipGallerySave: true, - sourceImageUrl, - }); - const cutoutBuffer = await fetchImageBufferFromUrl(cutoutResult.original_url); - const normalizedCutout = await sharp(cutoutBuffer, { failOn: "none" }) - .rotate() - .ensureAlpha() - .png({ compressionLevel: 6 }) - .toBuffer(); - const cutoutMetadata = await sharp(normalizedCutout, { failOn: "none" }).metadata(); - const cutoutWidth = Math.round(Number(cutoutMetadata.width || 0)); - const cutoutHeight = Math.round(Number(cutoutMetadata.height || 0)); - if (cutoutWidth <= 0 || cutoutHeight <= 0) return null; - const sameSizeCutout = - Math.abs(cutoutWidth - placement.sourceBox.width) <= 2 && - Math.abs(cutoutHeight - placement.sourceBox.height) <= 2; - const sourceCropRaw = sameSizeCutout - ? await sharp(sourceCropBuffer, { failOn: "none" }) - .removeAlpha() - .toColorspace("srgb") - .raw() - .toBuffer() - : null; - - const cutoutRaw = await sharp(normalizedCutout, { failOn: "none" }) - .ensureAlpha() - .raw() - .toBuffer(); - const { cleanedAlpha, cleanedRaw } = await cleanScaleAdjustAlphaChannel({ - height: cutoutHeight, - referenceRawRgb: sourceCropRaw, - rawRgba: cutoutRaw, - width: cutoutWidth, - }); - const highConfidenceCutoutMask = thresholdScaleAdjustAlphaMask({ - maskBuffer: cleanedAlpha, - threshold: 96, - }); - const highConfidenceCutoutBbox = getScaleAdjustMaskBoundingBox({ - height: cutoutHeight, - mask: highConfidenceCutoutMask, - width: cutoutWidth, - }); - if (!highConfidenceCutoutBbox) return null; - const refinedCutoutRaw = await applyScaleAdjustAlphaMaskToRgba({ - alphaMask: highConfidenceCutoutMask, - height: cutoutHeight, - rawRgba: cleanedRaw, - width: cutoutWidth, - }); - const cleanedCutout = await sharp(refinedCutoutRaw, { - raw: { channels: 4, height: cutoutHeight, width: cutoutWidth }, - }) - .png({ compressionLevel: 6 }) - .toBuffer(); - const alphaBbox = getScaleAdjustAlphaBoundingBox({ - height: cutoutHeight, - rawRgba: refinedCutoutRaw, - width: cutoutWidth, - }); - if (!alphaBbox) return null; - - const alphaRatio = alphaBbox.count / Math.max(1, cutoutWidth * cutoutHeight); - const bboxCoversCanvas = - alphaBbox.width >= cutoutWidth * 0.97 && - alphaBbox.height >= cutoutHeight * 0.97; - if ( - alphaRatio < SCALE_ADJUST_RMBG_MIN_ALPHA_RATIO || - (alphaRatio > SCALE_ADJUST_RMBG_MAX_SOLID_ALPHA_RATIO && bboxCoversCanvas) - ) { - return null; - } - - const fullAlphaMask = Buffer.from(highConfidenceCutoutMask); - const sourceMaskBuffer = sameSizeCutout - ? fullAlphaMask - : await resizeScaleAdjustAlphaMask({ - height: cutoutHeight, - maskBuffer: fullAlphaMask, - targetHeight: placement.sourceBox.height, - targetWidth: placement.sourceBox.width, - width: cutoutWidth, - }); - const alphaBandingStats = getScaleAdjustAlphaBandingStats({ - height: placement.sourceBox.height, - maskBuffer: sourceMaskBuffer, - width: placement.sourceBox.width, - }); - if (alphaBandingStats.detected) { - console.warn( - "[Canvas Local Edit] Scale adjust RMBG alpha banding detected; fallback to pixel mask:", - alphaBandingStats - ); - return null; - } - const background = estimateScaleAdjustBoxBackground({ - box: placement.sourceBox, - raw, - width: sourceWidth, - }); - const highConfidenceSourceMask = thresholdScaleAdjustAlphaMask({ - maskBuffer: sourceMaskBuffer, - threshold: 96, - }); - const filteredSourceMask = filterScaleAdjustStructureComponents({ - box: placement.sourceBox, - mask: highConfidenceSourceMask, - }); - const filteredSourceBbox = getScaleAdjustMaskBoundingBox({ - height: placement.sourceBox.height, - mask: filteredSourceMask, - width: placement.sourceBox.width, - }); - const sourceWashBaseMask = filteredSourceBbox - ? solidifyScaleAdjustStructureMask({ - box: placement.sourceBox, - mask: filteredSourceMask, - }) - : highConfidenceSourceMask; - const sourceWashMask = dilateScaleAdjustStructureMask({ - height: placement.sourceBox.height, - mask: sourceWashBaseMask, - radius: Math.max( - 2, - Math.round( - Math.min(placement.sourceBox.width, placement.sourceBox.height) * 0.014 - ) - ), - width: placement.sourceBox.width, - }); - const sourceWashPatch = await buildScaleAdjustMaskWashPatch({ - background, - box: placement.sourceBox, - maskBuffer: Buffer.from(sourceWashMask), - }); - - const subjectCutout = await sharp(cleanedCutout, { failOn: "none" }) - .extract(alphaBbox) - .png({ compressionLevel: 6 }) - .toBuffer(); - const widthFactor = - placement.targetBox.width / Math.max(1, placement.sourceFootprintBox.width); - const heightFactor = - placement.targetBox.height / Math.max(1, placement.sourceFootprintBox.height); - const structureScale = Math.max( - 0.05, - Math.min( - 3.5, - Math.sqrt( - Math.max(0.0025, widthFactor) * Math.max(0.0025, heightFactor) - ) - ) - ); - let placedWidth = Math.max(1, Math.round(alphaBbox.width * structureScale)); - let placedHeight = Math.max(1, Math.round(alphaBbox.height * structureScale)); - if (!sameSizeCutout) { - const maxPlacedWidth = Math.max(1, Math.round(placement.targetBox.width * 1.06)); - const maxPlacedHeight = Math.max(1, Math.round(placement.targetBox.height * 1.06)); - const fitRatio = Math.min( - 1, - maxPlacedWidth / Math.max(1, placedWidth), - maxPlacedHeight / Math.max(1, placedHeight) - ); - placedWidth = Math.max(1, Math.round(placedWidth * fitRatio)); - placedHeight = Math.max(1, Math.round(placedHeight * fitRatio)); - } - - const sourceSubjectBox = sameSizeCutout - ? { - left: placement.sourceBox.left + alphaBbox.left, - top: placement.sourceBox.top + alphaBbox.top, - width: alphaBbox.width, - height: alphaBbox.height, - } - : null; - const sourceCenterX = sourceSubjectBox - ? sourceSubjectBox.left + sourceSubjectBox.width / 2 - : placement.sourceBox.left + placement.sourceBox.width / 2; - const sourceCenterY = sourceSubjectBox - ? sourceSubjectBox.top + sourceSubjectBox.height / 2 - : placement.sourceBox.top + placement.sourceBox.height / 2; - const targetCenterX = sourceSubjectBox - ? placement.targetBox.left + - ((sourceCenterX - placement.sourceFootprintBox.left) / - Math.max(1, placement.sourceFootprintBox.width)) * - placement.targetBox.width - : placement.targetBox.left + placement.targetBox.width / 2; - const targetCenterY = sourceSubjectBox - ? placement.targetBox.top + - ((sourceCenterY - placement.sourceFootprintBox.top) / - Math.max(1, placement.sourceFootprintBox.height)) * - placement.targetBox.height - : placement.targetBox.top + placement.targetBox.height / 2; - const structureOverlay = await sharp(subjectCutout, { failOn: "none" }) - .resize(placedWidth, placedHeight, { - fit: "fill", - kernel: sharp.kernel.lanczos3, - }) - .png({ compressionLevel: 6 }) - .toBuffer(); - - console.info("[Canvas Local Edit] Scale adjust RMBG structure draft applied:", { - alphaRatio: Number(alphaRatio.toFixed(3)), - cutoutHeight, - cutoutWidth, - placedHeight, - placedWidth, - sameSizeCutout, - alphaBandingStats, - sourceHeight: placement.sourceBox.height, - sourceWidth: placement.sourceBox.width, - }); - - return { - method: "rmbg-cutout", - overlay: { - input: structureOverlay, - left: Math.round(targetCenterX - placedWidth / 2), - top: Math.round(targetCenterY - placedHeight / 2), - }, - wash: { - input: sourceWashPatch, - left: placement.sourceBox.left, - top: placement.sourceBox.top, - }, - }; - } catch (error) { - console.warn("[Canvas Local Edit] Scale adjust RMBG structure draft failed; fallback to pixel mask:", { - error: error instanceof Error ? error.message : String(error), - }); - return null; - } -} - -async function buildScaleAdjustStructureLockedComposite(params: { - includePersonPixels?: boolean; - placement: ReturnType; - raw: Buffer; - sourceBuffer: Buffer; - sourceImageUrl?: string; - sourceWidth: number; - userId?: string; -}): Promise { - const { - includePersonPixels = false, - placement, - raw, - sourceBuffer, - sourceImageUrl, - sourceWidth, - userId, - } = params; - // The current RMBG provider can bake horizontal matte stripes into furniture cutouts. - const allowRmbgStructureLock = - process.env.CANVAS_SCALE_ADJUST_ENABLE_RMBG_STRUCTURE === "1" || - (includePersonPixels && - process.env.CANVAS_SCALE_ADJUST_DISABLE_PERSON_RMBG !== "1"); - const rmbgComposite = !allowRmbgStructureLock - ? null - : await buildScaleAdjustRmbgStructureLockedComposite({ - placement, - raw, - sourceBuffer, - sourceImageUrl, - sourceWidth, - userId, - }); - if (rmbgComposite) return rmbgComposite; - if (includePersonPixels) return null; - - const initialMask = buildScaleAdjustStructureInitialMask({ - box: placement.sourceBox, - includePersonPixels, - raw, - width: sourceWidth, - }); - const mask = filterScaleAdjustStructureComponents({ - box: placement.sourceBox, - mask: initialMask, - }); - const structureBbox = getScaleAdjustMaskBoundingBox({ - height: placement.sourceBox.height, - mask, - width: placement.sourceBox.width, - }); - if (!structureBbox) return null; - const maskRatio = structureBbox.count / Math.max(1, placement.sourceBox.width * placement.sourceBox.height); - if (maskRatio < SCALE_ADJUST_STRUCTURE_LOCK_MIN_MASK_RATIO) return null; - const subjectMask = solidifyScaleAdjustStructureMask({ - box: placement.sourceBox, - mask, - }); - const bbox = getScaleAdjustMaskBoundingBox({ - height: placement.sourceBox.height, - mask: subjectMask, - width: placement.sourceBox.width, - }); - if (!bbox) return null; - - const sourceSubjectBox = { - left: placement.sourceBox.left + bbox.left, - top: placement.sourceBox.top + bbox.top, - width: bbox.width, - height: bbox.height, - }; - const sourceSubjectMask = extractScaleAdjustMaskBuffer({ - box: bbox, - mask: subjectMask, - maskWidth: placement.sourceBox.width, - }); - const background = estimateScaleAdjustBoxBackground({ - box: placement.sourceBox, - raw, - width: sourceWidth, - }); - const sourceWashMask = dilateScaleAdjustStructureMask({ - height: placement.sourceBox.height, - mask: subjectMask, - radius: Math.max( - 2, - Math.round(Math.min(placement.sourceBox.width, placement.sourceBox.height) * 0.012) - ), - width: placement.sourceBox.width, - }); - const sourceWashPatch = await buildScaleAdjustMaskWashPatch({ - background, - box: placement.sourceBox, - maskBuffer: Buffer.from(sourceWashMask), - }); - const subjectCrop = await sharp(sourceBuffer, { failOn: "none" }) - .extract(sourceSubjectBox) - .removeAlpha() - .png({ compressionLevel: 6 }) - .toBuffer(); - const subjectAlpha = await sharp(sourceSubjectMask, { - raw: { channels: 1, height: bbox.height, width: bbox.width }, - }) - .blur(Math.max(0.7, Math.min(bbox.width, bbox.height) * 0.006)) - .png({ compressionLevel: 6 }) - .toBuffer(); - const widthFactor = - placement.targetBox.width / Math.max(1, placement.sourceFootprintBox.width); - const heightFactor = - placement.targetBox.height / Math.max(1, placement.sourceFootprintBox.height); - const structureScale = Math.max( - 0.05, - Math.min( - 3.5, - Math.sqrt( - Math.max(0.0025, widthFactor) * Math.max(0.0025, heightFactor) - ) - ) - ); - const placedWidth = Math.max(1, Math.round(bbox.width * structureScale)); - const placedHeight = Math.max(1, Math.round(bbox.height * structureScale)); - const sourceCenterX = sourceSubjectBox.left + sourceSubjectBox.width / 2; - const sourceCenterY = sourceSubjectBox.top + sourceSubjectBox.height / 2; - const targetCenterX = - placement.targetBox.left + - ((sourceCenterX - placement.sourceFootprintBox.left) / - Math.max(1, placement.sourceFootprintBox.width)) * - placement.targetBox.width; - const targetCenterY = - placement.targetBox.top + - ((sourceCenterY - placement.sourceFootprintBox.top) / - Math.max(1, placement.sourceFootprintBox.height)) * - placement.targetBox.height; - const structureOverlay = await sharp(subjectCrop, { failOn: "none" }) - .joinChannel(subjectAlpha) - .resize(placedWidth, placedHeight, { - fit: "fill", - kernel: sharp.kernel.lanczos3, - }) - .png({ compressionLevel: 6 }) - .toBuffer(); - - return { - method: "pixel-mask", - overlay: { - input: structureOverlay, - left: Math.round(targetCenterX - placedWidth / 2), - top: Math.round(targetCenterY - placedHeight / 2), - }, - wash: { - input: sourceWashPatch, - left: placement.sourceBox.left, - top: placement.sourceBox.top, - }, - }; -} - -function getScaleAdjustEditMaskBoxes(params: { - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; - sourceHeight: number; - sourceWidth: number; -}) { - const { regions, scalePercent, sourceHeight, sourceWidth } = params; - return regions.map((region) => { - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const workspaceRect = getScaleAdjustWorkspaceRect( - region.rect, - targetRect, - scalePercent - ); - return rectToPixels(workspaceRect, sourceWidth, sourceHeight); - }); -} - -async function buildScaleAdjustEditMaskBuffer(params: { - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; - sourceHeight: number; - sourceWidth: number; -}) { - const { regions, scalePercent, sourceHeight, sourceWidth } = params; - const boxes = getScaleAdjustEditMaskBoxes({ - regions, - scalePercent, - sourceHeight, - sourceWidth, - }); - const minSide = Math.max(1, Math.min(sourceWidth, sourceHeight)); - const blur = Math.max(5, Math.min(28, Math.round(minSide * 0.018))); - const pad = Math.max(2, Math.round(blur * 0.55)); - const rects = boxes - .map((box) => { - const left = clamp(box.left - pad, 0, Math.max(0, sourceWidth - 1)); - const top = clamp(box.top - pad, 0, Math.max(0, sourceHeight - 1)); - const right = clamp( - box.left + box.width + pad, - left + 1, - sourceWidth - ); - const bottom = clamp( - box.top + box.height + pad, - top + 1, - sourceHeight - ); - return ``; - }) - .join(""); - const editMaskSvg = Buffer.from( - ` - - - - - - - ${rects} - ` - ); - const editAlpha = await sharp(editMaskSvg, { failOn: "none" }) - .resize(sourceWidth, sourceHeight, { fit: "fill" }) - .greyscale() - .raw() - .toBuffer(); - const rgba = Buffer.alloc(sourceWidth * sourceHeight * 4); - for (let index = 0; index < sourceWidth * sourceHeight; index += 1) { - const offset = index * 4; - const editable = editAlpha[index] || 0; - rgba[offset] = 0; - rgba[offset + 1] = 0; - rgba[offset + 2] = 0; - rgba[offset + 3] = clamp(255 - editable, 0, 255); - } - return sharp(rgba, { - raw: { channels: 4, height: sourceHeight, width: sourceWidth }, - }) - .png({ compressionLevel: 9 }) - .toBuffer(); -} - -async function buildScaleAdjustVisualLayoutGuideBuffer(params: { - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; - sourceBuffer: Buffer; - sourceHeight: number; - sourceImageUrl?: string; - sourceWidth: number; - structureLockAppliedRef?: { value: boolean }; - structureLockedDraft?: boolean; - userId?: string; -}) { - const { - regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceImageUrl, - sourceWidth, - structureLockAppliedRef, - structureLockedDraft = false, - userId, - } = params; - const sourceRaw = - structureLockedDraft || regions.length > 0 - ? await sharp(sourceBuffer, { failOn: "none" }) - .removeAlpha() - .toColorspace("srgb") - .raw() - .toBuffer() - : null; - const sourceFootprintBoxes: Array<{ - background?: { b: number; g: number; r: number } | null; - left: number; - top: number; - width: number; - height: number; - }> = []; - const placements: Array> = - []; - const composites: Array<{ input: Buffer; left: number; top: number }> = []; - const subjectWashComposites: Array<{ - input: Buffer; - left: number; - top: number; - }> = []; - - for (const region of regions) { - const placement = getScaleAdjustVisualGuidePlacement({ - height: sourceHeight, - region, - scalePercent, - width: sourceWidth, - }); - placements.push(placement); - const targetWidthFactor = - placement.targetBox.width / Math.max(1, placement.sourceFootprintBox.width); - const targetHeightFactor = - placement.targetBox.height / Math.max(1, placement.sourceFootprintBox.height); - const shouldUseStructureLock = - structureLockedDraft && - sourceRaw && - (targetWidthFactor > 1.08 || - targetHeightFactor > 1.08 || - targetWidthFactor < 0.92 || - targetHeightFactor < 0.92); - const structureLockedComposite = shouldUseStructureLock - ? await buildScaleAdjustStructureLockedComposite({ - includePersonPixels: - isScaleAdjustPersonLikePrompt(region.prompt) || - hasScaleAdjustPersonPixelSignal({ - box: placement.sourceBox, - raw: sourceRaw, - width: sourceWidth, - }), - placement, - raw: sourceRaw, - sourceBuffer, - sourceImageUrl, - sourceWidth, - userId, - }) - : null; - - if (structureLockedComposite) { - if (structureLockAppliedRef) { - structureLockAppliedRef.value = true; - } - subjectWashComposites.push(structureLockedComposite.wash); - composites.push(structureLockedComposite.overlay); - continue; - } - - const shouldUseShrinkCutoutDraft = - process.env.CANVAS_SCALE_ADJUST_ENABLE_RMBG_SHRINK_CUTOUT === "1" && - !structureLockedDraft && - sourceRaw && - userId && - (targetWidthFactor < 0.92 || targetHeightFactor < 0.92); - const shrinkCutoutComposite = shouldUseShrinkCutoutDraft - ? await buildScaleAdjustRmbgStructureLockedComposite({ - placement, - raw: sourceRaw, - sourceBuffer, - sourceImageUrl, - sourceWidth, - userId, - }) - : null; - - if (shrinkCutoutComposite) { - subjectWashComposites.push(shrinkCutoutComposite.wash); - composites.push(shrinkCutoutComposite.overlay); - continue; - } - - sourceFootprintBoxes.push({ - ...placement.sourceFootprintBox, - background: sourceRaw - ? estimateScaleAdjustBoxBackground({ - box: placement.sourceFootprintBox, - raw: sourceRaw, - width: sourceWidth, - }) - : null, - }); - - const resizedCropBuffer = await sharp(sourceBuffer, { failOn: "none" }) - .extract(placement.sourceBox) - .resize(placement.placedWidth, placement.placedHeight, { - fit: "fill", - }) - .png({ compressionLevel: 6 }) - .toBuffer(); - const cropBuffer = await sharp(resizedCropBuffer, { failOn: "none" }) - .ensureAlpha() - .composite([ - { - input: buildScaleAdjustPatchMaskSvg({ - height: placement.placedHeight, - width: placement.placedWidth, - }), - blend: "dest-in", - }, - ]) - .png({ compressionLevel: 6 }) - .toBuffer(); - composites.push({ - input: cropBuffer, - left: placement.placedLeft, - top: placement.placedTop, - }); - } - - const washComposite = sourceFootprintBoxes.length - ? [ - { - input: buildScaleAdjustSourceFootprintWashSvg({ - boxes: sourceFootprintBoxes, - height: sourceHeight, - width: sourceWidth, - }), - left: 0, - top: 0, - }, - ] - : []; - const targetShadowComposite = placements.length - ? structureLockedDraft - ? [] - : [ - { - input: buildScaleAdjustTargetFootprintShadowSvg({ - height: sourceHeight, - placements, - width: sourceWidth, - }), - left: 0, - top: 0, - }, - ] - : []; - - return sharp(sourceBuffer, { failOn: "none" }) - .composite([ - ...washComposite, - ...subjectWashComposites, - ...targetShadowComposite, - ...composites, - ]) - .png({ compressionLevel: 6 }) - .toBuffer(); -} - -async function createScaleAdjustPatchReference(params: { - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; - sourceBuffer: Buffer; - sourceHeight: number; - sourceImageUrl?: string; - sourceWidth: number; - userId?: string; -}): Promise { - const { - regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceImageUrl, - sourceWidth, - userId, - } = params; - const workspaceRect = expandRectToProviderAspectLimit( - getScaleAdjustPatchWorkspaceRect(regions, scalePercent), - sourceWidth, - sourceHeight - ); - const workspacePixelRect = rectToPixels(workspaceRect, sourceWidth, sourceHeight); - const shouldUseStructureLockedDraft = hasScaleAdjustStructureTarget( - regions, - scalePercent - ); - const structureLockAppliedRef = { value: false }; - const targetDraftBuffer = await buildScaleAdjustVisualLayoutGuideBuffer({ - regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceImageUrl, - sourceWidth, - structureLockAppliedRef, - structureLockedDraft: shouldUseStructureLockedDraft, - userId, - }); - const [sourceCropBuffer, targetDraftCropBuffer] = await Promise.all([ - sharp(sourceBuffer, { failOn: "none" }) - .extract(workspacePixelRect) - .png({ compressionLevel: 6 }) - .toBuffer(), - sharp(targetDraftBuffer, { failOn: "none" }) - .extract(workspacePixelRect) - .png({ compressionLevel: 6 }) - .toBuffer(), - ]); - const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; - const [sourceCropUpload, targetDraftUpload] = await Promise.all([ - uploadFile( - `canvas-scale-adjust-workspace-source-${suffix}.png`, - toArrayBuffer(sourceCropBuffer) - ), - uploadFile( - `canvas-scale-adjust-workspace-target-draft-${suffix}.png`, - toArrayBuffer(targetDraftCropBuffer) - ), - ]); - - return { - sourceCropUrl: sourceCropUpload.url, - structureLockedDraft: structureLockAppliedRef.value, - targetDraftUrl: targetDraftUpload.url, - workspacePixelRect, - workspaceRect, - }; -} - function wrapText(text: string, maxChars: number, maxLines = 3) { const compact = text.replace(/\s+/g, " ").trim(); if (!compact) return []; @@ -3099,278 +475,6 @@ function buildAnnotationSvg(params: { `); } -function buildScaleAdjustAnnotationSvg(params: { - width: number; - height: number; - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; -}) { - const { width, height, regions, scalePercent } = params; - const minSide = Math.max(1, Math.min(width, height)); - const strokeWidth = Math.max(2, Math.round(minSide * 0.0034)); - const fontSize = Math.max(16, Math.round(minSide * 0.018)); - const labelPadX = Math.round(fontSize * 0.45); - const labelPadY = Math.round(fontSize * 0.24); - const targetColor = "#111827"; - const sourceColor = "#9ca3af"; - const helperColor = "#4b5563"; - const label = (text: string, x: number, y: number, color: string) => { - const labelWidth = Math.round(text.length * fontSize * 0.62 + labelPadX * 2); - const labelHeight = Math.round(fontSize * 1.2 + labelPadY * 2); - const left = clamp(x, 6, Math.max(6, width - labelWidth - 6)); - const top = clamp(y, 6, Math.max(6, height - labelHeight - 6)); - return ` - - ${escapeXml(text)} - `; - }; - - const regionSvg = regions - .map((region) => { - const source = region.pixelRect; - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const target = - region.targetPixelRect || rectToPixels(targetRect, width, height); - const radius = Math.max(8, Math.round(strokeWidth * 2)); - const sourceCenterX = source.left + source.width / 2; - const sourceCenterY = source.top + source.height / 2; - const targetCenterX = target.left + target.width / 2; - const targetCenterY = target.top + target.height / 2; - const widthFactor = source.width > 0 ? target.width / source.width : 1; - const heightFactor = source.height > 0 ? target.height / source.height : 1; - const isShrink = widthFactor < 0.92 || heightFactor < 0.92; - const isEnlarge = widthFactor > 1.08 || heightFactor > 1.08; - const actionLabel = isShrink ? "SHRINK" : isEnlarge ? "ENLARGE" : "MOVE"; - const scaleLabel = `${actionLabel} ${widthFactor.toFixed(2)}W ${heightFactor.toFixed(2)}H`; - const instructionLabel = isShrink - ? "OLD OUTSIDE -> BG" - : isEnlarge - ? "TARGET = FINAL FOOTPRINT" - : "FINAL SUBJECT CENTER"; - const centerMoved = - Math.hypot(targetCenterX - sourceCenterX, targetCenterY - sourceCenterY) > - Math.max(8, minSide * 0.012); - - return ` - - - - - - - ${ - centerMoved - ? `` - : "" - } - ${label(`OLD ${region.index}`, source.left + strokeWidth, source.top + strokeWidth, sourceColor)} - ${label(`TARGET ${region.index}`, target.left + strokeWidth, target.top + strokeWidth, targetColor)} - ${label(scaleLabel, target.left + strokeWidth, target.top + target.height + strokeWidth * 2, helperColor)} - ${label(instructionLabel, source.left + strokeWidth, source.top + source.height + strokeWidth * 2, helperColor)} - `; - }) - .join(""); - - return Buffer.from(` - - - - - - - - - ${regionSvg} - - `); -} - -function buildScaleAdjustZoomedCoordinateSvg(params: { - width: number; - height: number; - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; -}) { - const { width, height, regions, scalePercent } = params; - const minSide = Math.max(1, Math.min(width, height)); - const strokeWidth = Math.max(3, Math.round(minSide * 0.006)); - const fontSize = Math.max(22, Math.round(minSide * 0.026)); - const smallFontSize = Math.max(18, Math.round(fontSize * 0.72)); - const panelMarginX = Math.round(width * 0.1); - const panelMarginY = Math.round(height * 0.12); - const panelLeft = panelMarginX; - const panelTop = panelMarginY; - const panelWidth = Math.max(1, width - panelMarginX * 2); - const panelHeight = Math.max(1, height - panelMarginY * 2); - const sourceColor = "#9ca3af"; - const targetColor = "#111827"; - const helperColor = "#4b5563"; - const padX = Math.round(fontSize * 0.42); - const labelHeight = Math.round(fontSize * 1.35); - const label = (text: string, x: number, y: number, color: string) => { - const labelWidth = Math.min( - Math.round(text.length * fontSize * 0.58 + padX * 2), - Math.max(160, width - 16) - ); - const left = clamp(x, 8, Math.max(8, width - labelWidth - 8)); - const top = clamp(y, 8, Math.max(8, height - labelHeight - 8)); - return ` - - ${escapeXml(text)} - `; - }; - - const regionSvg = regions - .map((region) => { - const source = region.pixelRect; - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const target = - region.targetPixelRect || rectToPixels(targetRect, width, height); - const sourceRight = source.left + source.width; - const sourceBottom = source.top + source.height; - const targetRight = target.left + target.width; - const targetBottom = target.top + target.height; - const unionLeft = Math.min(source.left, target.left); - const unionTop = Math.min(source.top, target.top); - const unionRight = Math.max(sourceRight, targetRight); - const unionBottom = Math.max(sourceBottom, targetBottom); - const marginX = Math.max(12, Math.round((unionRight - unionLeft) * 0.35)); - const marginY = Math.max(12, Math.round((unionBottom - unionTop) * 0.35)); - const viewLeft = unionLeft - marginX; - const viewTop = unionTop - marginY; - const viewWidth = Math.max(1, unionRight - unionLeft + marginX * 2); - const viewHeight = Math.max(1, unionBottom - unionTop + marginY * 2); - const scale = Math.min( - panelWidth / viewWidth, - panelHeight / viewHeight - ); - const drawnWidth = viewWidth * scale; - const drawnHeight = viewHeight * scale; - const originX = panelLeft + (panelWidth - drawnWidth) / 2 - viewLeft * scale; - const originY = panelTop + (panelHeight - drawnHeight) / 2 - viewTop * scale; - const project = (box: { left: number; top: number; width: number; height: number }) => ({ - left: Math.round(originX + box.left * scale), - top: Math.round(originY + box.top * scale), - width: Math.max(1, Math.round(box.width * scale)), - height: Math.max(1, Math.round(box.height * scale)), - }); - const sourceBox = project(source); - const targetBox = project(target); - const sourceCenterX = sourceBox.left + sourceBox.width / 2; - const sourceCenterY = sourceBox.top + sourceBox.height / 2; - const targetCenterX = targetBox.left + targetBox.width / 2; - const targetCenterY = targetBox.top + targetBox.height / 2; - const widthFactor = source.width > 0 ? target.width / source.width : 1; - const heightFactor = source.height > 0 ? target.height / source.height : 1; - const actionLabel = - widthFactor < 0.92 || heightFactor < 0.92 - ? "SHRINK" - : widthFactor > 1.08 || heightFactor > 1.08 - ? "ENLARGE" - : "MOVE"; - const scaleLabel = `${actionLabel} ${widthFactor.toFixed(2)}W ${heightFactor.toFixed(2)}H`; - const radius = Math.max(10, Math.round(strokeWidth * 2.2)); - const centerMoved = - Math.hypot(targetCenterX - sourceCenterX, targetCenterY - sourceCenterY) > - Math.max(10, minSide * 0.018); - - return ` - - - - - ${ - centerMoved - ? `` - : "" - } - ${label(`OLD ${region.index}`, sourceBox.left, sourceBox.top - labelHeight - strokeWidth, sourceColor)} - ${label(`TARGET ${region.index}`, targetBox.left, targetBox.top + strokeWidth, targetColor)} - ${label(scaleLabel, targetBox.left, targetBox.top + targetBox.height + strokeWidth * 2, helperColor)} - ${label("OLD OUTSIDE -> BG", sourceBox.left, sourceBox.top + sourceBox.height + strokeWidth * 4 + labelHeight, helperColor)} - `; - }) - .join(""); - - return Buffer.from(` - - - - - - - - - LOCAL SCALE MAP - USE PROMPT PIXELS FOR ABSOLUTE POSITION - ${regionSvg} - - `); -} - -function buildScaleAdjustMarkedPhotoGuideSvg(params: { - width: number; - height: number; - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; -}) { - const { width, height, regions, scalePercent } = params; - const minSide = Math.max(1, Math.min(width, height)); - const strokeWidth = Math.max(3, Math.round(minSide * 0.005)); - const currentColor = "#00b8d4"; - const finalColor = "#2563eb"; - - const regionSvg = regions - .map((region) => { - const source = region.pixelRect; - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const target = - region.targetPixelRect || rectToPixels(targetRect, width, height); - const radius = Math.max(8, Math.round(strokeWidth * 2)); - return ` - - - - - `; - }) - .join(""); - - return Buffer.from(` - - - ${regionSvg} - - `); -} - -async function buildScaleAdjustMarkedPhotoGuideBuffer(params: { - sourceBuffer: Buffer; - width: number; - height: number; - regions: NormalizedLocalEditRegion[]; - scalePercent?: ScaleAdjustPercent | null; -}) { - const { sourceBuffer, width, height, regions, scalePercent } = params; - return sharp(sourceBuffer, { failOn: "none" }) - .rotate() - .resize(width, height, { fit: "cover", position: "center" }) - .modulate({ brightness: 1.04, saturation: 0.45 }) - .composite([ - { - input: buildScaleAdjustMarkedPhotoGuideSvg({ - height, - regions, - scalePercent, - width, - }), - left: 0, - top: 0, - }, - ]) - .png({ compressionLevel: 6 }) - .toBuffer(); -} - function buildLocalEditPrompt(regions: NormalizedLocalEditRegion[]) { const regionLines = regions .map((region) => { @@ -3414,426 +518,58 @@ function buildLocalEditPrompt(regions: NormalizedLocalEditRegion[]) { ].join("\n"); } -function buildScaleAdjustPrompt( +function buildSimpleScaleAdjustPrompt( regions: NormalizedLocalEditRegion[], scalePercent: ScaleAdjustPercent | null | undefined, - cropReferences: ScaleAdjustCropReference[] = [], - sourceSize?: { width: number; height: number } -) { - const sourceSizeLine = sourceSize - ? `最终输出必须保持与输入图片1完全相同的画幅和像素尺寸:${sourceSize.width} x ${sourceSize.height} px。` - : "最终输出必须保持与输入图片1完全相同的画幅和像素尺寸。"; - const regionLines = regions - .map((region) => { - const cropIndex = cropReferences.findIndex( - (reference) => reference.regionIndex === region.index - ); - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const sourceCenterX = region.rect.x + region.rect.width / 2; - const sourceCenterY = region.rect.y + region.rect.height / 2; - const targetCenterX = targetRect.x + targetRect.width / 2; - const targetCenterY = targetRect.y + targetRect.height / 2; - const moved = - Math.hypot(targetCenterX - sourceCenterX, targetCenterY - sourceCenterY) > - 0.01; - const targetPixelRect = - region.targetPixelRect || - (sourceSize - ? rectToPixels(targetRect, sourceSize.width, sourceSize.height) - : null); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; - const sourcePixelLine = `源框像素坐标:x=${region.pixelRect.left}, y=${region.pixelRect.top}, w=${region.pixelRect.width}, h=${region.pixelRect.height}`; - const targetPixelLine = targetPixelRect - ? `目标框像素坐标:x=${targetPixelRect.left}, y=${targetPixelRect.top}, w=${targetPixelRect.width}, h=${targetPixelRect.height}` - : `目标框相对坐标:x=${Math.round(targetRect.x * 1000) / 10}%, y=${Math.round(targetRect.y * 1000) / 10}%, w=${Math.round(targetRect.width * 1000) / 10}%, h=${Math.round(targetRect.height * 1000) / 10}%`; - const scaleLine = `目标视觉占位约为原主体宽度的 ${widthFactor.toFixed(2)} 倍、高度的 ${heightFactor.toFixed(2)} 倍;执行时必须以等比主体缩放为准,不要拉伸主体去硬贴目标框。`; - const targetPositionNote = moved - ? "目标框同时指定用户希望的最终目标大小和目标位置,目标主体调整后的视觉中心应移动到目标框中心附近。" - : "目标框指定用户希望的最终目标大小,目标主体调整后应围绕当前主体位置自然放置。"; - const cropNote = - cropIndex >= 0 - ? `;输入图片${cropIndex + 3}是该区域的干净局部裁切参考图,只用于识别目标主体的身份、轮廓与原始比例` - : ""; - return `区域 ${region.index}${cropNote}:请在输入图片1中找到源框范围内最主要、可独立调整的商品/物体主体。${sourcePixelLine};${targetPixelLine};${scaleLine}${targetPositionNote}源框只是“寻找主体”的范围,不是最终边界,也不是要缩放或贴回的矩形补丁。目标框只是主体调整后的视觉占位参考,不要求主体填满矩形,更不能改变主体自身宽高比、透视或形体。请像真实图片编辑一样先保留锁定的原始画布,再只把这个主体整体等比变大/变小/移动到目标视觉占位;主体缩放后露出或遮挡的极小背景区域需要自然重建。严禁把输入图片1整张图、输入图片2目标布局参考图、任意裁切图、源框矩形区域或目标框矩形区域当成图片块整体缩放、平移、复制、裁切或贴回。如果源框中只覆盖到主体的一部分,请根据局部裁切参考和可见结构推断该主体的完整可见轮廓,只调整主体,不调整矩形框内背景。`; - }) - .join("\n"); - const cropLines = cropReferences - .map( - (reference, index) => - `输入图片${index + 3}:区域 ${reference.regionIndex} 的原图干净局部裁切参考图,只用于确认要缩放的主体身份、轮廓和宽高比,不能当成输出底图,也不能把裁切图整体贴回。` - ) - .join("\n"); - - return [ - "这是一项局部主体比例 inpaint/edit 任务,不是整图缩放、整图裁切或重新构图任务。", - sourceSizeLine, - "输入图片1是原始干净图,也是最终输出必须继承的唯一画面基底。除目标主体尺寸变化与必要背景补全外,输入图片1中的文字、Logo、装饰、排版、背景、光线、构图边界和所有未选区域必须保持不变。", - "输入图片2是一张与输入图片1尺寸和画幅完全相同的完整画面编辑意图图,不是输出底图。它保留原图完整画幅作为稳定参考,并把源框旧主体占位强淡化为“这里的原尺寸主体需要被目标尺寸替换并自然修复背景”的指令;同时把同一目标主体粗略缩放后放在用户希望的最终位置和大小。请只读取目标主体的最终视觉占位、中心位置和原画幅关系;输入图片2里被淡化的旧主体不能表示最终还要保留原尺寸主体。不得学习、复刻或输出淡化痕迹、阴影占位、矩形裁切边缘、拼接痕迹或参考图粗糙画质。", - cropLines - ? `输入图片3及之后是框选区域的干净局部裁切参考图,作用是帮助你确认“要缩放的是哪个主体”。这些裁切图不是输出底图,不得被整体放大、贴回或覆盖到原图上。\n${cropLines}` - : "", - "输入图片2中的完整画面编辑意图是强约束:淡化的 OLD 占位表示旧尺寸主体要被移除/修复,清晰的 TARGET 占位表示最终主体大小和中心位置;整张图不应缩放、裁切或平移。最终输出必须回到输入图片1的真实照片环境中完成自然编辑,不得直接粘贴 input2 的矩形图块;主体不需要填满目标矩形,必须保持主体自身原始宽高比和透视形体。", - "如果系统或模型只能读取一张参考图,必须优先以输入图片1为输出基底,不得清理、改写或删除输入图片1中框选区域外的任何文字和图形。", - "系统已根据用户框选区域计算出下方每个区域的原图坐标;框选区域只是定位目标主体的搜索范围,不是最终画面的裁切块、贴片、蒙版边界,也不是放大后的空间上限,更不是要整体缩放的矩形图层。", - "最终结果必须保持原始干净图的画幅比例、构图边界、镜头透视、光线、色温、材质质感和清晰度;严禁整张图整体缩放、裁切、平移、重新排版或重新生成。", - "Highest priority rule: do NOT zoom, crop, resize, reframe, pan, or regenerate the full canvas. Treat image 1 as a locked background plate; edit only the selected subject and the smallest necessary background around its old and new footprint.", - "请不要生成任何彩色框、矩形边框、箭头、连线、角点、编号圆点、提示词气泡、标注文字、UI 控件或半透明色块。", - "请同时使用下方每个区域的源框/目标框像素坐标和输入图片2的目标布局参考来理解目标占位。坐标和参考图只用于指导主体位置和大小,不是要求把某个矩形图块缩放后贴回。", - "", - "任务:先在输入图片1中识别源框范围内最主要、可独立调整的主体物体,再只对这个“主体物体”做局部比例调整。调整后的主体大小和位置必须接近目标框表示的视觉占位;不接受看起来和原图几乎相同的输出。", - regionLines, - "", - "关键要求:", - "1. 只调整目标主体物体本身的整体视觉比例,不得保留原尺寸;主体轮廓宽度和高度必须同步等比变化,宽高比必须与原主体一致,不能为了贴合目标框而拉宽、压窄、拉高或压扁。", - "2. 严禁把整个矩形框选区域、输入图片1整张图或任意裁切图当成图片块整体缩放、平移、复制、裁切或贴回;最终画面不得出现矩形拼接边缘、色差硬边、补丁感、裁切线或局部贴片痕迹。", - "2.1 严禁把输入图片1整张图整体放大、缩小、裁切或重新构图;画面中的标题、Logo、页面文字、边框、窗框、背景家具或非目标主体必须作为像素锚点保持原位置和原比例,不能跟着目标主体变化。", - "3. 如果输入图片2中的目标框明显小于源框,目标主体应自然变小,主体缩小后露出的背景、桌面、墙面、阴影、纹理和透视必须被重新生成并无缝补全,选区内应出现明显新增留白或背景。", - "4. 如果输入图片2中的目标框明显大于源框,目标主体应自然变大;允许主体自然超出用户手画的原始源框,使用周围真实背景完成边缘、阴影和遮挡衔接。宽度和高度都要同步变大,不能出现“高度变高但宽度变窄”的非等比变形;主体边缘与遮挡关系要合理,不能产生突兀裁切。", - "5. 如果目标框中心与源框中心不同,允许主体同步移动到目标框中心附近;如果主体靠近画布边界导致目标空间不足,请用能完整放入画面的最大统一倍率整体调整,绝不能为了塞进画面而只压缩宽度或只拉伸高度。", - "6. 框选区域内非目标主体的背景、墙面、桌面、植物、文字和其它物体应保持原场景逻辑,不要跟着主体一起缩放。", - "6.1 比例调整后的主体边缘必须和周围环境自然融合,选区边界不能被肉眼看出;不得出现一整块矩形区域清晰度、颜色、光照、纹理或透视突然变化。", - "6.2 框选区域通常会包含主体周围的背景留白,背景留白不是目标主体。请锁定这些非主体背景的窗框、文字、地毯纹理、墙面、桌面边缘和透视线,只重建主体缩放后被遮挡或露出的极小必要区域;不要把框选矩形当作整块背景重新生成。", - "6.3 如果框选范围内没有清晰、完整、可独立缩放的主体物体,请保持该区域背景结构稳定,不要为了制造变化而重绘窗框、文字、墙面、地面或其它非主体元素。", - "7. 未受比例调整影响的其它画面区域必须保持原图不变,尤其是框选区域外的文字、Logo、标题、尺寸标注、装饰条和页面排版不得被清理、改写、模糊或重绘。", - "8. 最终输出必须是一张完整、干净、无缝的照片,不得出现任何选区框、说明文字、对比线、比例数字或 UI 元素。", - "9. 输出前自检:如果目标主体大小与原图相比没有明显变化,或者主体宽高比发生非等比变形,必须重新生成;禁止返回看起来和原图相同或被拉伸的结果。", - ].join("\n"); -} - -function buildScaleAdjustCoordinatePrompt( - regions: NormalizedLocalEditRegion[], - scalePercent: ScaleAdjustPercent | null | undefined, - sourceSize: { width: number; height: number }, - cropReferences: ScaleAdjustCropReference[] = [], - options: { - falSafe?: boolean; - markedPhotoGuide?: boolean; - visualLayoutGuide?: boolean; - } = {} -) { - const regionLines = regions - .map((region) => { - const cropIndex = cropReferences.findIndex( - (reference) => reference.regionIndex === region.index - ); - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const targetPixelRect = - region.targetPixelRect || - rectToPixels(targetRect, sourceSize.width, sourceSize.height); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; - const sourceRight = region.pixelRect.left + region.pixelRect.width; - const sourceBottom = region.pixelRect.top + region.pixelRect.height; - const targetRight = targetPixelRect.left + targetPixelRect.width; - const targetBottom = targetPixelRect.top + targetPixelRect.height; - const regionUserInstruction = region.prompt.trim(); - const userInstructionLine = regionUserInstruction - ? ` User instruction for this region: ${regionUserInstruction}.` - : ""; - const isShrink = widthFactor < 0.92 || heightFactor < 0.92; - const isEnlarge = widthFactor > 1.08 || heightFactor > 1.08; - const scaleDirection = - isShrink - ? "make the selected subject clearly smaller" - : isEnlarge - ? "make the selected subject clearly larger" - : "move/fit the selected subject to the target box"; - const footprintRule = isShrink - ? "After shrinking, the original OLD footprint outside the TARGET box must be cleared and rebuilt as natural background/floor/rug/wall; the selected subject must not still touch the OLD box edges." - : isEnlarge - ? "After enlarging, the same selected subject should visibly occupy more of the TARGET footprint, with natural shadows and occlusion; do not just move it or stretch one axis." - : "Keep the subject centered on the TARGET box without changing the full canvas."; - - const cropNote = - cropIndex >= 0 - ? options.falSafe - ? ` Input image ${cropIndex + 3} is an extra identity and silhouette reference.` - : ` Input image ${cropIndex + 3} is a clean crop reference for this same target subject identity and silhouette; use it only to recognize the subject, never paste it, and do not preserve its old size.` - : ""; - if (options.falSafe) { - const actionPhrase = - isShrink - ? "resize the selected subject proportionally smaller and place it inside the final footprint" - : isEnlarge - ? "resize the same selected subject proportionally larger toward the final footprint" - : "place the same selected subject on the final footprint"; - const blendPhrase = - isShrink - ? "Blend the newly visible floor, rug, wall, window area, shadow, and background around it naturally." - : isEnlarge - ? "Blend edges, contact shadows, and occlusion with the surrounding room naturally." - : "Keep the surrounding room stable."; - return `Region ${region.index}: current target-subject search box in source photo left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; requested final footprint left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; scale factor width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. Edit direction: ${actionPhrase}. ${blendPhrase}${cropNote}`; - } - return `Region ${region.index}: OLD search box in input 1 left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; TARGET final visual footprint left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; target scale is ${widthFactor.toFixed(2)}x width and ${heightFactor.toFixed(2)}x height. Main action: ${scaleDirection}.${userInstructionLine} The final selected-subject silhouette must clearly leave the OLD footprint edges and align much closer to TARGET than OLD; returning an almost unchanged target subject footprint is not acceptable. ${footprintRule}${cropNote}`; - }) - .join("\n"); - const cropLines = cropReferences - .map( - (reference, index) => - `Input image ${index + 3}: clean crop for Region ${reference.regionIndex}; identity/shape reference only, not a patch or layer.` - ) - .join("\n"); - - if (options.falSafe) { - return [ - "Interior selected-subject scale photo edit.", - `Return one realistic photo with the same camera frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, - "Input image 1 is the source photo. Input image 2 is a marked copy of the source photo for location guidance only and should not appear in the final photo.", - "In the guide, the cyan dashed box marks the existing selected target subject area and the blue solid box marks the requested final footprint.", - "Resize only the selected target subject indicated by each current box. The target may be a person/model/child/body part, furniture, product, or another object. Keep the camera, room layout, walls, windows, floor, rug, sofa, lamp, text, background, and all non-target subjects stable.", - "Preserve the target identity, person anatomy/face/clothing or product material/structure, perspective, contact shadows, and natural aspect ratio/proportions.", - "For a smaller final footprint, show the selected subject smaller and blend newly visible floor, rug, wall, window area, shadow, and background around it naturally. For a larger final footprint, scale the same selected subject proportionally with natural edges and contact shadows.", - "Return a clean photo without guide marks, boxes, arrows, overlays, patch edges, color mismatch, or full-frame zoom.", - cropLines ? `${cropLines}` : "", - "", - "Region instructions:", - regionLines, - ].join("\n"); - } - - const coordinateGuideLine = options.visualLayoutGuide - ? "输入图片2是一张完整画面的粗略目标布局草稿,不是输出底图。它把 OLD 源框旧主体占位洗淡,表示旧尺寸主体必须从原尺寸位置移除并自然修复背景;同时把目标主体粗略缩放/移动到 TARGET 最终占位附近,这个缩小后的位置和尺寸是最终结果必须匹配的几何目标。请把 input 2 当成最终构图/比例的强约束:如果 input 2 中目标主体比 input 1 小,最终输出也必须明显变小,不能保留 input 1 的原尺寸主体。不要复制 input 2 的淡化痕迹、粗糙拼接、局部透明边、矩形补丁、亮度变化或参考图画质;最终必须以 input 1 的真实照片为唯一画面基底重新完成无缝图片编辑。" - : options.markedPhotoGuide - ? "输入图片2是一张原图浅化后的完整画面位置参考图,不是输出底图。青色虚线框表示当前主体搜索框(对应下方 OLD),蓝色实线框表示目标最终占位(对应下方 TARGET)。请用输入图片2理解主体在真实室内画面中的位置关系,但最终图不能出现任何框线、色块、标注或参考图的浅化效果。" - : "Input image 2 is a zoomed neutral coordinate instruction map, not a photo and not output content. It enlarges the OLD and TARGET boxes so their relative scale is easy to read; use the numeric pixel coordinates below for the exact absolute position in input image 1. The OLD box/label locates the current selected subject; the TARGET box/label gives the required final footprint, center, and scale factor. If the map says OLD OUTSIDE -> BG, rebuild the old full-size subject area outside TARGET as natural background in the final photo. Read the boxes, labels, arrows, and scale text only as instructions; never output any map graphics."; - - return [ - "Local selected-subject scale edit. Use input image 1 as the clean original photo and the locked camera frame.", - "One-shot cost constraint: produce the requested edit in this generation without relying on later retries or alternate candidates; an unchanged result is not acceptable.", - "中文硬约束:只调整 OLD 框中的主要目标主体,目标可以是人物、模特、小孩、手臂身体、商品或家具。TARGET 框是最终占位;如果是缩小,OLD 框里超出 TARGET 的旧主体占位必须改为自然背景;如果是放大,同一目标主体必须明显变大。禁止整图缩放、整图裁切、整图重绘。", - "一次成功硬约束:不要保守返回原尺寸。目标主体的可见轮廓必须明显从 OLD 原始占位变到 TARGET 占位;不接受看起来和原图几乎相同的结果。", - `Return one seamless realistic photo with the same frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, - coordinateGuideLine, - cropLines ? `${cropLines}` : "", - "", - "Task:", - "Find the main selected target subject inside each OLD box in input image 1. The target can be a person/model/child/body part, furniture, product, or another movable object. Resize and, if needed, move that subject only so its final visible footprint matches the TARGET box shown in input image 2 and the numeric TARGET coordinates below.", - "Do a real subject-scale edit, not a full image zoom. The camera, room layout, windows, wall decor, text, floor, rug, and all non-target subjects must remain stable.", - "If an OLD box contains more than one object/person, choose the dominant target subject inside that box, usually the largest or most central selected item/person. Keep adjacent lamps, plants, side tables, pillows, wall decor, windows, text, background objects, and non-target people at their original size unless they are clearly part of the same target subject.", - "Keep the target identity, person face/anatomy/clothing or product material/structure, perspective, contact shadows, and natural aspect ratio/proportions from input image 1. Do not create a second copy or extra parts. Do not preserve the original target size just because the scene looks realistic; the user explicitly wants a visible scale change.", - "For beds, sofas, tables, chairs, cabinets, benches, people, models, children, hands, and other large visible subjects, still perform the scale edit on that selected subject. Do not treat the selected subject as locked background.", - "If the target is smaller, the selected subject must visibly become smaller and be mostly contained by the TARGET footprint. Rebuild the OLD area outside the TARGET footprint as newly exposed floor, rug, wall, bedding, shadows, or background. If the target is larger, enlarge the same selected subject naturally without stretching it.", - "缩小时请优先让目标主体明显缩小,而不是为了保守而保持原样。不接受原尺寸保留、只轻微变形、或只改变整张图构图。", - "Do not keep the selected subject at its original footprint. The edited subject should fit the TARGET rectangle much better than the OLD rectangle.", - "", - "Region requirements:", - regionLines, - "", - "Success check: compare the final selected-subject footprint with input image 1 and the neutral coordinate map in input image 2. The selected subject size must clearly change from the original and align much closer to TARGET than OLD, while the rest of the photo stays stable.", - "Do not paste rectangular image areas. Do not output coordinate-map lines, labels, boxes, arrows, scale text, muted wash, overlays, seams, hard patch edges, haze, color mismatch, full-canvas zoom, crop, pan, or redesign.", - "Return only the clean edited photo.", - ].join("\n"); -} - -function buildScaleAdjustCoordinateSystemPrompt() { - return [ - "You are an image editing model for local selected-subject scale adjustment.", - "Input image 1 is the only final photo base. Input image 2 is a zoomed neutral coordinate instruction map, not a photo layer.", - "Follow both English and Chinese instructions. The Chinese lines are hard constraints for avoiding an unchanged selected target subject and full-canvas zoom.", - "Generate a clean realistic final photo by editing the selected target subject itself and naturally rebuilding only the tiny surrounding background that becomes visible.", - "The target subject can be a person/model/child/body part, furniture, product, or another movable object. Prefer a clear visible size change over a conservative unchanged result; an unchanged target subject is not acceptable.", - "When shrinking, rebuild the old full-size target-subject footprint outside the target footprint as natural background. Large selected subjects are editable and must not remain locked at original size.", - "Do not paste, composite, clone, crop, resize, or copy rectangular image patches from any input.", - "Never output guide artifacts from the edit map: no faded wash, placeholder shadow, overlay patch, rough crop rectangle, lines, labels, blocks, seams, rectangular borders, arrows, masks, UI marks, or annotations.", - "Keep the camera frame, lighting, wall, floor, rug, windows, background furniture, text, logos, and all non-target regions stable.", - ].join("\n"); -} - -function buildScaleAdjustTextOnlyPrompt( - regions: NormalizedLocalEditRegion[], - scalePercent: ScaleAdjustPercent | null | undefined, - cropReferences: ScaleAdjustCropReference[], sourceSize: { width: number; height: number } ) { - const cropLines = cropReferences - .map( - (reference, index) => - `Input image ${index + 2}: clean crop reference for Region ${reference.regionIndex}; use it only to identify the selected target subject and its natural aspect ratio/proportions, never paste the crop into the output.` - ) - .join("\n"); const regionLines = regions .map((region) => { - const cropIndex = cropReferences.findIndex( - (reference) => reference.regionIndex === region.index - ); const targetRect = getScaleAdjustTargetRect(region, scalePercent); const targetPixelRect = region.targetPixelRect || rectToPixels(targetRect, sourceSize.width, sourceSize.height); - const widthFactor = - region.rect.width > 0 ? targetRect.width / region.rect.width : 1; - const heightFactor = - region.rect.height > 0 ? targetRect.height / region.rect.height : 1; const sourceRight = region.pixelRect.left + region.pixelRect.width; const sourceBottom = region.pixelRect.top + region.pixelRect.height; const targetRight = targetPixelRect.left + targetPixelRect.width; const targetBottom = targetPixelRect.top + targetPixelRect.height; - const cropNote = - cropIndex >= 0 - ? ` Input image ${cropIndex + 2} is the clean crop reference for this target-subject identity and silhouette.` - : ""; - return `Region ${region.index}: hidden coordinate set A current area x0=${region.pixelRect.left}, y0=${region.pixelRect.top}, x1=${sourceRight}, y1=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}; hidden coordinate set B final size/location x0=${targetPixelRect.left}, y0=${targetPixelRect.top}, x1=${targetRight}, y1=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}; final visual scale width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. User request: ${region.prompt || "make the same selected target subject match set B"}.${cropNote}`; - }) - .join("\n"); - - return [ - "Local selected-subject scale edit. Input image 1 is the locked source photo and the only final canvas base.", - `Return one clean realistic photo with exactly the same camera frame and pixel size as input image 1: ${sourceSize.width} x ${sourceSize.height} px.`, - cropLines ? cropLines : "", - "The final photo must contain only natural scene content. Never add artificial graphic overlays, visible coordinate aids, labels, lines, UI elements, or text.", - "Only edit the main selected target subject inside each current pixel area. The target can be a person/model/child/body part, furniture, product, or another object. Keep all other non-target subjects, furniture, sofa, lamps, wall, windows, rug, floor, decor, lighting, and camera frame stable.", - "Use the numeric pixel sets below as hidden instructions only; they are not visual content and must not be drawn.", - "When set B is smaller than set A, make the same selected target subject visibly smaller and naturally rebuild the newly visible floor, rug, wall, shadow, or background around it. Do not leave the old full-size subject silhouette.", - "Keep the target identity, person anatomy/face/clothing or product material/structure, perspective, contact shadows, and natural aspect ratio/proportions. Do not stretch, squash, duplicate, or paste a rectangular crop.", - "中文硬约束:输入图1是锁定底图,只能调整 A 像素范围里的主要目标主体,目标可以是人物、模特、小孩、手臂身体、商品或家具,让它变成 B 像素范围对应的大小和位置。A/B 坐标只是隐藏指令,最终照片里绝对不能画出任何线条、框、文字、标注或 UI 元素。", - "", - "Region instructions:", - regionLines, - "", - "Success check before returning: the selected target subject must be clearly closer to set B than to set A, while the rest of the photo remains visually unchanged and clean.", - ].filter(Boolean).join("\n"); -} - -function toPatchRelativePixelBox( - box: { left: number; top: number; width: number; height: number }, - workspace: ScaleAdjustPatchReference["workspacePixelRect"] -) { - const left = clamp(box.left - workspace.left, 0, Math.max(0, workspace.width - 1)); - const top = clamp(box.top - workspace.top, 0, Math.max(0, workspace.height - 1)); - const right = clamp( - box.left + box.width - workspace.left, - left + 1, - workspace.width - ); - const bottom = clamp( - box.top + box.height - workspace.top, - top + 1, - workspace.height - ); - - return { - left, - top, - width: Math.max(1, right - left), - height: Math.max(1, bottom - top), - }; -} - -function buildScaleAdjustPatchPrompt( - regions: NormalizedLocalEditRegion[], - scalePercent: ScaleAdjustPercent | null | undefined, - patchReference: ScaleAdjustPatchReference, - sourceSize: { width: number; height: number }, - cropReferences: ScaleAdjustCropReference[] = [], - options: { includeSourceReference?: boolean; targetDraftPrimary?: boolean } = {} -) { - const targetDraftPrimary = options.targetDraftPrimary === true; - const includeSourceReference = options.includeSourceReference !== false; - const structureLockedDraft = patchReference.structureLockedDraft === true; - const sourceInputIndex = targetDraftPrimary && includeSourceReference ? 2 : 1; - const draftInputIndex = targetDraftPrimary ? 1 : 2; - const cropReferenceStartIndex = - targetDraftPrimary && !includeSourceReference ? 2 : 3; - const firstInputRole = targetDraftPrimary - ? structureLockedDraft - ? includeSourceReference - ? "Input image 1 is a rough subject-structure-locked target crop. The selected target subject was moved and scaled using source-photo pixels, so its final size, position, silhouette, material/skin/clothing, perspective, and visible structure are the hard target. If the subject is a person, keep the same person identity, face, body proportions, pose, hair, hands, and clothing while cleaning rough edges. If the subject is furniture/product, keep rods, panels, weave, wheels, material, and product structure. Repair rough background holes, edge halos, blur, occlusion, contact shadows, and surface artifacts without redesigning the subject. Input image 2 is only the clean background and non-target reference, never the old size reference." - : "Input image 1 is a rough subject-structure-locked target crop and the only visual reference. The selected target subject was moved and scaled using source-photo pixels, so its final size, position, silhouette, material/skin/clothing, perspective, and visible structure are the hard target. If the subject is a person, keep the same person identity, face, body proportions, pose, hair, hands, and clothing while cleaning rough edges. If the subject is furniture/product, keep rods, panels, weave, wheels, material, and product structure. Repair rough background holes, edge halos, blur, occlusion, contact shadows, and surface artifacts without redesigning the subject." - : includeSourceReference - ? "Input image 1 is the rough edited target-layout crop. It is the hard layout target: the selected subject size and center in the final output must match this draft, but the rough wash, ghosted old footprint, pale wipe, placeholder shadow, blur, and patch artifacts are only edit instructions and must be cleaned. Never reproduce the pale wipe or any rectangular haze as photo content." - : "Input image 1 is the rough edited target-layout crop and the only visual reference. It is the hard layout target: the selected subject size and center in the final output must match this draft. Clean away the rough wash, ghosted old footprint, pale wipe, placeholder shadow, blur, and patch artifacts. Never reproduce the pale wipe or any rectangular haze as photo content." - : "Input image 1 is the exact crop from the original photo and is the locked crop base."; - const secondInputRole = targetDraftPrimary - ? includeSourceReference - ? "Input image 2 is the original clean crop. Use it for stable crop framing, background texture, lighting, perspective, target identity, and non-target person/object preservation. Do not restore the selected subject to its old size from this image." - : "" - : "Input image 2 is a rough target-layout draft of the same crop. It is the hard layout target for the selected subject size and position. Use it to understand the final footprint and newly visible background area, then remove any rough seams, washed areas, placeholder shadows, blur, or patch artifacts from that draft."; - const cropLines = cropReferences - .map( - (reference, index) => - `Input image ${index + cropReferenceStartIndex}: clean identity crop for Region ${reference.regionIndex}; use it only to recognize the target subject shape, identity, anatomy/materials, and natural aspect ratio, not its old size.` - ) - .join("\n"); - const regionLines = regions - .map((region) => { - const cropIndex = cropReferences.findIndex( - (reference) => reference.regionIndex === region.index - ); - const targetRect = getScaleAdjustTargetRect(region, scalePercent); - const targetPixelRect = - region.targetPixelRect || - rectToPixels(targetRect, sourceSize.width, sourceSize.height); - const sourceInPatch = toPatchRelativePixelBox( - region.pixelRect, - patchReference.workspacePixelRect - ); - const targetInPatch = toPatchRelativePixelBox( - targetPixelRect, - patchReference.workspacePixelRect - ); const widthFactor = region.rect.width > 0 ? targetRect.width / region.rect.width : 1; const heightFactor = region.rect.height > 0 ? targetRect.height / region.rect.height : 1; + const moved = + Math.hypot( + targetRect.x + targetRect.width / 2 - (region.rect.x + region.rect.width / 2), + targetRect.y + targetRect.height / 2 - (region.rect.y + region.rect.height / 2) + ) > 0.01; const action = widthFactor < 0.92 || heightFactor < 0.92 - ? "make the same selected subject visibly smaller" + ? "把同一个主体等比缩小" : widthFactor > 1.08 || heightFactor > 1.08 - ? "make the same selected subject visibly larger" - : "move the same selected subject to the final footprint"; - const cropNote = - cropIndex >= 0 - ? ` Input image ${cropIndex + cropReferenceStartIndex} is the clean identity reference for this exact target subject.` - : ""; - return `Region ${region.index}: current search area inside input image ${sourceInputIndex} crop is x=${sourceInPatch.left}, y=${sourceInPatch.top}, w=${sourceInPatch.width}, h=${sourceInPatch.height}; final visual footprint inside input image ${draftInputIndex} / output crop is x=${targetInPatch.left}, y=${targetInPatch.top}, w=${targetInPatch.width}, h=${targetInPatch.height}; requested scale width=${widthFactor.toFixed(2)}, height=${heightFactor.toFixed(2)}. User request: ${region.prompt || action}. Main action: ${action}. Treat the main selected subject inside the search area as the target; it may be a person, model, child, body part, furniture, product, or other object. The final subject must be much closer to the final footprint than to the current search area.${cropNote}`; + ? "把同一个主体等比放大" + : "把同一个主体调整到目标位置和大小"; + return [ + `区域 ${region.index}:`, + `源框 A: left=${region.pixelRect.left}, top=${region.pixelRect.top}, right=${sourceRight}, bottom=${sourceBottom}, width=${region.pixelRect.width}, height=${region.pixelRect.height}.`, + `目标框 B: left=${targetPixelRect.left}, top=${targetPixelRect.top}, right=${targetRight}, bottom=${targetBottom}, width=${targetPixelRect.width}, height=${targetPixelRect.height}.`, + `目标比例约为宽 ${widthFactor.toFixed(2)}x、高 ${heightFactor.toFixed(2)}x。`, + `请识别 A 框内的主要商品/物体/人物主体,只${action},${moved ? "并移动到 B 框中心附近" : "保持在当前位置附近"}。`, + ].join(" "); }) .join("\n"); - const chineseHardConstraint = (() => { - if (!targetDraftPrimary) { - return "中文硬约束:只输出输入图1同一裁切范围的干净局部照片;输入图2是目标大小/位置草稿,必须按它的目标尺寸和目标位置输出,不是要保留旧尺寸。目标家具必须相对原图产生明显比例变化,非目标背景和裁切边缘要稳定自然。"; - } - if (structureLockedDraft) { - return includeSourceReference - ? "中文硬约束:输入图1已经用原图像素把目标主体放到目标尺寸和目标位置,目标主体可以是人物、模特、小孩、手臂身体、商品或家具。人物目标必须按输入图1保留同一身份、脸部、身体比例、姿态、发型、手部和服装;商品/家具目标必须保留产品结构、杆件、面板、编织纹理、轮子、材质和透视。输入图2只能作为干净背景、光影和非目标元素参考,绝对不能把目标主体恢复成输入图2里的旧尺寸。不能重新设计或替换目标主体,只清理草稿边缘、黑斑、破洞、脏点、灰块、皮肤/服装/产品表面伪影。" - : "中文硬约束:输入图1已经用原图像素把目标主体放到目标尺寸和目标位置,目标主体可以是人物、模特、小孩、手臂身体、商品或家具。人物目标必须按输入图1保留同一身份、脸部、身体比例、姿态、发型、手部和服装;商品/家具目标必须保留产品结构、杆件、面板、编织纹理、轮子、材质和透视。不能重新设计或替换目标主体,只清理草稿边缘、黑斑、破洞、脏点、灰块、皮肤/服装/产品表面伪影。"; - } - return includeSourceReference - ? "中文硬约束:输入图1是目标大小/位置草稿,必须按它的目标尺寸和目标位置输出;输入图2只是原始质感、非目标人物和背景参考,绝对不要把目标主体恢复成输入图2里的旧尺寸。草稿里的淡色擦除层/雾块只是提示旧位置需要补背景,不是画面内容,最终不能出现矩形雾块、白块、残影或拼接感。" - : "中文硬约束:输入图1是唯一视觉参考和目标大小/位置草稿,必须按它的目标尺寸和目标位置输出。不要找回旧尺寸目标主体。草稿里的淡色擦除层/雾块只是提示旧位置需要补背景,不是画面内容,最终不能出现矩形雾块、白块、残影或拼接感。"; - })(); return [ - "Local selected-subject scale edit inside a cropped workspace.", - `Return exactly one clean realistic crop with the same framing and aspect as input image 1. The crop represents full-photo pixels left=${patchReference.workspacePixelRect.left}, top=${patchReference.workspacePixelRect.top}, width=${patchReference.workspacePixelRect.width}, height=${patchReference.workspacePixelRect.height}.`, - firstInputRole, - secondInputRole, - cropLines, - "Only edit the selected target subject inside the search area. The target subject can be a person/model/child/body part, furniture, product, or another movable object. Keep the crop borders, wall, window frame, floor, rug, sofa, lamps, decor, lighting, camera perspective, and all non-target subjects stable.", - "If the selected target is a person, scale the whole visible person/body coherently to the final footprint while preserving identity, face, pose, anatomy, hand shape, hair, clothing, and natural human proportions. If a person appears outside the selected target, preserve that non-target person without resizing or redrawing them.", - "When the final footprint is smaller, the selected subject must clearly shrink; erase the old larger subject footprint outside the final footprint and replace it with natural background/floor/rug/wall/shadow that matches the original crop.", - "If input image 1 still shows any faint, transparent, blurred, or ghosted old-size copy of the selected subject outside the final footprint, treat it as an erase marker only. Do not keep it. The only selected target subject that may remain is the smaller clean subject inside the final footprint.", - structureLockedDraft - ? "When the final footprint is larger, the target draft already places the same selected subject at the required larger size. Do not redesign the subject geometry/anatomy; keep the locked person identity/anatomy/clothing or product structure/material/perspective while cleaning background gaps, boundary blending, rough surface artifacts, natural occlusion, and contact shadows." - : "When the final footprint is larger, enlarge the selected subject itself to match the target draft while keeping nearby non-target people and hands natural. If the target is a person, preserve anatomy and identity instead of inventing a new person.", - "Keep the same target identity, perspective, visible details, contact shadows, and natural aspect ratio/proportions. Do not stretch, squash, duplicate, or replace it with a different subject.", - "Hard failure condition: if the selected target subject remains near its original old size, the answer is wrong. The output must visibly change the selected subject footprint to match the target draft footprint.", - structureLockedDraft - ? "Remove every rough draft artifact from input image 1: gray fill patches, beige wash, flat painted areas, jagged mask holes, black speckled stains, dark blotches, rectangular crop edges, and ghost fragments. Human skin, face, hands, hair, and clothing must look continuous and natural when the target is a person. Woven panels, wheels, rods, hooks, and product surfaces must remain continuous and clean when the target is furniture/product." - : "", - "Do not output boxes, lines, labels, coordinate marks, UI marks, text, arrows, overlays, rough layout artifacts, rectangular patch edges, or a full-room image.", - chineseHardConstraint, + "对输入图片做一次简单的图生图局部比例编辑。", + `最终输出保持原图完整画幅和像素尺寸:${sourceSize.width} x ${sourceSize.height} px。`, + "只编辑用户框选的主体本身,保持主体外观、材质、文字、图案、透视和宽高比,不要拉伸或压扁。", + "不要缩放整张图,不要裁剪整张图,不要重绘未选区域。", + "如果主体变小,原位置露出的区域按原图背景自然补齐;白底或纯色背景必须保持干净一致。", + "如果主体变大,让同一个主体自然占据更大的目标范围,并保持边缘、阴影和背景衔接自然。", + "A/B 坐标只是隐藏编辑指令,最终图片里绝不能出现框线、箭头、文字、标注、UI 或半透明色块。", "", - "Region instructions:", + "编辑要求:", regionLines, - "", - "Success check before returning: the selected target subject footprint must be clearly closer to the final footprint than the current search area, and the crop must look like one natural photograph.", - ].filter(Boolean).join("\n"); + ].join("\n"); } export async function POST(request: NextRequest) { @@ -3924,22 +660,9 @@ export async function POST(request: NextRequest) { ); } - const shouldUseScaleAdjustDetailModel = - operation === SCALE_ADJUST_OPERATION && - (hasScaleAdjustTargetRects || scalePercent !== null); - const [pointsConfig, siteSettingsForModel, scaleAdjustModelCandidates] = - await Promise.all([ + const [pointsConfig, siteSettingsForModel] = await Promise.all([ getPointsSystemConfig(), getSiteSettings().catch(() => null), - shouldUseScaleAdjustDetailModel - ? getEnabledAiModelsWithProvider(false, true).catch((error) => { - console.warn( - "[Canvas Local Edit] Failed to load scale adjust model candidates:", - error - ); - return [] as AiModelWithProviderForSelection[]; - }) - : Promise.resolve([] as AiModelWithProviderForSelection[]), ]); const pointsCharge = await prepareFeaturePointsCharge({ userId: session.user.id, @@ -3954,21 +677,101 @@ export async function POST(request: NextRequest) { return NextResponse.json(pointsCharge.payload, { status: pointsCharge.status }); } - const isScaleAdjustOperation = + if ( operation === SCALE_ADJUST_OPERATION && - (hasScaleAdjustTargetRects || scalePercent !== null); - const hasScaleAdjustEnlarge = isScaleAdjustOperation - ? hasScaleAdjustEnlargeTarget(regions, scalePercent) - : false; - const hasScaleAdjustShrink = isScaleAdjustOperation - ? hasScaleAdjustShrinkTarget(regions, scalePercent) - : false; - const preferScaleAdjustMaskCapableModel = - hasScaleAdjustShrink && !hasScaleAdjustEnlarge; - const preferScaleAdjustFalNanoBananaEdit = - hasScaleAdjustShrink && !hasScaleAdjustEnlarge; - const preferScaleAdjustProviderTypes = - hasScaleAdjustShrink && !hasScaleAdjustEnlarge ? ["grsai-gpt-image"] : []; + (hasScaleAdjustTargetRects || scalePercent !== null) + ) { + const displayPrompt = buildLocalEditDisplayPrompt({ operation, scalePercent }); + const resolvedAspectRatio = resolveLocalEditAspectRatio( + body.aspectRatio, + sourceWidth, + sourceHeight + ); + const requestedModel = + typeof body.model === "string" && body.model.trim() + ? body.model.trim() + : undefined; + const configuredDetailModel = + typeof siteSettingsForModel?.canvasDetailDefaultModelId === "string" + ? siteSettingsForModel.canvasDetailDefaultModelId.trim() + : ""; + const resolvedModel = requestedModel || configuredDetailModel; + const requestedImageSize = + typeof body.imageSize === "string" && body.imageSize.trim() + ? body.imageSize.trim() + : "2K"; + const manualRegionReferenceImageUrls = regions.flatMap((region) => + region.referenceImages.map((reference) => reference.url) + ); + const prompt = buildSimpleScaleAdjustPrompt(regions, scalePercent, { + width: sourceWidth, + height: sourceHeight, + }); + const imageRequest: CanvasGenerateImageRequest = { + aspectRatio: resolvedAspectRatio, + billingFeature: "repaint", + debugLabel: "canvas-scale-adjust-simple", + debugMeta: { + displayPrompt, + operation, + requestedModel: requestedModel || null, + resolvedAspectRatio, + resolvedModel: resolvedModel || null, + scaleAdjustPromptStrategy: "simple-image-edit-v1", + scaleAdjustTargetRegionCount: regions.filter((region) => region.targetRect) + .length, + scalePercent, + sourceHeight, + sourceNodeId: body.sourceNodeId || null, + sourceWidth, + }, + displayPrompt, + imageCount: 1, + imageSize: requestedImageSize, + model: resolvedModel || undefined, + negativePrompt: + "不要画框线、箭头、坐标、标注、文字或 UI。不要缩放整张图、裁剪整张图、重绘未选区域。不要拉伸、压扁、复制或替换主体。", + prompt, + promptExtend: false, + referenceImages: [sourceImageUrl, ...manualRegionReferenceImageUrls], + ownerKey: session.user.id, + }; + + const task = await createCanvasImageTask({ + request: imageRequest as unknown as Record, + userId: session.user.id, + }); + await enqueueCanvasImageTask(task.id); + const currentTask = await getCanvasImageTaskForUser({ + taskId: task.id, + userId: session.user.id, + }); + + if (pointsCharge.chargeable) { + try { + await pointsCharge.consume({ + note: `比例调整消耗积分(${task.id})`, + }); + } catch (pointsError) { + console.error("[Points] Failed to consume scale adjust points:", pointsError); + } + } + + return NextResponse.json({ + success: true, + annotatedReferenceUrl: sourceImageUrl, + aspectRatio: resolvedAspectRatio, + displayPrompt, + prompt: displayPrompt, + regions, + sourceHeight, + sourceWidth, + taskId: task.id, + status: currentTask?.status || task.status, + queueStatus: currentTask?.queueStatus, + }); + } + const displayPrompt = buildLocalEditDisplayPrompt({ operation, scalePercent }); const resolvedAspectRatio = resolveLocalEditAspectRatio( body.aspectRatio, @@ -3979,497 +782,66 @@ export async function POST(request: NextRequest) { typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined; - const configuredDetailModel = - typeof siteSettingsForModel?.canvasDetailDefaultModelId === "string" - ? siteSettingsForModel.canvasDetailDefaultModelId.trim() - : ""; - const detailFixedModel = isScaleAdjustOperation - ? resolveScaleAdjustPreferredModelId({ - configuredModelId: configuredDetailModel, - honorRequestedModelBeforeGpt: hasScaleAdjustEnlarge, - preferFalNanoBananaEdit: preferScaleAdjustFalNanoBananaEdit, - preferMaskCapableGpt: preferScaleAdjustMaskCapableModel, - preferProviderTypes: preferScaleAdjustProviderTypes, - requestedModelId: requestedModel || "", - models: scaleAdjustModelCandidates, - }) - : ""; - if ( - isScaleAdjustOperation && - detailFixedModel && - detailFixedModel !== configuredDetailModel - ) { - console.info("[Canvas Local Edit] Override scale adjust model to detail line:", { - configuredDetailModel: configuredDetailModel || null, - requestedModel: requestedModel || null, - resolvedModel: detailFixedModel, - }); - } - const resolvedModel = detailFixedModel || requestedModel; - const resolvedScaleAdjustModelEntry = isScaleAdjustOperation - ? findModelSelectionEntry(scaleAdjustModelCandidates, resolvedModel || "") - : null; - const useScaleAdjustCoordinateGuide = - isScaleAdjustOperation && - isScaleAdjustCoordinateGuideModel(resolvedScaleAdjustModelEntry); - const scaleAdjustModelFamily = getScaleAdjustModelFamily( - resolvedScaleAdjustModelEntry - ); - const useProviderTextOnlyCoordinatePrompt = - isScaleAdjustOperation && - resolvedScaleAdjustModelEntry?.provider?.type === "alibaba-image"; - const useScaleAdjustCoordinatePrompt = useScaleAdjustCoordinateGuide; - const useScaleAdjustFullFrameFalEdit = - isScaleAdjustOperation && - isScaleAdjustFalNanoBananaEditModel(resolvedScaleAdjustModelEntry); - const useFalScaleAdjustCoordinatePrompt = - useScaleAdjustCoordinatePrompt && - resolvedScaleAdjustModelEntry?.provider?.type === "fal-image" && - getScaleAdjustModelFamily(resolvedScaleAdjustModelEntry) === "nano-banana-2"; - const useScaleAdjustVisualLayoutGuide = - useScaleAdjustCoordinatePrompt && - !useFalScaleAdjustCoordinatePrompt && - !useProviderTextOnlyCoordinatePrompt; - const useScaleAdjustMarkedPhotoGuide = - useScaleAdjustCoordinatePrompt && !useScaleAdjustVisualLayoutGuide; - const useScaleAdjustStructureLockedPatchWorkflow = - isScaleAdjustOperation && - !useScaleAdjustFullFrameFalEdit && - hasScaleAdjustStructureTarget(regions, scalePercent) && - (!preferScaleAdjustMaskCapableModel || - !isScaleAdjustMaskCapableModel(resolvedScaleAdjustModelEntry)); - const useScaleAdjustEditMask = - isScaleAdjustOperation && - !useScaleAdjustStructureLockedPatchWorkflow && - isScaleAdjustMaskCapableModel(resolvedScaleAdjustModelEntry); - const useScaleAdjustPatchWorkflow = - isScaleAdjustOperation && - !useScaleAdjustFullFrameFalEdit && - (useScaleAdjustStructureLockedPatchWorkflow || !useScaleAdjustEditMask); - const sendScaleAdjustAnnotatedReferenceToModel = - isScaleAdjustOperation && - !useScaleAdjustPatchWorkflow && - !useProviderTextOnlyCoordinatePrompt; - const annotatedBuffer = isScaleAdjustOperation - ? useScaleAdjustCoordinatePrompt - ? useScaleAdjustVisualLayoutGuide - ? await buildScaleAdjustVisualLayoutGuideBuffer({ - regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceWidth, - }) - : useScaleAdjustMarkedPhotoGuide - ? await buildScaleAdjustMarkedPhotoGuideBuffer({ - height: sourceHeight, - regions, - scalePercent, - sourceBuffer, - width: sourceWidth, - }) - : await sharp( - buildScaleAdjustZoomedCoordinateSvg({ - height: sourceHeight, - regions, - scalePercent, - width: sourceWidth, - }), - { failOn: "none" } - ) - .png({ compressionLevel: 6 }) - .toBuffer() - : await buildScaleAdjustVisualLayoutGuideBuffer({ + const annotatedBuffer = await sharp(sourceBuffer, { failOn: "none" }) + .composite([ + { + input: buildAnnotationSvg({ + height: sourceHeight, + hidePromptText: false, regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceWidth, - }) - : await sharp(sourceBuffer, { failOn: "none" }) - .composite([ - { - input: buildAnnotationSvg({ - height: sourceHeight, - hidePromptText: false, - regions, - width: sourceWidth, - }), - left: 0, - top: 0, - }, - ]) - .png({ compressionLevel: 6 }) - .toBuffer(); - const annotatedFilename = `${isScaleAdjustOperation ? "canvas-scale-adjust-layout-guide" : "canvas-local-edit"}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`; + width: sourceWidth, + }), + left: 0, + top: 0, + }, + ]) + .png({ compressionLevel: 6 }) + .toBuffer(); + const annotatedFilename = `canvas-local-edit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`; const annotatedUpload = await uploadFile( annotatedFilename, toArrayBuffer(annotatedBuffer) ); - const scaleAdjustEditMaskUpload = useScaleAdjustEditMask - ? await uploadFile( - `canvas-scale-adjust-edit-mask-${Date.now()}-${Math.random() - .toString(36) - .slice(2, 8)}.png`, - toArrayBuffer( - await buildScaleAdjustEditMaskBuffer({ - regions, - scalePercent, - sourceHeight, - sourceWidth, - }) - ) - ) - : null; - const scaleAdjustPatchReference = useScaleAdjustPatchWorkflow - ? await createScaleAdjustPatchReference({ - regions, - scalePercent, - sourceBuffer, - sourceHeight, - sourceImageUrl, - sourceWidth, - userId: session.user.id, - }) - : null; - const shouldCreateScaleAdjustCropReferences = - isScaleAdjustOperation && - (!scaleAdjustPatchReference && - (useScaleAdjustVisualLayoutGuide || - !useScaleAdjustCoordinatePrompt || - useProviderTextOnlyCoordinatePrompt || - (useScaleAdjustMarkedPhotoGuide && !useFalScaleAdjustCoordinatePrompt))); - const scaleAdjustCropReferences: ScaleAdjustCropReference[] = - shouldCreateScaleAdjustCropReferences - ? await createScaleAdjustCropReferences({ - regions, - sourceBuffer, - sourceHeight, - sourceWidth, - }) - : []; - const useScaleAdjustPatchTargetDraftPrimary = Boolean(scaleAdjustPatchReference); - const includeScaleAdjustPatchSourceReference = - Boolean(scaleAdjustPatchReference); - const prompt = isScaleAdjustOperation - ? scaleAdjustPatchReference - ? buildScaleAdjustPatchPrompt( - regions, - scalePercent, - scaleAdjustPatchReference, - { width: sourceWidth, height: sourceHeight }, - scaleAdjustCropReferences, - { - includeSourceReference: includeScaleAdjustPatchSourceReference, - targetDraftPrimary: useScaleAdjustPatchTargetDraftPrimary, - } - ) - : useProviderTextOnlyCoordinatePrompt - ? buildScaleAdjustTextOnlyPrompt( - regions, - scalePercent, - scaleAdjustCropReferences, - { width: sourceWidth, height: sourceHeight } - ) - : useScaleAdjustCoordinatePrompt - ? buildScaleAdjustCoordinatePrompt( - regions, - scalePercent, - { - width: sourceWidth, - height: sourceHeight, - }, - scaleAdjustCropReferences, - { - falSafe: useFalScaleAdjustCoordinatePrompt, - markedPhotoGuide: useScaleAdjustMarkedPhotoGuide, - visualLayoutGuide: useScaleAdjustVisualLayoutGuide, - } - ) - : buildScaleAdjustPrompt( - regions, - scalePercent, - scaleAdjustCropReferences, - { width: sourceWidth, height: sourceHeight } - ) - : buildLocalEditPrompt(regions); - const scaleAdjustCoordinateNegativePrompt = useFalScaleAdjustCoordinatePrompt - ? "guide marks, labels, boxes, arrows, overlays, patch edges, color mismatch, full-frame zoom, unchanged target subject, duplicate subject, duplicate furniture, duplicate person, stretched furniture, distorted furniture, deformed person, changed face, extra limbs" - : "visible annotation, guide overlay, translucent overlay, target placement overlay, faded wash, placeholder shadow, text label, arrows, boxes, rectangle border, UI marks, pasted patch, rough layout patch, hard crop edge, seam, hard rectangular edge, color mismatch, different-resolution area, whole image zoom, whole image crop, whole image pan, whole image redesign, unchanged target subject, old-size target subject, unchanged target person, old-size target person, unchanged target furniture, old-size target furniture, stretched subject, squashed subject, distorted subject, stretched furniture, squashed furniture, duplicate subject, duplicate person, duplicate furniture, second copy, changed face, deformed person, broken anatomy, extra limbs, extra fingers, extra legs, extra rails, side panels, shelves, cabinets, lattice panels"; - const scaleAdjustTextOnlyNegativePrompt = - "artificial graphic overlay, visible coordinate aid, visible line, visible label, UI element, annotation text, full image redesign, full-frame zoom, crop, pan, pasted crop, hard patch edge, color mismatch, changed sofa, changed lamp, changed wall, changed rug, duplicate subject, duplicate person, duplicate furniture, changed face, deformed person, extra limbs, stretched subject, stretched furniture, distorted furniture"; - const scaleAdjustPatchNegativePrompt = - "full room image, changed crop border, artificial graphic overlay, visible coordinate aid, visible line, visible label, UI element, annotation text, guide mark, pasted crop, hard patch edge, rectangular haze, white haze block, pale wipe block, color mismatch, gray draft patch, beige wash patch, flat painted area, jagged mask hole, black speckled stain, dark blotch, duplicate subject, duplicate person, duplicate furniture, unchanged target subject, unchanged target person, unchanged target furniture, old-size target subject, changed target identity, changed face, deformed person, broken anatomy, extra limbs, extra fingers, changed locked product, redrawn product interior, different furniture, broken woven panel, dirty woven panel, wheel inside woven panel, stretched subject, stretched furniture, distorted furniture"; + const prompt = buildLocalEditPrompt(regions); const manualRegionReferenceImageUrls = regions.flatMap((region) => region.referenceImages.map((reference) => reference.url) ); - const scaleAdjustCropReferenceImageUrls = scaleAdjustCropReferences.map( - (reference) => reference.url - ); - const referenceImages = isScaleAdjustOperation - ? scaleAdjustPatchReference - ? useScaleAdjustPatchTargetDraftPrimary - ? [ - scaleAdjustPatchReference.targetDraftUrl, - ...(includeScaleAdjustPatchSourceReference - ? [scaleAdjustPatchReference.sourceCropUrl] - : []), - ...scaleAdjustCropReferenceImageUrls, - ...manualRegionReferenceImageUrls, - ] - : [ - scaleAdjustPatchReference.sourceCropUrl, - scaleAdjustPatchReference.targetDraftUrl, - ...scaleAdjustCropReferenceImageUrls, - ...manualRegionReferenceImageUrls, - ] - : [ - sourceImageUrl, - ...(sendScaleAdjustAnnotatedReferenceToModel - ? [annotatedUpload.url] - : []), - ...scaleAdjustCropReferenceImageUrls, - ...manualRegionReferenceImageUrls, - ] - : [sourceImageUrl, ...manualRegionReferenceImageUrls]; - const scaleAdjustCompositeRegions = isScaleAdjustOperation - ? buildScaleAdjustCompositeRegions(regions, scalePercent) - : []; - const scaleAdjustPatchCompositeRegions = isScaleAdjustOperation - ? buildScaleAdjustPatchCompositeRegions(regions, scalePercent) - : []; - const scaleAdjustProtectedChangeRegions = - isScaleAdjustOperation && scaleAdjustPatchReference - ? buildScaleAdjustProtectedChangeRegions(regions, scalePercent) - : []; - const scaleAdjustProtectedRegions = - isScaleAdjustOperation && scaleAdjustPatchReference - ? scaleAdjustPatchReference.structureLockedDraft - ? [scaleAdjustPatchReference.workspaceRect] - : scaleAdjustProtectedChangeRegions - : scaleAdjustCompositeRegions; - const scaleAdjustVerificationConfig = isScaleAdjustOperation - ? { - allowOutsideChangedWhenChangedInside: false, - allowDeterministicFallback: false, - protectedRegions: scaleAdjustProtectedRegions, - rejectFailedCandidates: true, - sourceImageUrl, - regions: regions.map((region) => region.rect), - regionPrompts: regions.map((region) => region.prompt), - ...(typeof scalePercent === "number" - ? { scalePercent: scalePercent as ScaleAdjustPercent } - : {}), - ...(hasScaleAdjustTargetRects - ? { - targetRegions: regions - .map((region) => region.targetRect) - .filter( - ( - rect - ): rect is NonNullable => - Boolean(rect) - ), - } - : {}), - } - : undefined; + const referenceImages = [sourceImageUrl, ...manualRegionReferenceImageUrls]; const requestedImageSize = typeof body.imageSize === "string" && body.imageSize.trim() ? body.imageSize.trim() : "2K"; - const resolvedRequestImageSize = - scaleAdjustPatchReference?.structureLockedDraft === true - ? requestedImageSize - : scaleAdjustPatchReference - ? "1K" - : requestedImageSize; const imageRequest: CanvasGenerateImageRequest = { - allowFailover: isScaleAdjustOperation ? false : undefined, - aspectRatio: scaleAdjustPatchReference - ? inferScaleAdjustPatchAspectRatio( - scaleAdjustPatchReference.workspacePixelRect.width, - scaleAdjustPatchReference.workspacePixelRect.height - ) - : resolvedAspectRatio, + aspectRatio: resolvedAspectRatio, billingFeature: "repaint", - debugLabel: - operation === SCALE_ADJUST_OPERATION ? "canvas-scale-adjust" : "canvas-local-edit", + debugLabel: "canvas-local-edit", debugMeta: { annotatedReferenceUrl: annotatedUpload.url, - annotatedReferenceSentToModel: sendScaleAdjustAnnotatedReferenceToModel, - annotatedReferenceType: isScaleAdjustOperation - ? useProviderTextOnlyCoordinatePrompt - ? "scale-adjust-text-coordinate-only-debug-map" - : useScaleAdjustCoordinatePrompt - ? useScaleAdjustVisualLayoutGuide - ? "scale-adjust-visual-layout-guide" - : useScaleAdjustMarkedPhotoGuide - ? "scale-adjust-marked-photo-guide" - : "scale-adjust-neutral-coordinate-map" - : "scale-adjust-full-frame-semantic-edit-map" - : "source-overlay", - scaleAdjustEditMaskApplied: Boolean(scaleAdjustEditMaskUpload), - scaleAdjustEditMaskUrl: scaleAdjustEditMaskUpload?.url || null, - scaleAdjustEditMaskProviderType: - useScaleAdjustEditMask - ? resolvedScaleAdjustModelEntry?.provider?.type || null - : null, - cleanSourceReferenceIndex: - scaleAdjustPatchReference && - useScaleAdjustPatchTargetDraftPrimary && - !includeScaleAdjustPatchSourceReference - ? null - : scaleAdjustPatchReference && useScaleAdjustPatchTargetDraftPrimary - ? 2 - : 1, - configuredDetailModelId: configuredDetailModel || null, - detailFixedModelApplied: Boolean(detailFixedModel), - detailFixedModelId: detailFixedModel || null, + annotatedReferenceType: "source-overlay", displayPrompt, operation, requestedModel: requestedModel || null, resolvedAspectRatio, - scaleAdjustPatchWorkflowApplied: Boolean(scaleAdjustPatchReference), - scaleAdjustPatchStructureLockedDraftApplied: - scaleAdjustPatchReference?.structureLockedDraft === true, - scaleAdjustFullFrameFalEditApplied: useScaleAdjustFullFrameFalEdit, - scaleAdjustPatchReferenceOrder: - scaleAdjustPatchReference && useScaleAdjustPatchTargetDraftPrimary - ? includeScaleAdjustPatchSourceReference - ? "target-draft-source-identity" - : "target-draft-identity" - : scaleAdjustPatchReference - ? "source-target-draft-identity" - : null, - scaleAdjustPatchSourceCropUrl: - scaleAdjustPatchReference?.sourceCropUrl || null, - scaleAdjustPatchTargetDraftUrl: - scaleAdjustPatchReference?.targetDraftUrl || null, - scaleAdjustPatchWorkspacePixelRect: - scaleAdjustPatchReference?.workspacePixelRect || null, - scaleAdjustPatchWorkspaceRect: - scaleAdjustPatchReference?.workspaceRect || null, - resolvedModel: resolvedModel || null, - resolvedScaleAdjustProviderType: - resolvedScaleAdjustModelEntry?.provider?.type || null, - scaleAdjustModelFamily: scaleAdjustModelFamily || null, - scaleAdjustCoordinateGuideApplied: useScaleAdjustCoordinateGuide, - scaleAdjustCoordinatePromptApplied: - useScaleAdjustCoordinatePrompt || useProviderTextOnlyCoordinatePrompt, - scaleAdjustTextOnlyCoordinatePromptApplied: - useProviderTextOnlyCoordinatePrompt, - scaleAdjustNeutralCoordinateMapApplied: - isScaleAdjustOperation && - useScaleAdjustCoordinatePrompt && - !useScaleAdjustMarkedPhotoGuide && - !useScaleAdjustVisualLayoutGuide, - scaleAdjustMarkedPhotoGuideApplied: useScaleAdjustMarkedPhotoGuide, - scaleAdjustFalMarkedPhotoGuideApplied: useFalScaleAdjustCoordinatePrompt, - scaleAdjustVisualLayoutGuideApplied: - isScaleAdjustOperation && - !useProviderTextOnlyCoordinatePrompt && - (!useScaleAdjustCoordinatePrompt || useScaleAdjustVisualLayoutGuide), - falScaleAdjustCoordinateGuideApplied: - useScaleAdjustCoordinateGuide && - resolvedScaleAdjustModelEntry?.provider?.type === "fal-image", - falScaleAdjustSafePromptApplied: useFalScaleAdjustCoordinatePrompt, - scaleAdjustProviderFallbackPolicy: isScaleAdjustOperation - ? "disabled-one-shot-single-model" - : undefined, - scaleAdjustQualityFailoverPolicy: isScaleAdjustOperation - ? "disabled-reject-unchanged-ai-candidate" - : undefined, - scaleAdjustPreferSameNameProviderFailover: - false, - scaleAdjustStrictSameFamilyFailover: - false, manualRegionReferenceImageCount: manualRegionReferenceImageUrls.length, - regionReferenceImageCount: - referenceImages.length, + regionReferenceImageCount: referenceImages.length, regionCount: regions.length, - scalePercent, - scaleAdjustCropReferenceCount: scaleAdjustCropReferenceImageUrls.length, - scaleAdjustProtectionMode: hasScaleAdjustTargetRects - ? "target-rect" - : "scale-percent", - scaleAdjustTargetRegionCount: regions.filter((region) => region.targetRect) - .length, - scaleAdjustPromptStrategy: isScaleAdjustOperation - ? scaleAdjustPatchReference - ? scaleAdjustPatchReference.structureLockedDraft - ? "ai-patch-workspace-structure-locked-draft-v85-one-shot" - : "ai-patch-workspace-draft-v75-soft-wipe-erase-ghost-one-shot" - : useScaleAdjustEditMask - ? "mask-edit-gpt-image-2-scale-shrink-v74-one-shot" - : useFalScaleAdjustCoordinatePrompt - ? "fal-safe-marked-photo-box-guide-no-old-crop-v44-one-shot" - : useScaleAdjustVisualLayoutGuide - ? "same-name-focused-layout-crop-guide-v54-one-shot" - : useProviderTextOnlyCoordinatePrompt - ? "provider-text-coordinate-crop-v61-one-shot" - : useScaleAdjustMarkedPhotoGuide - ? "same-name-marked-photo-box-guide-no-old-crop-v45-one-shot" - : "locked-plate-semantic-target-map-no-old-crop-v15" - : undefined, - scaleAdjustPostCompositeApplied: Boolean(scaleAdjustPatchReference), - scaleAdjustUsesFullFrameOutput: - isScaleAdjustOperation && !scaleAdjustPatchReference, sourceHeight, sourceNodeId: body.sourceNodeId || null, sourceWidth, }, displayPrompt, - falSafetyTolerance: useScaleAdjustCoordinateGuide ? "6" : undefined, - falSystemPrompt: - useScaleAdjustCoordinatePrompt - ? buildScaleAdjustCoordinateSystemPrompt() - : undefined, - falThinkingLevel: useScaleAdjustCoordinateGuide ? "high" : undefined, imageCount: 1, - imageSize: resolvedRequestImageSize, - model: resolvedModel || undefined, + imageSize: requestedImageSize, + model: requestedModel || undefined, negativePrompt: - isScaleAdjustOperation - ? scaleAdjustPatchReference - ? scaleAdjustPatchNegativePrompt - : useProviderTextOnlyCoordinatePrompt - ? scaleAdjustTextOnlyNegativePrompt - : useScaleAdjustCoordinatePrompt - ? scaleAdjustCoordinateNegativePrompt - : "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、箭头、连线、角点、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、蓝色色块、色条、灰底坐标图、目标占位叠图、淡化痕迹、选区边框、白边、画幅压扁、画面拉伸、整张图缩放、全图放大、全图裁切、全图平移、文字位置变化、文字内容变化、文字模糊、Logo位置变化、主体拉伸、主体压扁、主体变窄、主体变高但变窄、横向挤压、纵向拉伸、透视变形、矩形贴片、硬边、拼接线、补丁感、局部裁切、色差边缘、背景断裂、背景错位、窗框错位、文字错位、地毯纹理错位、非主体背景重绘、主体未缩放、整块框选区域缩放" - : "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、选区边框、白边、画幅压扁、画面拉伸、主体截断、动物截断、缺头、缺尾巴、缺四肢、贴边裁切、矩形贴片、硬边、拼接线、补丁感、色差边缘、背景错位、地面纹理断裂、椅脚错位", + "彩色框、蓝色边框、绿色边框、红色边框、橙色边框、矩形框、编号圆点、提示词气泡、标注文字、UI 控件、半透明色块、选区边框、白边、画幅压扁、画面拉伸、主体截断、贴边裁切、矩形贴片、硬边、拼接线、补丁感、色差边缘、背景错位、地面纹理断裂、椅脚错位", prompt, promptExtend: false, - providerImageParams: scaleAdjustEditMaskUpload - ? { maskImageUrl: scaleAdjustEditMaskUpload.url } - : undefined, referenceImages, - scaleAdjustPatchComposite: scaleAdjustPatchReference - ? { - diffCompareBlurPx: 0.8, - diffHighThreshold: 42, - diffLowThreshold: 14, - featherMaxPx: 42, - featherMinPx: 10, - featherRatio: 0.018, - maskMode: scaleAdjustPatchReference.structureLockedDraft - ? "workspace" - : "diff", - regions: scaleAdjustPatchReference.structureLockedDraft - ? undefined - : scaleAdjustPatchCompositeRegions, - sourceImageUrl, - workspaceRegion: scaleAdjustPatchReference.workspaceRect, - } - : undefined, - scaleAdjustVerification: scaleAdjustVerificationConfig, - localEditComposite: isScaleAdjustOperation - ? undefined - : { - sourceImageUrl, - regions: regions.map((region) => region.rect), - }, + localEditComposite: { + sourceImageUrl, + regions: regions.map((region) => region.rect), + }, ownerKey: session.user.id, }; From adbbe4442a624641dbbd34c9d9f02dfe1e4fa1cb Mon Sep 17 00:00:00 2001 From: 134 Date: Thu, 9 Jul 2026 15:42:33 +0800 Subject: [PATCH 28/29] Use canvas default for scale adjust model fallback --- app/api/canvas/local-edit/route.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/app/api/canvas/local-edit/route.ts b/app/api/canvas/local-edit/route.ts index ea8771892..0cf8f6f9d 100644 --- a/app/api/canvas/local-edit/route.ts +++ b/app/api/canvas/local-edit/route.ts @@ -695,7 +695,19 @@ export async function POST(request: NextRequest) { typeof siteSettingsForModel?.canvasDetailDefaultModelId === "string" ? siteSettingsForModel.canvasDetailDefaultModelId.trim() : ""; - const resolvedModel = requestedModel || configuredDetailModel; + const configuredCanvasModel = + typeof siteSettingsForModel?.canvasDefaultModelId === "string" + ? siteSettingsForModel.canvasDefaultModelId.trim() + : ""; + const configuredAutoCanvasModel = + typeof siteSettingsForModel?.canvasAutoModeDefaultModelId === "string" + ? siteSettingsForModel.canvasAutoModeDefaultModelId.trim() + : ""; + const resolvedModel = + requestedModel || + configuredDetailModel || + configuredCanvasModel || + configuredAutoCanvasModel; const requestedImageSize = typeof body.imageSize === "string" && body.imageSize.trim() ? body.imageSize.trim() From 3252cbd2c829a745f942aa1d3553a2ed1e800885 Mon Sep 17 00:00:00 2001 From: 134 Date: Fri, 10 Jul 2026 12:57:01 +0800 Subject: [PATCH 29/29] feat: refine canvas workflows and unify application UI --- .../_components/access-security-dashboard.tsx | 698 + .../_components/admin-settings-navigation.tsx | 56 +- .../_components/local-ai-command-center.tsx | 42 +- .../_components/local-ai-section-shell.tsx | 24 +- .../local-ai-sections/planning-sections.tsx | 20 +- .../_components/setting-status-badge.tsx | 2 +- .../settings/_lib/settings-navigation.ts | 7 + .../settings/admin-settings-client.tsx | 131 +- .../agent-workflow-settings-client.tsx | 27 +- .../psd-templates-settings-client.tsx | 25 +- .../style-pro/style-pro-settings-client.tsx | 14 +- .../video-canvas-settings-client.tsx | 180 +- app/(auth)/auth.ts | 32 +- app/(chat)/api/files/direct-upload/route.ts | 18 +- app/(chat)/api/models/route.ts | 72 + app/api/admin/access-blocklist/route.ts | 207 + app/api/admin/access-logs/route.ts | 271 + app/api/admin/settings/route.ts | 24 +- app/api/canvas/[id]/route.ts | 63 +- app/api/canvas/workflow/analyze/route.ts | 456 +- app/api/favicon/route.ts | 9 + app/api/internal/access-log/route.ts | 147 + app/api/internal/ip-blocklist/check/route.ts | 140 + app/api/pick-object/route.ts | 119 +- app/api/site-settings/route.ts | 30 + app/api/user/membership-summary/route.ts | 30 +- app/api/video-canvas/config/route.ts | 4 + .../[id]/CanvasEditorLegacyPageClient.tsx | 31 +- app/canvas/[id]/CanvasPageClientRouter.tsx | 2 +- app/canvas/[id]/page.tsx | 11 +- app/globals.css | 136 + components/canvas/CanvasChatPanel.tsx | 132 +- .../canvas/LiblibVideoCanvasReplica.tsx | 14161 +++++++++++++++- components/elements/actions.tsx | 2 +- components/elements/conversation.tsx | 2 +- components/elements/message.tsx | 4 +- components/elements/prompt-input.tsx | 4 +- components/elements/response.tsx | 12 +- components/elements/suggestion.tsx | 2 +- components/home/home-animation-embed.tsx | 36 +- components/home/lovart-home.tsx | 100 +- .../home/lovart/lovart-featured-gallery.tsx | 10 +- .../home/lovart/lovart-hero-composer.tsx | 69 +- .../home/lovart/lovart-projects-section.tsx | 26 +- components/home/lovart/lovart-sidebar.tsx | 32 +- components/layout/brand-top-bar.tsx | 12 +- components/ui/button.tsx | 10 +- components/ui/card.tsx | 12 +- components/ui/dialog.tsx | 14 +- components/ui/input.tsx | 2 +- components/ui/label.tsx | 1 + components/ui/popover.tsx | 2 +- components/ui/select.tsx | 10 +- components/ui/sheet.tsx | 12 +- components/ui/tabs.tsx | 5 +- components/ui/textarea.tsx | 2 +- components/ui/tooltip.tsx | 2 +- docs/Claw模式技能使用宣导.md | 221 + docs/Claw模式技能使用宣导.txt | 197 + docs/Claw模式技能使用宣导2.pdf | Bin 0 -> 191290 bytes docs/video-canvas-competitor-audit.md | 364 + lib/ai/detail-agent-kimi-profile.ts | 11 +- lib/ai/detail-agent-model-config.ts | 55 +- lib/ai/providers/fal-image.ts | 9 + lib/ai/qwen3-vl.ts | 11 +- lib/ai/tools/generate-video.ts | 218 +- lib/client/upload-with-retry.ts | 2 +- .../migrations/0087_add_access_ip_events.sql | 35 + .../0088_add_access_ip_blocklist.sql | 20 + lib/db/migrations/meta/_journal.json | 14 + lib/db/queries.ts | 12 +- lib/db/schema.ts | 37 + lib/security/access-log.ts | 200 + lib/security/manual-ip-blocklist.ts | 88 + lib/storage/service.ts | 3 +- lib/video-canvas/config.ts | 207 + proxy.ts | 501 +- public/video-canvas/effects/bee-camera.webp | Bin 0 -> 3050362 bytes public/video-canvas/effects/cloud-dive.webp | Bin 0 -> 2110984 bytes public/video-canvas/effects/earth-dive.webp | Bin 0 -> 1934196 bytes public/video-canvas/effects/earth-zoom.webp | Bin 0 -> 1315378 bytes public/video-canvas/effects/global-zoom.webp | Bin 0 -> 1926700 bytes .../video-canvas/effects/horizon-flight.webp | Bin 0 -> 1784842 bytes public/video-canvas/effects/iris-push.webp | Bin 0 -> 1652144 bytes public/video-canvas/effects/multi-angle.webp | Bin 0 -> 1754590 bytes public/video-canvas/effects/prada-change.webp | Bin 0 -> 1407378 bytes .../effects/product-light-sweep.webp | Bin 0 -> 1020162 bytes .../video-canvas/effects/reverse-gravity.webp | Bin 0 -> 2052752 bytes .../video-canvas/effects/underwater-slow.webp | Bin 0 -> 1872114 bytes .../storage/configure-direct-upload-cors.ts | 147 +- .../storage/configure-multipart-lifecycle.ts | 181 +- services/canvas/index.ts | 12 + 92 files changed, 18716 insertions(+), 1533 deletions(-) create mode 100644 app/(admin)/settings/_components/access-security-dashboard.tsx create mode 100644 app/api/admin/access-blocklist/route.ts create mode 100644 app/api/admin/access-logs/route.ts create mode 100644 app/api/internal/access-log/route.ts create mode 100644 app/api/internal/ip-blocklist/check/route.ts create mode 100644 docs/Claw模式技能使用宣导.md create mode 100644 docs/Claw模式技能使用宣导.txt create mode 100644 docs/Claw模式技能使用宣导2.pdf create mode 100644 docs/video-canvas-competitor-audit.md create mode 100644 lib/db/migrations/0087_add_access_ip_events.sql create mode 100644 lib/db/migrations/0088_add_access_ip_blocklist.sql create mode 100644 lib/security/access-log.ts create mode 100644 lib/security/manual-ip-blocklist.ts create mode 100644 public/video-canvas/effects/bee-camera.webp create mode 100644 public/video-canvas/effects/cloud-dive.webp create mode 100644 public/video-canvas/effects/earth-dive.webp create mode 100644 public/video-canvas/effects/earth-zoom.webp create mode 100644 public/video-canvas/effects/global-zoom.webp create mode 100644 public/video-canvas/effects/horizon-flight.webp create mode 100644 public/video-canvas/effects/iris-push.webp create mode 100644 public/video-canvas/effects/multi-angle.webp create mode 100644 public/video-canvas/effects/prada-change.webp create mode 100644 public/video-canvas/effects/product-light-sweep.webp create mode 100644 public/video-canvas/effects/reverse-gravity.webp create mode 100644 public/video-canvas/effects/underwater-slow.webp diff --git a/app/(admin)/settings/_components/access-security-dashboard.tsx b/app/(admin)/settings/_components/access-security-dashboard.tsx new file mode 100644 index 000000000..2662cfeb7 --- /dev/null +++ b/app/(admin)/settings/_components/access-security-dashboard.tsx @@ -0,0 +1,698 @@ +"use client"; + +import { + Activity, + AlertTriangle, + Ban, + Clock3, + Globe2, + LogIn, + Plus, + RefreshCw, + Search, + ShieldAlert, + Unlock, + UserCheck, +} from "lucide-react"; +import { useMemo, useState } from "react"; +import { toast } from "sonner"; +import useSWR from "swr"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { cn, fetcher } from "@/lib/utils"; + +type Severity = "info" | "watch" | "high" | "critical"; + +type AccessLogEvent = { + id: string; + eventType: string; + ip: string; + userEmail: string | null; + userRole: string | null; + method: string | null; + path: string | null; + routeGroup: string | null; + statusCode: number | null; + outcome: string; + severity: Severity; + reasons: string[] | null; + userAgent: string | null; + createdAt: string; +}; + +type AccessLogTopIp = { + ip: string; + total: number; + uniqueUsers: number; + failureCount: number; + rateLimitedCount: number; + authFailureCount: number; + loginSuccessCount: number; + suspiciousCount: number; + firstSeen: string; + lastSeen: string; + severity: Severity; + failureRate: number; + reasons: string[]; +}; + +type AccessLogResponse = { + overview: { + totalEvents: number; + uniqueIps: number; + abnormalEvents: number; + abnormalIps: number; + rateLimitedEvents: number; + manualBlockedEvents: number; + loginSuccessEvents: number; + unauthorizedEvents: number; + }; + topIps: AccessLogTopIp[]; + hourlyStats: Array<{ + hour: string; + count: number; + abnormalCount: number; + }>; + pathStats: Array<{ + path: string | null; + routeGroup: string | null; + count: number; + abnormalCount: number; + }>; + recentEvents: AccessLogEvent[]; + rules: string[]; +}; + +type AccessBlocklistEntry = { + id: string; + ip: string; + reason: string | null; + isActive: boolean; + expiresAt: string | null; + createdAt: string; + updatedAt: string; + createdByEmail: string | null; +}; + +const severityLabels: Record = { + info: "正常", + watch: "关注", + high: "异常", + critical: "高危", +}; + +const severityClassNames: Record = { + info: "border-emerald-200 bg-emerald-50 text-emerald-700", + watch: "border-amber-200 bg-amber-50 text-amber-700", + high: "border-orange-200 bg-orange-50 text-orange-700", + critical: "border-red-200 bg-red-50 text-red-700", +}; + +function formatNumber(value: number | null | undefined) { + return new Intl.NumberFormat("zh-CN").format(Number(value || 0)); +} + +function formatPercent(value: number | null | undefined) { + return `${Math.round(Number(value || 0) * 100)}%`; +} + +function formatTime(value: string | null | undefined) { + if (!value) return "--"; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return "--"; + return new Intl.DateTimeFormat("zh-CN", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }).format(date); +} + +function getStatusClassName(statusCode: number | null) { + if (!statusCode) return "text-muted-foreground"; + if (statusCode >= 500) return "text-red-700"; + if (statusCode >= 400) return "text-orange-700"; + if (statusCode >= 300) return "text-sky-700"; + return "text-emerald-700"; +} + +function AccessSeverityBadge({ severity }: { severity: Severity }) { + return ( + + {severityLabels[severity]} + + ); +} + +export function AccessSecurityDashboard() { + const [hours, setHours] = useState("24"); + const [severity, setSeverity] = useState("all"); + const [query, setQuery] = useState(""); + const [blockIp, setBlockIp] = useState(""); + const [blockReason, setBlockReason] = useState(""); + const [isSavingBlock, setIsSavingBlock] = useState(false); + + const accessLogUrl = useMemo(() => { + const params = new URLSearchParams({ + hours, + severity, + limit: "160", + }); + if (query.trim()) params.set("q", query.trim()); + return `/api/admin/access-logs?${params.toString()}`; + }, [hours, query, severity]); + + const { data, isLoading, mutate } = useSWR( + accessLogUrl, + fetcher, + { refreshInterval: 30_000 } + ); + const { data: blocklistData, mutate: mutateBlocklist } = useSWR<{ + entries: AccessBlocklistEntry[]; + }>("/api/admin/access-blocklist", fetcher); + + const activeBlocklistEntries = useMemo( + () => (blocklistData?.entries || []).filter((entry) => entry.isActive), + [blocklistData?.entries] + ); + const blockedRules = useMemo( + () => new Set(activeBlocklistEntries.map((entry) => entry.ip.toLowerCase())), + [activeBlocklistEntries] + ); + + const saveBlockEntry = async (targetIp?: string, targetReason?: string) => { + const ip = String(targetIp || blockIp).trim(); + const reason = String(targetReason ?? blockReason).trim(); + if (!ip) { + toast.error("请输入要拉黑的 IP"); + return; + } + + setIsSavingBlock(true); + try { + const response = await fetch("/api/admin/access-blocklist", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ip, reason }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "拉黑失败"); + } + + toast.success(`${ip} 已加入手动黑名单`); + setBlockIp(""); + setBlockReason(""); + await Promise.all([mutateBlocklist(), mutate()]); + } catch (error) { + toast.error(error instanceof Error ? error.message : "拉黑失败"); + } finally { + setIsSavingBlock(false); + } + }; + + const updateBlockEntry = async (entry: AccessBlocklistEntry, isActive: boolean) => { + try { + const response = await fetch("/api/admin/access-blocklist", { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + id: entry.id, + isActive, + reason: entry.reason || "", + expiresAt: entry.expiresAt || null, + }), + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "更新失败"); + } + + toast.success(isActive ? `${entry.ip} 已重新拉黑` : `${entry.ip} 已解除拉黑`); + await Promise.all([mutateBlocklist(), mutate()]); + } catch (error) { + toast.error(error instanceof Error ? error.message : "更新失败"); + } + }; + + const overviewCards = [ + { + key: "events", + label: "访问记录", + value: formatNumber(data?.overview.totalEvents), + note: `${hours} 小时窗口`, + icon: Activity, + className: "border-slate-200 bg-slate-50 text-slate-900", + }, + { + key: "ips", + label: "独立 IP", + value: formatNumber(data?.overview.uniqueIps), + note: `${formatNumber(data?.overview.abnormalIps)} 个异常标注`, + icon: Globe2, + className: "border-sky-200 bg-sky-50 text-sky-900", + }, + { + key: "abnormal", + label: "异常事件", + value: formatNumber(data?.overview.abnormalEvents), + note: `${formatNumber(data?.overview.manualBlockedEvents)} 次手动阻断`, + icon: ShieldAlert, + className: "border-orange-200 bg-orange-50 text-orange-900", + }, + { + key: "login", + label: "成功登录", + value: formatNumber(data?.overview.loginSuccessEvents), + note: `${formatNumber(data?.overview.unauthorizedEvents)} 次未授权`, + icon: LogIn, + className: "border-emerald-200 bg-emerald-50 text-emerald-900", + }, + ]; + + const maxHourlyCount = Math.max( + 1, + ...(data?.hourlyStats || []).map((item) => item.count) + ); + const maxPathCount = Math.max( + 1, + ...(data?.pathStats || []).map((item) => item.count) + ); + + return ( +
+ + +
+
+ 访问安全分析 + + IP 访问记录、登录来源、异常标注与请求趋势 + +
+
+
+ + setQuery(event.target.value)} + placeholder="搜索 IP、路径、用户" + value={query} + /> +
+ + + +
+
+
+ +
+ {overviewCards.map((item) => { + const Icon = item.icon; + return ( +
+
+
{item.label}
+ +
+
+ {item.value} +
+
{item.note}
+
+ ); + })} +
+ +
+
+
+ + 小时趋势 +
+
+ 橙色表示异常事件占比 +
+
+
+ {(data?.hourlyStats || []).map((item) => { + const height = Math.max(4, (item.count / maxHourlyCount) * 100); + const abnormalHeight = + item.count > 0 + ? Math.max(0, (item.abnormalCount / item.count) * height) + : 0; + return ( +
+
+
+ {item.hour} · {formatNumber(item.count)} 次 · 异常{" "} + {formatNumber(item.abnormalCount)} +
+
+ ); + })} + {(!data?.hourlyStats || data.hourlyStats.length === 0) && ( +
+ 暂无访问记录 +
+ )} +
+
+ + + + + + 手动 IP 黑名单 + + 管理员手动加入后,命中 IP 会被阻断并写入访问日志 + + + +
+ setBlockIp(event.target.value)} + placeholder="IP 或 IPv4 CIDR" + value={blockIp} + /> + setBlockReason(event.target.value)} + placeholder="拉黑原因" + value={blockReason} + /> + +
+ +
+ {activeBlocklistEntries.map((entry) => ( +
+
+
+
+ + + {entry.ip} + +
+
+ {entry.reason || "未填写原因"} +
+
+ {formatTime(entry.updatedAt)} +
+
+ +
+
+ ))} + {activeBlocklistEntries.length === 0 ? ( +
+ 暂无手动拉黑 IP +
+ ) : null} +
+
+
+ +
+ + + 异常 IP 标注 + + 按限流、失败率、认证异常、敏感路径和请求量综合排序 + + + +
+ {(data?.topIps || []).map((item) => ( +
+
+
+
+ + {item.ip} + + +
+
+ {formatNumber(item.total)} 次访问 + {formatNumber(item.uniqueUsers)} 个用户 + 失败率 {formatPercent(item.failureRate)} + 最近 {formatTime(item.lastSeen)} +
+
+
+ {(item.reasons.length > 0 ? item.reasons : ["正常访问"]).map( + (reason) => ( + + {reason} + + ) + )} + +
+
+
+ ))} + {(!data?.topIps || data.topIps.length === 0) && ( +
+ 暂无 IP 聚合数据 +
+ )} +
+
+
+ + + + 访问路径 + 按请求数量排序 + + +
+ {(data?.pathStats || []).map((item) => { + const abnormalRate = + item.count > 0 ? item.abnormalCount / item.count : 0; + return ( +
+
+ + {item.path || "/"} + + + {formatNumber(item.count)} + +
+
+
+
+
+
+ ); + })} + {(!data?.pathStats || data.pathStats.length === 0) && ( +
+ 暂无路径统计 +
+ )} +
+ + +
+ + + +
+
+ 访问日志列表 + 最近 {formatNumber(data?.recentEvents.length)} 条 +
+
+ {(data?.rules || []).map((rule) => ( + + {rule} + + ))} +
+
+
+ +
+
+
+
时间
+
IP
+
状态
+
路径
+
用户
+
标注
+
+ {(data?.recentEvents || []).map((event) => ( +
+
+ {formatTime(event.createdAt)} +
+
{event.ip}
+
+ {event.statusCode || "--"} +
+
+
+ {event.method || "GET"} {event.path || "/"} +
+
+ {event.reasons?.join("、") || event.outcome} +
+
+
+
+ {event.userEmail || "匿名"} +
+
+ + {event.userRole || "unknown"} +
+
+
+ {event.severity === "high" || event.severity === "critical" ? ( + + ) : null} + +
+
+ ))} + {(!data?.recentEvents || data.recentEvents.length === 0) && ( +
+ 暂无访问日志 +
+ )} +
+
+
+
+
+ ); +} diff --git a/app/(admin)/settings/_components/admin-settings-navigation.tsx b/app/(admin)/settings/_components/admin-settings-navigation.tsx index 346e073b7..f449fa28f 100644 --- a/app/(admin)/settings/_components/admin-settings-navigation.tsx +++ b/app/(admin)/settings/_components/admin-settings-navigation.tsx @@ -33,8 +33,8 @@ function SettingsQuickAction({ ? "border-foreground/10 bg-foreground text-background shadow-sm hover:!bg-foreground/90 hover:!text-background dark:border-white/20 dark:bg-white dark:text-black dark:hover:!bg-white/90 dark:hover:!text-black" : "border-transparent bg-transparent text-muted-foreground hover:!border-border/80 hover:!bg-zinc-100 hover:!text-foreground dark:hover:!bg-zinc-900/50"; const layoutClassName = stretched - ? "h-10 w-full min-w-0 justify-center gap-2 rounded-2xl border px-4" - : "h-9 shrink-0 gap-2 rounded-full border px-3.5"; + ? "h-8 w-full min-w-0 justify-center gap-1.5 rounded-md border px-2.5 text-xs" + : "h-8 shrink-0 gap-1.5 rounded-md border px-2.5 text-xs"; if (item.href) { return ( @@ -45,7 +45,7 @@ function SettingsQuickAction({ variant="ghost" > - + {item.label} @@ -59,7 +59,7 @@ function SettingsQuickAction({ size="sm" variant="ghost" > - + {item.label} ); @@ -84,11 +84,14 @@ export function AdminSettingsNavigation({ }; return ( -
-
+