Compare commits
No commits in common. "main" and "codex/sku-stream-links" have entirely different histories.
main
...
codex/sku-
@ -2377,10 +2377,8 @@ export function LocalAiImagePipelineSections({
|
||||
items={[
|
||||
{
|
||||
label:
|
||||
extendConfig.provider === "fal"
|
||||
? "fal · FLUX 2 Pro 扩图"
|
||||
: extendConfig.provider === "vip98k"
|
||||
? `98K · ${extendConfig.modelId || "image-expansion"}`
|
||||
extendConfig.provider === "vip98k"
|
||||
? "VIP98K 服务商"
|
||||
: "阿里云服务商",
|
||||
tone: "enabled",
|
||||
},
|
||||
@ -2393,13 +2391,9 @@ export function LocalAiImagePipelineSections({
|
||||
}
|
||||
title="图像拓展API配置"
|
||||
>
|
||||
{extendConfig.provider === "fal" ? (
|
||||
{extendConfig.provider === "vip98k" ? (
|
||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||
使用 FLUX 2 Pro Outpaint 扩展图片。密钥从已启用的 fal 官方服务商读取。
|
||||
</div>
|
||||
) : extendConfig.provider === "vip98k" ? (
|
||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||
使用 98K 的 {extendConfig.modelId || "image-expansion"} 模型。API Key 从“AI 模型设置”中的
|
||||
使用 VIP98K 的 image-expansion 模型。API Key 从“AI 模型设置”中的
|
||||
VIP98K 服务商读取,仅在这里维护扩展比例。
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@ -274,9 +274,7 @@ export type EnhanceConfig = {
|
||||
};
|
||||
|
||||
export type ExtendConfig = {
|
||||
provider: "vip98k" | "dashscope" | "fal";
|
||||
modelId: string;
|
||||
routeOptionId: string;
|
||||
provider: "vip98k" | "dashscope";
|
||||
xScale: string;
|
||||
yScale: string;
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -4,8 +4,7 @@ import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
|
||||
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
||||
import {
|
||||
DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
||||
findConfiguredDetailReplacementImageModel,
|
||||
isDetailReplacementImageModel,
|
||||
normalizeDetailReplacementImageModelConfig,
|
||||
} from "@/lib/ai/detail-replacement-image-model-config";
|
||||
import {
|
||||
compositeReplacementWithReferenceLocks,
|
||||
@ -30,6 +29,7 @@ import {
|
||||
} from "@/lib/db/queries";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
import { bufferToArrayBuffer } from "./persistence";
|
||||
import { isVideoProviderType } from "./video-models";
|
||||
import type { AgentPresetMessageImagePart } from "./agent-scene-workflow";
|
||||
import type { PostRequestBody } from "../schema";
|
||||
|
||||
@ -623,7 +623,7 @@ async function resolveReplacementProductIdentityProfile(params: {
|
||||
system:
|
||||
"你是高精度商品结构分析器。多张图片属于同一商品;请跨视角还原唯一结构身份,并明确每个视角最清楚的构件。",
|
||||
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
||||
maxOutputTokens: 1800,
|
||||
maxTokens: 1800,
|
||||
abortSignal: AbortSignal.timeout(
|
||||
params.planningRuntime.kind === "local_moonshot" ? 90_000 : 60_000,
|
||||
),
|
||||
@ -2161,10 +2161,22 @@ export async function resolveDirectReplacementModelRef(params: {
|
||||
models?: Awaited<ReturnType<typeof getEnabledAiModelsWithProvider>>;
|
||||
}) {
|
||||
const models = params.models || (await getEnabledAiModelsWithProvider(false));
|
||||
const imageModels = models.filter(
|
||||
({ model, provider }) =>
|
||||
model.supportsImageGen &&
|
||||
!model.isSubModel &&
|
||||
!isVideoProviderType(provider?.type, model),
|
||||
);
|
||||
const configuredModelSetting = await getSystemSetting({
|
||||
key: DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
||||
}).catch(() => null);
|
||||
const configuredModel = findConfiguredDetailReplacementImageModel(models, configuredModelSetting?.value);
|
||||
const configuredModelId = normalizeDetailReplacementImageModelConfig(
|
||||
configuredModelSetting?.value,
|
||||
).modelId;
|
||||
const configuredModel = imageModels.find(
|
||||
({ model }) =>
|
||||
model.id === configuredModelId || model.modelId === configuredModelId,
|
||||
);
|
||||
if (configuredModel) {
|
||||
return configuredModel.model.id;
|
||||
}
|
||||
@ -2178,7 +2190,6 @@ export async function resolveDirectReplacementModelRef(params: {
|
||||
return routedModel;
|
||||
}
|
||||
|
||||
const imageModels = models.filter(isDetailReplacementImageModel);
|
||||
const preferred =
|
||||
imageModels.find(({ model }) => model.isDefault) ||
|
||||
imageModels.find(({ provider }) => String(provider?.type || "").includes("image")) ||
|
||||
@ -2376,7 +2387,7 @@ export async function analyzeReplacementReferenceImage(params: {
|
||||
},
|
||||
],
|
||||
temperature: 0,
|
||||
maxOutputTokens: 160,
|
||||
maxTokens: 160,
|
||||
abortSignal: AbortSignal.timeout(45_000),
|
||||
} as any);
|
||||
|
||||
@ -2679,7 +2690,7 @@ export async function analyzeReplacementExecutionPlan(params: {
|
||||
system:
|
||||
"你是高精度商品详情图场景规划器。你只分析当前参考图本身,负责理解这一屏的场景、机位、主体位置和人物需求,不要臆测或依赖其他输入图片。",
|
||||
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
||||
maxOutputTokens: 1600,
|
||||
maxTokens: 1600,
|
||||
abortSignal: AbortSignal.timeout(replacementScenePlanningTimeoutMs),
|
||||
} as any);
|
||||
|
||||
|
||||
@ -5,7 +5,7 @@ import { modelLacksReferenceImageInputSupport } from "@/lib/ai/reference-image-c
|
||||
import type { ChatMessage } from "@/lib/types";
|
||||
import { convertMessagesWithImages } from "./image-media";
|
||||
import { isProviderBalanceError } from "@/lib/request-error";
|
||||
import { isImageModelBalanceBlocked } from "@/lib/ai/runtime/image-balance";
|
||||
import { isImageFallbackModelBalanceCoolingDown } from "@/lib/ai/runtime/image-fallback-balance-cooldown";
|
||||
|
||||
const chatApiLogger = createLogger("chat.imageFailover");
|
||||
|
||||
@ -264,29 +264,6 @@ export function chatMessagesHaveImageInput(messages: ChatMessage[]) {
|
||||
return countChatMessageImageInputs(messages) > 0;
|
||||
}
|
||||
|
||||
export function canUseImageFallback(
|
||||
candidate: { model: any; provider: any },
|
||||
imageParams: { imageSize?: unknown; aspectRatio?: unknown; imageCount?: number },
|
||||
messages: ChatMessage[],
|
||||
balanceBlockedProviders: ReadonlySet<string>,
|
||||
) {
|
||||
if (balanceBlockedProviders.has(candidate.provider?.id)) return false;
|
||||
const config = candidate.model?.imageGenConfig;
|
||||
const size = String(imageParams.imageSize || "").toUpperCase();
|
||||
const ratio = String(imageParams.aspectRatio || "");
|
||||
if (size && Array.isArray(config?.supportedImageSizes) &&
|
||||
!config.supportedImageSizes.includes(size)) return false;
|
||||
if (ratio && ratio !== "auto" && Array.isArray(config?.supportedAspectRatios) &&
|
||||
!config.supportedAspectRatios.includes(ratio)) return false;
|
||||
if (imageParams.imageCount && typeof config?.maxImages === "number" &&
|
||||
imageParams.imageCount > config.maxImages) return false;
|
||||
const referenceCount = countChatMessageImageInputs(messages);
|
||||
if (referenceCount && modelLacksReferenceImageInputSupport(candidate.model, candidate.provider)) return false;
|
||||
if (referenceCount && typeof config?.maxReferenceImages === "number" &&
|
||||
referenceCount > config.maxReferenceImages) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getImageFailoverConvertProvider(providerType?: string | null) {
|
||||
switch (providerType) {
|
||||
case "bfl-image":
|
||||
@ -349,7 +326,7 @@ export function buildImageFallbackCandidates(
|
||||
if (!sameProvider && !IMAGE_FAILOVER_PROVIDER_ALLOWLIST.has(providerType)) {
|
||||
return false;
|
||||
}
|
||||
if (isImageFallbackModelCoolingDown(item.model.id) || isImageModelBalanceBlocked(item.model)) {
|
||||
if (isImageFallbackModelCoolingDown(item.model.id) || isImageFallbackModelBalanceCoolingDown(item.model)) {
|
||||
const cooldown = imageFailoverModelCooldown.get(item.model.id);
|
||||
chatApiLogger.info(`[Chat API] ⏭ Skip configured image fallback on cooldown: ${item.model.displayName} (${providerType}) - ${cooldown?.reason || "provider balance cooldown"}`);
|
||||
return false;
|
||||
@ -511,7 +488,7 @@ export function getImageCrossProviderCandidates(
|
||||
}
|
||||
if (m.model.id === options.currentModelId) return false;
|
||||
if (options.currentProviderId && m.provider.id === options.currentProviderId) return false;
|
||||
if (isImageFallbackModelCoolingDown(m.model.id) || isImageModelBalanceBlocked(m.model)) {
|
||||
if (isImageFallbackModelCoolingDown(m.model.id) || isImageFallbackModelBalanceCoolingDown(m.model)) {
|
||||
const cooldown = imageFailoverModelCooldown.get(m.model.id);
|
||||
chatApiLogger.info(`[Chat API] ⏭ Skip image failover model on cooldown: ${m.model.displayName} (${m.provider.type}) - ${cooldown?.reason || "provider balance cooldown"}`);
|
||||
return false;
|
||||
|
||||
@ -1,56 +0,0 @@
|
||||
import { saveMessages } from "@/lib/db/queries";
|
||||
import type { ImageGenerationStatusStreamPayload } from "@/lib/canvas/image-generation-status";
|
||||
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { safeWriteStreamChunk, type StreamWriter, writeAssistantTextChunk, writeStructuredDataChunk } from "./stream";
|
||||
|
||||
const logger = createLogger("chat.imageGenerationFailure");
|
||||
|
||||
export async function reportImageGenerationFailure(params: {
|
||||
writer: StreamWriter;
|
||||
chatId: string;
|
||||
userMessageId: string;
|
||||
messageId: string;
|
||||
error: unknown;
|
||||
label: string;
|
||||
}) {
|
||||
const failure = getRequestFailureDetails(params.error, "图片生成失败");
|
||||
logger.warn("Image request failed", {
|
||||
requestId: params.messageId,
|
||||
userMessageId: params.userMessageId,
|
||||
providerRequestId: (params.error as { providerRequestId?: string } | null)?.providerRequestId,
|
||||
code: failure.code,
|
||||
});
|
||||
const status: ImageGenerationStatusStreamPayload = {
|
||||
phase: "failed",
|
||||
userMessageId: params.userMessageId,
|
||||
requestId: params.messageId,
|
||||
failure,
|
||||
};
|
||||
const text = formatRequestFailure(failure, params.messageId);
|
||||
const parts = [
|
||||
{ type: "text", text },
|
||||
{ type: "data-imageGenerationStatus", data: status },
|
||||
];
|
||||
writeStructuredDataChunk(params.writer, "data-imageGenerationStatus", status, `${params.label}:status`);
|
||||
safeWriteStreamChunk(params.writer, {
|
||||
type: "data-appendMessage",
|
||||
data: JSON.stringify({ id: params.messageId, role: "assistant", parts }),
|
||||
}, params.label);
|
||||
writeAssistantTextChunk(params.writer, "<!-- IMAGE_GENERATION_END -->", `${params.label}:end`);
|
||||
// History carries the same terminal state when the browser loses the stream.
|
||||
await saveMessages({ messages: [{
|
||||
id: params.messageId,
|
||||
chatId: params.chatId,
|
||||
role: "assistant",
|
||||
parts,
|
||||
attachments: [],
|
||||
createdAt: new Date(),
|
||||
videoStorageStatus: null,
|
||||
temporaryVideoUrl: null,
|
||||
permanentVideoUrl: null,
|
||||
archivedAt: null,
|
||||
videoMetadata: null,
|
||||
}] });
|
||||
return text;
|
||||
}
|
||||
@ -208,7 +208,6 @@ export function writeImageGenerationStatusChunk(
|
||||
writer: StreamWriter,
|
||||
params: {
|
||||
phase: "queued" | "processing" | "finalizing" | "failed" | "completed";
|
||||
userMessageId?: string;
|
||||
providerType?: string | null;
|
||||
modelName?: string | null;
|
||||
imageCount?: number | null;
|
||||
@ -224,7 +223,6 @@ export function writeImageGenerationStatusChunk(
|
||||
"data-imageGenerationStatus",
|
||||
{
|
||||
phase: params.phase,
|
||||
userMessageId: params.userMessageId,
|
||||
providerType: normalizeImageLoadingProviderType(params.providerType),
|
||||
modelName: String(params.modelName || "").trim() || undefined,
|
||||
imageCount:
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
import { isExplicitDestructiveIntent } from "@/lib/ai/canvas-agent-runtime/capability-access";
|
||||
import { inferVideoTaskRequirements } from "@/lib/ai/canvas-agent-runtime/video-protocol";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { trackRuntimeWork } from "@/lib/observability/active-work";
|
||||
import { geolocation } from "@vercel/functions";
|
||||
import {
|
||||
convertToModelMessages,
|
||||
createUIMessageStream as createAiUIMessageStream,
|
||||
createUIMessageStream,
|
||||
generateText,
|
||||
smoothStream,
|
||||
stepCountIs,
|
||||
@ -337,8 +336,6 @@ import {
|
||||
} from "./_lib/image-media";
|
||||
import {
|
||||
buildImageFallbackCandidates,
|
||||
canUseImageFallback,
|
||||
countChatMessageImageInputs,
|
||||
generateImageWithFailoverCandidate,
|
||||
getImageCrossProviderCandidates,
|
||||
IMAGE_FAILOVER_PROVIDER_ALLOWLIST,
|
||||
@ -347,8 +344,6 @@ import {
|
||||
setImageFallbackModelCooldown,
|
||||
shouldCooldownImageFallbackModel,
|
||||
} from "./_lib/image-failover";
|
||||
import { isImageModelBalanceBlocked, resolveConfiguredImageBalanceFallback } from "@/lib/ai/runtime/image-balance";
|
||||
import { isProviderBalanceError } from "@/lib/request-error";
|
||||
import {
|
||||
buildAgentSceneWorkflowPrompt,
|
||||
buildAgentSlotPrompt,
|
||||
@ -427,11 +422,7 @@ import {
|
||||
type VideoModeType,
|
||||
} from "./_lib/video-models";
|
||||
|
||||
import { reportImageGenerationFailure } from "./_lib/image-generation-failure";
|
||||
|
||||
const chatApiLogger = createLogger("chat.route");
|
||||
const createUIMessageStream: typeof createAiUIMessageStream = (options) =>
|
||||
createAiUIMessageStream({ ...options, execute: (writer) => trackRuntimeWork(() => options.execute(writer)) });
|
||||
|
||||
const INTERNAL_IMAGE_GENERATION_FAILURE_PATTERN =
|
||||
/生成图片失败|图片生成失败|未找到图片数据|未解析到图片|模型未返回生成图片|图片数据不可用|未返回可用图片/i;
|
||||
@ -449,6 +440,16 @@ function assertGeneratedImageMarkdownHasImage(markdown: string, modelLabel: stri
|
||||
throw new Error(`${modelLabel} 未返回可用图片:${reason.slice(0, 160)}`);
|
||||
}
|
||||
|
||||
function getPublicImageGenerationErrorText(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error || "");
|
||||
const publicMessage = getUserFacingImageGenerationErrorMessage(error);
|
||||
if (!message || (publicMessage === message && INTERNAL_IMAGE_GENERATION_FAILURE_PATTERN.test(message))) {
|
||||
return "图片生成失败,请稍后重试";
|
||||
}
|
||||
return publicMessage;
|
||||
}
|
||||
|
||||
|
||||
const AGENT_REPLACEMENT_PARALLEL_WORKER_COUNT = Math.max(
|
||||
1,
|
||||
Math.min(8, Number(process.env.AGENT_REPLACEMENT_PARALLEL_WORKER_COUNT || 6) || 6),
|
||||
@ -5681,7 +5682,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
modelName: resolvedModelRef,
|
||||
imageCount: replacementReferences.length,
|
||||
@ -6024,7 +6024,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase:
|
||||
queueStatus.status === "running"
|
||||
? "processing"
|
||||
@ -6180,7 +6179,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: successCount > 0 ? "completed" : "failed",
|
||||
modelName: resolvedModelDisplayName,
|
||||
imageCount: successCount,
|
||||
@ -6413,7 +6411,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
modelName:
|
||||
selectedAgentPreset.defaultModel?.displayName ||
|
||||
@ -6965,7 +6962,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase:
|
||||
queueStatus.status === "running"
|
||||
? "processing"
|
||||
@ -7291,7 +7287,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase:
|
||||
queueStatus.status === "running"
|
||||
? "processing"
|
||||
@ -7520,7 +7515,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase:
|
||||
queueStatus.status === "running"
|
||||
? "processing"
|
||||
@ -7839,7 +7833,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: successCount > 0 ? "completed" : "failed",
|
||||
modelName:
|
||||
selectedAgentPreset.defaultModel?.displayName ||
|
||||
@ -8049,7 +8042,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
providerType: requestedModelProviderType,
|
||||
modelName: finalModelId,
|
||||
@ -8088,7 +8080,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
...directImageStatusPayload,
|
||||
},
|
||||
@ -8181,7 +8172,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: requestedModelProviderType,
|
||||
modelName: directImageResult.model,
|
||||
@ -8202,16 +8192,42 @@ export async function POST(request: Request) {
|
||||
);
|
||||
} catch (directToolError) {
|
||||
chatApiLogger.error("[Chat API] Direct agent image generation failed:", directToolError);
|
||||
const errorMessage = await reportImageGenerationFailure({
|
||||
writer, chatId: id, userMessageId: message.id,
|
||||
messageId: assistantMessageId, error: directToolError,
|
||||
label: "agent:generate_image:error",
|
||||
const errorMessage = getDirectAgentToolErrorMessage(
|
||||
"generate_image",
|
||||
directToolError,
|
||||
);
|
||||
await saveAssistantTextOnlyMessage({
|
||||
chatId: id,
|
||||
messageId: assistantMessageId,
|
||||
text: errorMessage,
|
||||
});
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
errorMessage,
|
||||
"agent:generate_image:error",
|
||||
assistantMessageId,
|
||||
);
|
||||
if (contextPayload?.source === "canvas") {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
phase: "failed",
|
||||
providerType: requestedModelProviderType,
|
||||
modelName: finalModelId,
|
||||
},
|
||||
"agent:generate_image:status-failed",
|
||||
);
|
||||
}
|
||||
writeAgentProgressChunk(
|
||||
writer,
|
||||
buildDirectAgentImageGenerateFailedProgress(errorMessage),
|
||||
"agent:generate_image:progress-failed",
|
||||
);
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"<!-- IMAGE_GENERATION_END -->",
|
||||
"agent:generate_image:end-error",
|
||||
);
|
||||
} finally {
|
||||
stopDirectImageKeepalive();
|
||||
if (stopDirectImageStatus) {
|
||||
@ -8753,19 +8769,6 @@ export async function POST(request: Request) {
|
||||
}
|
||||
}
|
||||
|
||||
if (/^[0-9a-f-]{36}$/i.test(finalModelId)) {
|
||||
const requested = await getAiModelById({ id: finalModelId });
|
||||
if (requested?.supportsImageGen && isImageModelBalanceBlocked(requested)) {
|
||||
const replacement = resolveConfiguredImageBalanceFallback(requested, await getEnabledAiModelsWithProvider(), {
|
||||
imageSize: effectiveImageGenerationParams.imageSize,
|
||||
aspectRatio: effectiveImageGenerationParams.aspectRatio,
|
||||
referenceImageCount: countChatMessageImageInputs(uiMessagesForModel.filter(item => item.role === "user").slice(-1)),
|
||||
});
|
||||
if (!replacement) return new ChatSDKError("bad_request:api", "当前生图线路余额不足,已暂停新请求;请切换可用模型,已有任务和图片会保留。").toResponse();
|
||||
finalModelId = replacement.model.id;
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否是 UUID 格式(数据库中的模型 ID)
|
||||
const isUUID =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
@ -9173,7 +9176,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
providerType: (languageModel as any).provider,
|
||||
modelName: currentModelConfig?.displayName || actualModelId,
|
||||
@ -9217,11 +9219,8 @@ export async function POST(request: Request) {
|
||||
|
||||
// 🆕 尝试备用模型(支持跨服务商切换)
|
||||
let fallbackSuccess = false;
|
||||
const balanceBlockedProviders = new Set<string>();
|
||||
if (isProviderBalanceError(primaryError) && currentModelConfig?.providerId) balanceBlockedProviders.add(currentModelConfig.providerId);
|
||||
const triedFallbackModelIds = new Set<string>();
|
||||
for (const candidate of fallbackCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, buildMessagesForGemini(), balanceBlockedProviders)) continue;
|
||||
try {
|
||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||
chatApiLogger.info(`[Chat API] 🔄 Trying fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
@ -9243,7 +9242,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Fallback model ${fallbackResult.displayName} succeeded!`);
|
||||
break;
|
||||
} catch (fallbackError) {
|
||||
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||
@ -9265,7 +9263,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.warn("[Chat API] Record Gemini fallback health failure failed:", healthError);
|
||||
});
|
||||
chatApiLogger.error(`[Chat API] ❌ Fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
|
||||
@ -9297,7 +9294,6 @@ export async function POST(request: Request) {
|
||||
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")));
|
||||
|
||||
for (const candidate of crossProviderCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, buildMessagesForGemini(), balanceBlockedProviders)) continue;
|
||||
try {
|
||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||
chatApiLogger.info(`[Chat API] 🔁 Gemini cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
@ -9320,7 +9316,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Gemini cross-provider fallback model ${fallbackResult.displayName} succeeded!`);
|
||||
break;
|
||||
} catch (fallbackError) {
|
||||
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||
@ -9342,7 +9337,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.warn("[Chat API] Record Gemini cross-provider health failure failed:", healthError);
|
||||
});
|
||||
chatApiLogger.error(`[Chat API] ❌ Gemini cross-provider fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -9410,7 +9404,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: (languageModel as any).provider,
|
||||
modelName: usedModelDisplayName,
|
||||
@ -9475,14 +9468,6 @@ export async function POST(request: Request) {
|
||||
}
|
||||
} catch (error) {
|
||||
chatApiLogger.error("[Chat API] Gemini generation error:", error);
|
||||
let finalError = error;
|
||||
if (!shouldFailoverAiModelError(error)) {
|
||||
await reportImageGenerationFailure({
|
||||
writer, chatId: id, userMessageId: message.id,
|
||||
messageId: generateUUID(), error, label: "gemini:error",
|
||||
});
|
||||
return;
|
||||
}
|
||||
chatApiLogger.info("[Chat API] Attempting failover to Volcano Vision...");
|
||||
|
||||
// 故障转移:尝试使用火山引擎模型
|
||||
@ -9560,7 +9545,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: "volcano-vision",
|
||||
modelName: volcanoModel.model.displayName || volcanoModel.model.modelId,
|
||||
@ -9626,14 +9610,46 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info("[Chat API] No Volcano Vision model available for failover");
|
||||
} catch (failoverError) {
|
||||
chatApiLogger.error("[Chat API] Failover to Volcano Vision also failed:", failoverError);
|
||||
finalError = failoverError;
|
||||
}
|
||||
|
||||
// 如果故障转移也失败,返回错误消息
|
||||
await reportImageGenerationFailure({
|
||||
writer, chatId: id, userMessageId: message.id,
|
||||
messageId: generateUUID(), error: finalError, label: "gemini:error",
|
||||
});
|
||||
const errorMessageId = generateUUID();
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"图片生成失败,请稍后重试",
|
||||
"gemini:error",
|
||||
errorMessageId,
|
||||
);
|
||||
|
||||
// 🆕 图片生成结束标记(失败)
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"<!-- IMAGE_GENERATION_END -->",
|
||||
"gemini:image-end-failed",
|
||||
);
|
||||
|
||||
// 尝试保存错误消息
|
||||
try {
|
||||
await saveMessages({
|
||||
messages: [
|
||||
{
|
||||
id: errorMessageId,
|
||||
chatId: id,
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: "图片生成失败,请稍后重试" }],
|
||||
attachments: [],
|
||||
createdAt: new Date(),
|
||||
videoStorageStatus: null,
|
||||
temporaryVideoUrl: null,
|
||||
permanentVideoUrl: null,
|
||||
archivedAt: null,
|
||||
videoMetadata: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (saveError) {
|
||||
chatApiLogger.error("[Chat API] Failed to save error message:", saveError);
|
||||
}
|
||||
} finally {
|
||||
stopKeepalive?.();
|
||||
}
|
||||
@ -9831,7 +9847,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "queued",
|
||||
providerType: "fal-image",
|
||||
modelName: modelDisplayName,
|
||||
@ -9938,7 +9953,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
providerType: (languageModel as any).provider,
|
||||
modelName: alibabaModelConfig?.displayName || actualModelId,
|
||||
@ -9988,10 +10002,7 @@ export async function POST(request: Request) {
|
||||
|
||||
let fallbackSuccess = false;
|
||||
const triedFallbackModelIds = new Set<string>();
|
||||
const balanceBlockedProviders = new Set<string>();
|
||||
if (isProviderBalanceError(primaryError) && currentModelEntry?.provider.id) balanceBlockedProviders.add(currentModelEntry.provider.id);
|
||||
for (const candidate of fallbackCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForAlibaba, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||
chatApiLogger.info(`[Chat API] 🔄 Alibaba fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
@ -10014,7 +10025,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Alibaba fallback model ${fallbackResult.displayName} succeeded!`);
|
||||
break;
|
||||
} catch (fallbackError) {
|
||||
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||
@ -10036,7 +10046,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.warn("[Chat API] Record image fallback health failure failed:", healthError);
|
||||
});
|
||||
chatApiLogger.error(`[Chat API] ❌ Alibaba fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
|
||||
@ -10064,10 +10073,9 @@ export async function POST(request: Request) {
|
||||
currentModelKey: actualModelId,
|
||||
currentProviderId: alibabaModelConfig?.providerId,
|
||||
providerPriority,
|
||||
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")) && !balanceBlockedProviders.has(candidate.provider.id));
|
||||
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")));
|
||||
|
||||
for (const candidate of crossProviderCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForAlibaba, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||
chatApiLogger.info(`[Chat API] 🔁 Cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
@ -10149,7 +10157,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
break;
|
||||
} catch (crossError) {
|
||||
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||
@ -10171,7 +10178,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.warn("[Chat API] Record image cross-provider health failure failed:", healthError);
|
||||
});
|
||||
chatApiLogger.error(`[Chat API] ❌ Cross-provider failover failed: ${candidate.model.displayName} (${candidate.provider.type})`, crossError);
|
||||
if (!shouldFailoverAiModelError(crossError)) throw crossError;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -10239,7 +10245,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: (languageModel as any).provider,
|
||||
modelName: usedModelDisplayName,
|
||||
@ -10304,10 +10309,43 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.error("[Chat API] Alibaba generation error:", error);
|
||||
|
||||
// 返回错误消息
|
||||
await reportImageGenerationFailure({
|
||||
writer, chatId: id, userMessageId: message.id,
|
||||
messageId: generateUUID(), error, label: "alibaba:error",
|
||||
});
|
||||
const errorMessageId = generateUUID();
|
||||
const errorText = getPublicImageGenerationErrorText(error);
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
errorText,
|
||||
"alibaba:error",
|
||||
errorMessageId,
|
||||
);
|
||||
|
||||
// 🆕 图片生成结束标记(失败)
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"<!-- IMAGE_GENERATION_END -->",
|
||||
"alibaba:image-end-failed",
|
||||
);
|
||||
|
||||
try {
|
||||
await saveMessages({
|
||||
messages: [
|
||||
{
|
||||
id: errorMessageId,
|
||||
chatId: id,
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: errorText }],
|
||||
attachments: [],
|
||||
createdAt: new Date(),
|
||||
videoStorageStatus: null,
|
||||
temporaryVideoUrl: null,
|
||||
permanentVideoUrl: null,
|
||||
archivedAt: null,
|
||||
videoMetadata: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (saveError) {
|
||||
chatApiLogger.error("[Chat API] Failed to save error message:", saveError);
|
||||
}
|
||||
} finally {
|
||||
stopKeepalive?.();
|
||||
}
|
||||
@ -10436,7 +10474,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
providerType: "volcano-vision",
|
||||
modelName: volcanoModelConfig?.displayName || actualModelId,
|
||||
@ -10455,10 +10492,7 @@ export async function POST(request: Request) {
|
||||
throw primaryError;
|
||||
}
|
||||
let fallbackSuccess = false;
|
||||
const balanceBlockedProviders = new Set<string>();
|
||||
if (isProviderBalanceError(primaryError) && volcanoModelConfig?.providerId) balanceBlockedProviders.add(volcanoModelConfig.providerId);
|
||||
for (const candidate of fallbackCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForVolcano, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
chatApiLogger.info(`[Chat API] 🔄 Volcano fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
const fallbackResult = await generateImageWithFailoverCandidate({
|
||||
@ -10480,13 +10514,11 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Volcano fallback model ${fallbackResult.displayName} succeeded!`);
|
||||
break;
|
||||
} catch (fallbackError) {
|
||||
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||
}
|
||||
chatApiLogger.error(`[Chat API] ❌ Volcano fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
if (!fallbackSuccess) {
|
||||
@ -10516,7 +10548,6 @@ export async function POST(request: Request) {
|
||||
});
|
||||
|
||||
for (const candidate of crossProviderCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForVolcano, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
chatApiLogger.info(`[Chat API] 🔁 Volcano cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
if (
|
||||
@ -10597,7 +10628,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ Volcano cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
break;
|
||||
} catch (crossError) {
|
||||
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||
@ -10655,7 +10685,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
writer,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: "volcano-vision",
|
||||
modelName: usedModelDisplayName,
|
||||
@ -10720,10 +10749,43 @@ export async function POST(request: Request) {
|
||||
}
|
||||
} catch (error) {
|
||||
chatApiLogger.error("[Chat API] Volcano Vision generation error:", error);
|
||||
await reportImageGenerationFailure({
|
||||
writer, chatId: id, userMessageId: message.id,
|
||||
messageId: generateUUID(), error, label: "volcano:error",
|
||||
});
|
||||
const errorMessageId = generateUUID();
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"图片生成失败,请稍后重试",
|
||||
"volcano:error",
|
||||
errorMessageId,
|
||||
);
|
||||
|
||||
// 🆕 图片生成结束标记(失败)
|
||||
writeAssistantTextChunk(
|
||||
writer,
|
||||
"<!-- IMAGE_GENERATION_END -->",
|
||||
"volcano:image-end-failed",
|
||||
);
|
||||
|
||||
// 尝试保存错误消息
|
||||
try {
|
||||
await saveMessages({
|
||||
messages: [
|
||||
{
|
||||
id: errorMessageId,
|
||||
chatId: id,
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: "图片生成失败,请稍后重试" }],
|
||||
attachments: [], // 必须提供 attachments 字段
|
||||
createdAt: new Date(),
|
||||
videoStorageStatus: null,
|
||||
temporaryVideoUrl: null,
|
||||
permanentVideoUrl: null,
|
||||
archivedAt: null,
|
||||
videoMetadata: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (saveError) {
|
||||
chatApiLogger.error("[Chat API] Failed to save error message:", saveError);
|
||||
}
|
||||
} finally {
|
||||
stopKeepalive?.();
|
||||
}
|
||||
@ -11296,7 +11358,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
dataStream as unknown as StreamWriter,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "processing",
|
||||
providerType: currentModelConfig?.providerId ? resolvedProviderType || providerType : providerType,
|
||||
modelName: currentModelConfig?.displayName || actualModelId,
|
||||
@ -11341,10 +11402,7 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
let fallbackSuccess = false;
|
||||
const balanceBlockedProviders = new Set<string>();
|
||||
if (isProviderBalanceError(primaryError) && currentModelConfig?.providerId) balanceBlockedProviders.add(currentModelConfig.providerId);
|
||||
for (const candidate of fallbackCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForCrossProvider, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
chatApiLogger.info(`[Chat API] 🔄 OpenAI-compatible fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
const shouldUseOpenAICompatFallback =
|
||||
@ -11386,13 +11444,11 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible fallback model ${candidate.model.displayName} succeeded!`);
|
||||
break;
|
||||
} catch (fallbackError) {
|
||||
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||
}
|
||||
chatApiLogger.error(`[Chat API] ❌ OpenAI-compatible fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||
}
|
||||
}
|
||||
|
||||
@ -11423,7 +11479,6 @@ export async function POST(request: Request) {
|
||||
});
|
||||
|
||||
for (const candidate of crossProviderCandidates) {
|
||||
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForCrossProvider, balanceBlockedProviders)) continue;
|
||||
try {
|
||||
chatApiLogger.info(`[Chat API] 🔁 OpenAI-compatible cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
if (
|
||||
@ -11507,7 +11562,6 @@ export async function POST(request: Request) {
|
||||
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||
break;
|
||||
} catch (crossError) {
|
||||
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||
@ -11566,7 +11620,6 @@ export async function POST(request: Request) {
|
||||
writeImageGenerationStatusChunk(
|
||||
dataStream as unknown as StreamWriter,
|
||||
{
|
||||
userMessageId: message.id,
|
||||
phase: "completed",
|
||||
providerType: resolvedProviderType || providerType,
|
||||
modelName: usedModelDisplayName,
|
||||
@ -11626,10 +11679,54 @@ export async function POST(request: Request) {
|
||||
} catch (error) {
|
||||
chatApiLogger.error("[Chat API] OpenAI-compatible image model generation error:", error);
|
||||
|
||||
await reportImageGenerationFailure({
|
||||
writer: dataStream as unknown as StreamWriter,
|
||||
chatId: id, userMessageId: message.id,
|
||||
messageId: generateUUID(), error, label: "openai-compat:error",
|
||||
const errorMessageId = generateUUID();
|
||||
const errorText = getPublicImageGenerationErrorText(error);
|
||||
|
||||
dataStream.write({
|
||||
type: "data-appendMessage",
|
||||
data: JSON.stringify({
|
||||
id: errorMessageId,
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: errorText }],
|
||||
}),
|
||||
});
|
||||
dataStream.write({
|
||||
type: "data-appendMessage",
|
||||
data: JSON.stringify({
|
||||
id: generateUUID(),
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: "<!-- IMAGE_GENERATION_END -->" }],
|
||||
}),
|
||||
});
|
||||
if (contextPayload?.source === "canvas") {
|
||||
writeImageGenerationStatusChunk(
|
||||
dataStream as unknown as StreamWriter,
|
||||
{
|
||||
phase: "failed",
|
||||
providerType: resolvedProviderType || providerType,
|
||||
modelName: currentModelConfig?.displayName || actualModelId,
|
||||
imageCount: effectiveImageParams?.imageCount || 1,
|
||||
},
|
||||
"openai-compat:image-status-failed",
|
||||
);
|
||||
}
|
||||
|
||||
await saveMessages({
|
||||
messages: [
|
||||
{
|
||||
id: errorMessageId,
|
||||
role: "assistant",
|
||||
parts: [{ type: "text", text: errorText }],
|
||||
createdAt: new Date(),
|
||||
attachments: [],
|
||||
chatId: id,
|
||||
videoStorageStatus: null,
|
||||
temporaryVideoUrl: null,
|
||||
permanentVideoUrl: null,
|
||||
archivedAt: null,
|
||||
videoMetadata: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@ -10,10 +10,6 @@ import {
|
||||
} from "@/lib/db/queries";
|
||||
import { getAiModelFrontendAvailability } from "@/lib/ai/model-frontend-availability";
|
||||
import { buildVideoToolCapability } from "@/lib/ai/video-tool-capability";
|
||||
import {
|
||||
DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
||||
findConfiguredDetailReplacementImageModel,
|
||||
} from "@/lib/ai/detail-replacement-image-model-config";
|
||||
import {
|
||||
isImageGenerationModelDescriptor,
|
||||
isVideoModelDescriptor,
|
||||
@ -161,17 +157,10 @@ export async function GET(request: Request) {
|
||||
: await getEnabledAiModelsWithProvider(false, true);
|
||||
const agentModelWithProvider = await getAgentAiModelWithProvider();
|
||||
const defaultModel = await getDefaultAiModel();
|
||||
const [siteSettings, agentWorkflowUiConfigSetting, detailReplacementModelSetting] = await Promise.all([
|
||||
const [siteSettings, agentWorkflowUiConfigSetting] = await Promise.all([
|
||||
getSiteSettings(),
|
||||
getSystemSetting({ key: AGENT_WORKFLOW_UI_CONFIG_KEY }).catch(() => null),
|
||||
getSystemSetting({ key: DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY }).catch(() => null),
|
||||
]);
|
||||
const detailReplacementModel = findConfiguredDetailReplacementImageModel(
|
||||
includeUnavailable ? modelsWithProvider.filter(({ model, provider }) =>
|
||||
provider.isEnabled && model.isEnabled && getAiModelFrontendAvailability(model).selectable !== false
|
||||
) : modelsWithProvider,
|
||||
detailReplacementModelSetting?.value,
|
||||
);
|
||||
type ModelWithProvider = (typeof modelsWithProvider)[number];
|
||||
const serializeModel = ({ model, provider }: ModelWithProvider) => ({
|
||||
id: model.id,
|
||||
@ -320,7 +309,6 @@ export async function GET(request: Request) {
|
||||
: null,
|
||||
agentWorkflowDefaultModelId: agentWorkflowDefaultModel?.model.id || null,
|
||||
agentWorkflowConfiguredModels,
|
||||
detailReplacementModel: detailReplacementModel ? serializeModel(detailReplacementModel) : null,
|
||||
agentModel: agentModelWithProvider
|
||||
? {
|
||||
id: agentModelWithProvider.model.id,
|
||||
|
||||
@ -8,8 +8,6 @@ import { ArrowLeft, Download, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsR
|
||||
import { Input } from "@/components/ui/input";
|
||||
import Image from "next/image";
|
||||
import { formatBeijingTime } from "@/lib/utils";
|
||||
import { toast } from "sonner";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
type FeaturedImage = {
|
||||
id: string;
|
||||
@ -76,11 +74,18 @@ export default function FeaturedPage() {
|
||||
|
||||
const handleDownload = async (url: string, prompt: string) => {
|
||||
try {
|
||||
await downloadOriginalImage({ url, name: "featured-image" });
|
||||
toast.success("原图已开始下载");
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = `featured-${Date.now()}.png`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} catch (error) {
|
||||
console.error("Download failed:", error);
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { isRetiredStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
@ -13,7 +12,6 @@ import { requestLongTaskResult } from "@/lib/client/long-task";
|
||||
import { buildImageProxyUrl, getImageDownloadExtension } from "@/lib/image-delivery";
|
||||
import { inferOriginalImageUrl } from "@/lib/image-url";
|
||||
import { formatBeijingTime } from "@/lib/utils";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
type GalleryImage = {
|
||||
id: string;
|
||||
@ -60,7 +58,7 @@ function buildGalleryDownloadFilename(url: string, alt: string, contentType: str
|
||||
}
|
||||
}
|
||||
|
||||
return `${safeBase}.${getImageDownloadExtension(contentType) || extension}`;
|
||||
return `${safeBase}-${Date.now()}.${getImageDownloadExtension(contentType) || extension}`;
|
||||
}
|
||||
|
||||
export default function GalleryPage() {
|
||||
@ -120,11 +118,25 @@ export default function GalleryPage() {
|
||||
const parsed = new URL(originalUrl, window.location.origin);
|
||||
const source = parsed.pathname === "/api/image-proxy" ? originalUrl : inferOriginalImageUrl(originalUrl);
|
||||
|
||||
await downloadOriginalImage({ url: source, name: buildGalleryDownloadFilename(originalUrl, alt, "") });
|
||||
const response = await fetch(
|
||||
buildImageProxyUrl(source, { delivery: "original" })
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`download failed: ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = buildGalleryDownloadFilename(originalUrl, alt, blob.type);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.setTimeout(() => window.URL.revokeObjectURL(blobUrl), 1000);
|
||||
toast.success("图片已开始下载");
|
||||
} catch (error) {
|
||||
console.error("Download failed:", error);
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
toast.error(error instanceof Error && error.message.includes("无法确认原图") ? error.message : "原图下载失败,请重试");
|
||||
}
|
||||
};
|
||||
|
||||
@ -304,12 +316,7 @@ export default function GalleryPage() {
|
||||
<>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="flex flex-wrap justify-center gap-6 px-4">
|
||||
{images.map((img) => isRetiredStorageUrl(img.url) ? (
|
||||
<div key={img.id} className="flex h-[270px] w-[200px] shrink-0 flex-col justify-center rounded-lg border bg-muted p-4 text-center text-sm text-muted-foreground">
|
||||
<p>{RETIRED_STORAGE_MESSAGE}</p>
|
||||
<p className="mt-3 line-clamp-3 text-xs">{img.alt}</p>
|
||||
</div>
|
||||
) : (
|
||||
{images.map((img) => (
|
||||
<div
|
||||
key={img.id}
|
||||
className="group relative cursor-pointer rounded-lg border bg-muted overflow-hidden transition-all hover:shadow-lg hover:scale-105"
|
||||
@ -318,7 +325,7 @@ export default function GalleryPage() {
|
||||
>
|
||||
<div className="relative w-full h-full">
|
||||
<Image
|
||||
src={isRetiredStorageUrl(img.thumbnailUrl) ? img.url : img.thumbnailUrl || img.url}
|
||||
src={img.thumbnailUrl || img.url}
|
||||
alt={img.alt}
|
||||
width={200}
|
||||
height={270}
|
||||
|
||||
@ -1,10 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import { requireAdmin } from "@/lib/middleware/admin";
|
||||
import { ChatSDKError } from "@/lib/errors";
|
||||
import { db } from "@/lib/db";
|
||||
import { aiModelHealthEvent } from "@/lib/db/schema";
|
||||
import { and, desc, eq, sql } from "drizzle-orm";
|
||||
import {
|
||||
listAiModelHealthEvents,
|
||||
restoreAiModelHealth,
|
||||
} from "@/lib/ai/runtime/model-health";
|
||||
|
||||
@ -17,30 +15,14 @@ export async function GET(request: Request) {
|
||||
await requireAdmin();
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const modelId = searchParams.get("modelId");
|
||||
const providerId = searchParams.get("providerId");
|
||||
const rawLimit = Number(searchParams.get("limit") || 20);
|
||||
const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(200, Math.floor(rawLimit))) : 20;
|
||||
const rawPage = Number(searchParams.get("page") || 1);
|
||||
const page = Number.isFinite(rawPage) ? Math.max(1, Math.floor(rawPage)) : 1;
|
||||
const filters = [];
|
||||
if (modelId) filters.push(eq(aiModelHealthEvent.modelId, modelId));
|
||||
if (providerId) filters.push(eq(aiModelHealthEvent.providerId, providerId));
|
||||
if (searchParams.get("eventType")) filters.push(eq(aiModelHealthEvent.eventType, searchParams.get("eventType")!));
|
||||
const start = searchParams.get("startDate");
|
||||
const end = searchParams.get("endDate");
|
||||
if (start && /^\d{4}-\d{2}-\d{2}$/.test(start)) filters.push(sql`${aiModelHealthEvent.createdAt}>=${start}::date`);
|
||||
if (end && /^\d{4}-\d{2}-\d{2}$/.test(end)) filters.push(sql`${aiModelHealthEvent.createdAt}<${end}::date+interval '1 day'`);
|
||||
const events = await db.select({
|
||||
id: aiModelHealthEvent.id, modelId: aiModelHealthEvent.modelId, modelDisplayName: aiModelHealthEvent.modelDisplayName,
|
||||
modelRuntimeId: aiModelHealthEvent.modelRuntimeId, providerName: aiModelHealthEvent.providerName,
|
||||
providerId: aiModelHealthEvent.providerId, eventType: aiModelHealthEvent.eventType,
|
||||
errorMessage: aiModelHealthEvent.errorMessage, elapsedMs: aiModelHealthEvent.elapsedMs,
|
||||
consecutiveFailures: aiModelHealthEvent.consecutiveFailures, autoDisabled: aiModelHealthEvent.autoDisabled,
|
||||
counted: aiModelHealthEvent.counted, createdAt: aiModelHealthEvent.createdAt,
|
||||
}).from(aiModelHealthEvent).where(and(...filters)).orderBy(desc(aiModelHealthEvent.createdAt), desc(aiModelHealthEvent.id))
|
||||
.limit(limit + 1).offset((page - 1) * limit);
|
||||
return Response.json({ events: events.slice(0, limit), hasMore: events.length > limit, page });
|
||||
const modelId = searchParams.get("modelId") || undefined;
|
||||
const limit = Number(searchParams.get("limit") || 80);
|
||||
const events = await listAiModelHealthEvents({
|
||||
modelId,
|
||||
limit: Number.isFinite(limit) ? limit : 80,
|
||||
});
|
||||
|
||||
return Response.json({ events });
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) {
|
||||
return error.toResponse();
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { aiModel, aiProvider } from "@/lib/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { requireAdmin } from "@/lib/middleware/admin";
|
||||
import {
|
||||
getAllAiModels,
|
||||
getAiModelById,
|
||||
getAiModelsByProviderId,
|
||||
createAiModel,
|
||||
updateAiModel,
|
||||
deleteAiModel,
|
||||
@ -155,14 +154,8 @@ export async function GET(request: Request) {
|
||||
const id = searchParams.get("id");
|
||||
const providerId = searchParams.get("providerId");
|
||||
|
||||
if (searchParams.get("view") === "options") {
|
||||
const models = await db.select({ id: aiModel.id, modelId: aiModel.modelId, displayName: aiModel.displayName,
|
||||
providerName: aiProvider.name }).from(aiModel).leftJoin(aiProvider, eq(aiModel.providerId, aiProvider.id));
|
||||
return Response.json({ models: sortModelsForDisplay(models) });
|
||||
}
|
||||
|
||||
if (id) {
|
||||
const model = await db.query.aiModel.findFirst({ where: eq(aiModel.id, id) });
|
||||
const model = await getAiModelById({ id });
|
||||
if (!model) {
|
||||
return new ChatSDKError("bad_request:api", "Model not found").toResponse();
|
||||
}
|
||||
@ -170,19 +163,12 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
if (providerId) {
|
||||
const models = await db.select().from(aiModel).where(eq(aiModel.providerId, providerId));
|
||||
const models = await getAiModelsByProviderId({ providerId });
|
||||
return Response.json({ models: sortModelsForDisplay(models.map(normalizeModel)) });
|
||||
}
|
||||
|
||||
const models = await db.select().from(aiModel);
|
||||
const normalized = models.map(normalizeModel);
|
||||
const output = searchParams.get("view") === "summary" ? normalized.map(model => {
|
||||
const { capabilities, defaultParams, imageGenConfig, description, ...summary } = model;
|
||||
const fields = ["kind", "mediaType", "modelType", "outputType", "supportedModes"];
|
||||
return { ...summary, healthLastError: summary.healthLastError?.slice(0, 1200),
|
||||
capabilities: Object.fromEntries(fields.filter(key => capabilities?.[key] !== undefined).map(key => [key, capabilities[key]])) };
|
||||
}) : normalized;
|
||||
return Response.json({ models: sortModelsForDisplay(output) });
|
||||
const models = await getAllAiModels();
|
||||
return Response.json({ models: sortModelsForDisplay(models.map(normalizeModel)) });
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) {
|
||||
return error.toResponse();
|
||||
|
||||
@ -1,31 +1,237 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { generatedImage, user } from "@/lib/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { chat, generatedImage, message, user } from "@/lib/db/schema";
|
||||
import { eq, desc, sql, and, gte, lte, like, or, isNotNull } from "drizzle-orm";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { requireAdmin } from "@/lib/middleware/admin";
|
||||
import { ChatSDKError } from "@/lib/errors";
|
||||
import { mediaRecordsQuery, parseMediaQuery } from "@/lib/admin/media-records";
|
||||
import { resolveArchivedImageUrls } from "@/lib/storage/image-archive-db";
|
||||
|
||||
function extractVideoUrlFromParts(parts: unknown): string | null {
|
||||
const text = Array.isArray(parts)
|
||||
? parts
|
||||
.map((part) => (part && typeof part === "object" && "text" in part ? String((part as any).text || "") : ""))
|
||||
.join("\n")
|
||||
: typeof parts === "string"
|
||||
? parts
|
||||
: "";
|
||||
|
||||
if (!text) return null;
|
||||
|
||||
const htmlMatch = text.match(/<video[^>]+src="([^"]+)"/i);
|
||||
if (htmlMatch?.[1]) return htmlMatch[1];
|
||||
|
||||
const markdownMatch = text.match(/\[[^\]]*]\((https?:\/\/[^)\s]+\.mp4(?:\?[^)\s]*)?)\)/i);
|
||||
if (markdownMatch?.[1]) return markdownMatch[1];
|
||||
|
||||
const plainMatch = text.match(/(https?:\/\/[^\s"'<>]+\.mp4(?:\?[^\s"'<>]+)?)/i);
|
||||
return plainMatch?.[1] || null;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await requireAdmin();
|
||||
const operator = await db.query.user.findFirst({ where: eq(user.id, session.user.id) });
|
||||
if (operator?.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
const query = parseMediaQuery(request.nextUrl.searchParams);
|
||||
if (query.startDate && query.endDate && query.startDate > query.endDate) {
|
||||
return NextResponse.json({ error: "开始日期不能晚于结束日期" }, { status: 400 });
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
const [result] = await db.execute(mediaRecordsQuery(query));
|
||||
const images = await resolveArchivedImageUrls(result.records);
|
||||
const total = Number(result.total);
|
||||
return NextResponse.json({ images, pagination: { page: query.page, pageSize: query.pageSize, total,
|
||||
totalPages: Math.ceil(total / query.pageSize), totalImages: Number(result.totalImages), totalVideos: Number(result.totalVideos) } });
|
||||
|
||||
// 检查是否为管理员
|
||||
const currentUser = await db.query.user.findFirst({
|
||||
where: eq(user.id, session.user.id),
|
||||
});
|
||||
|
||||
if (currentUser?.role !== "admin") {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
// 获取查询参数
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const page = Number.parseInt(searchParams.get("page") || "1");
|
||||
const pageSize = Number.parseInt(searchParams.get("pageSize") || "200");
|
||||
const offset = (page - 1) * pageSize;
|
||||
const search = searchParams.get("search") || "";
|
||||
const startDate = searchParams.get("startDate");
|
||||
const endDate = searchParams.get("endDate");
|
||||
|
||||
// 构建查询条件
|
||||
const imageConditions = [];
|
||||
const videoConditions = [
|
||||
eq(message.role, "assistant"),
|
||||
or(
|
||||
isNotNull(message.temporaryVideoUrl),
|
||||
isNotNull(message.permanentVideoUrl),
|
||||
sql`${message.parts}::text ILIKE '%<video%'`,
|
||||
sql`${message.parts}::text ILIKE '%.mp4%'`
|
||||
),
|
||||
];
|
||||
if (search) {
|
||||
// 搜索用户名或邮箱
|
||||
const matchingUsers = await db
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(or(
|
||||
like(user.name, `%${search}%`),
|
||||
like(user.email, `%${search}%`)
|
||||
));
|
||||
|
||||
if (matchingUsers.length > 0) {
|
||||
const matchedUserIds = matchingUsers.map((u) => u.id);
|
||||
imageConditions.push(
|
||||
sql`${generatedImage.userId} IN (${sql.join(matchedUserIds.map((id) => sql`${id}`), sql`, `)})`
|
||||
);
|
||||
videoConditions.push(
|
||||
sql`${chat.userId} IN (${sql.join(matchedUserIds.map((id) => sql`${id}`), sql`, `)})`
|
||||
);
|
||||
} else {
|
||||
// 没有匹配的用户,返回空结果
|
||||
return NextResponse.json({
|
||||
images: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (startDate) {
|
||||
const start = new Date(startDate);
|
||||
imageConditions.push(gte(generatedImage.createdAt, start));
|
||||
videoConditions.push(gte(message.createdAt, start));
|
||||
}
|
||||
|
||||
if (endDate) {
|
||||
const end = new Date(endDate);
|
||||
end.setHours(23, 59, 59, 999);
|
||||
imageConditions.push(lte(generatedImage.createdAt, end));
|
||||
videoConditions.push(lte(message.createdAt, end));
|
||||
}
|
||||
|
||||
const imageWhereClause = imageConditions.length > 0 ? and(...imageConditions) : undefined;
|
||||
const videoWhereClause = videoConditions.length > 0 ? and(...videoConditions) : undefined;
|
||||
|
||||
// 查询图片总数
|
||||
const imageCountResult = await db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(generatedImage)
|
||||
.where(imageWhereClause);
|
||||
|
||||
// 查询视频总数
|
||||
const videoCountResult = await db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(message)
|
||||
.innerJoin(chat, eq(message.chatId, chat.id))
|
||||
.where(videoWhereClause);
|
||||
|
||||
const totalImages = imageCountResult[0]?.count || 0;
|
||||
const totalVideos = videoCountResult[0]?.count || 0;
|
||||
const total = totalImages + totalVideos;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
const fetchLimit = Math.max(page * pageSize, pageSize);
|
||||
|
||||
// 查询图片列表(包含用户信息)
|
||||
const imageRows = await db
|
||||
.select({
|
||||
id: generatedImage.id,
|
||||
userId: generatedImage.userId,
|
||||
userName: user.name,
|
||||
userEmail: user.email,
|
||||
userDepartment: user.department,
|
||||
thumbnailUrl: generatedImage.thumbnailUrl,
|
||||
originalUrl: generatedImage.originalUrl,
|
||||
imageSize: generatedImage.imageSize,
|
||||
prompt: generatedImage.prompt,
|
||||
modelId: generatedImage.modelId,
|
||||
isFeatured: generatedImage.isFeatured,
|
||||
featuredCategory: generatedImage.featuredCategory,
|
||||
featuredAt: generatedImage.featuredAt,
|
||||
createdAt: generatedImage.createdAt,
|
||||
chatId: generatedImage.chatId,
|
||||
recordType: sql<"image">`'image'`,
|
||||
videoUrl: sql<string | null>`null`,
|
||||
})
|
||||
.from(generatedImage)
|
||||
.leftJoin(user, eq(generatedImage.userId, user.id))
|
||||
.where(imageWhereClause)
|
||||
.orderBy(desc(generatedImage.createdAt))
|
||||
.limit(fetchLimit);
|
||||
|
||||
// 查询视频列表(来自消息表)
|
||||
const videoRows = await db
|
||||
.select({
|
||||
id: message.id,
|
||||
userId: chat.userId,
|
||||
userName: user.name,
|
||||
userEmail: user.email,
|
||||
userDepartment: user.department,
|
||||
temporaryVideoUrl: message.temporaryVideoUrl,
|
||||
permanentVideoUrl: message.permanentVideoUrl,
|
||||
parts: message.parts,
|
||||
videoMetadata: message.videoMetadata,
|
||||
createdAt: message.createdAt,
|
||||
chatId: message.chatId,
|
||||
})
|
||||
.from(message)
|
||||
.innerJoin(chat, eq(message.chatId, chat.id))
|
||||
.leftJoin(user, eq(chat.userId, user.id))
|
||||
.where(videoWhereClause)
|
||||
.orderBy(desc(message.createdAt))
|
||||
.limit(fetchLimit);
|
||||
|
||||
const normalizedVideos = videoRows
|
||||
.map((item) => {
|
||||
const metadata = (item.videoMetadata as Record<string, any> | null) || {};
|
||||
const videoUrl =
|
||||
item.permanentVideoUrl ||
|
||||
item.temporaryVideoUrl ||
|
||||
extractVideoUrlFromParts(item.parts);
|
||||
|
||||
if (!videoUrl) return null;
|
||||
|
||||
const resolution =
|
||||
typeof metadata.resolution === "string" && metadata.resolution.trim()
|
||||
? metadata.resolution.trim()
|
||||
: null;
|
||||
const prompt =
|
||||
typeof metadata.prompt === "string" && metadata.prompt.trim()
|
||||
? metadata.prompt.trim()
|
||||
: null;
|
||||
const modelId =
|
||||
typeof metadata.model === "string" && metadata.model.trim()
|
||||
? metadata.model.trim()
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: `video-${item.id}`,
|
||||
sourceMessageId: item.id,
|
||||
userId: item.userId,
|
||||
userName: item.userName,
|
||||
userEmail: item.userEmail,
|
||||
userDepartment: item.userDepartment,
|
||||
thumbnailUrl: videoUrl,
|
||||
originalUrl: videoUrl,
|
||||
videoUrl,
|
||||
imageSize: resolution,
|
||||
prompt,
|
||||
modelId,
|
||||
isFeatured: false,
|
||||
featuredCategory: null,
|
||||
featuredAt: null,
|
||||
createdAt: item.createdAt,
|
||||
chatId: item.chatId,
|
||||
recordType: "video" as const,
|
||||
};
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
const merged = [...imageRows, ...normalizedVideos].sort(
|
||||
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
||||
);
|
||||
const images = merged.slice(offset, offset + pageSize);
|
||||
|
||||
return NextResponse.json({
|
||||
images,
|
||||
pagination: { page, pageSize, total, totalPages, totalImages, totalVideos }
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) return error.toResponse();
|
||||
console.error("[Admin Images API] GET failed", error);
|
||||
return NextResponse.json({ error: "记录加载失败,请重试" }, { status: 500 });
|
||||
console.error("[Admin Images API] Error:", error);
|
||||
return NextResponse.json({ error: "Failed to fetch images" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { requireAdmin } from "@/lib/middleware/admin";
|
||||
import { ChatSDKError } from "@/lib/errors";
|
||||
import { parseMediaQuery } from "@/lib/admin/media-records";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
await requireAdmin();
|
||||
const q = parseMediaQuery(request.nextUrl.searchParams);
|
||||
const status = request.nextUrl.searchParams.get("status") || "all";
|
||||
const filters = [sql`true`];
|
||||
if (q.search)
|
||||
filters.push(sql`(u.name ilike ${`%${q.search}%`} or u.email ilike ${`%${q.search}%`})`);
|
||||
if (["pending", "running", "failed", "succeeded"].includes(status))
|
||||
filters.push(sql`t.status=${status}`);
|
||||
if (q.startDate) filters.push(sql`t."createdAt">=${q.startDate}::date - interval '8 hours'`);
|
||||
if (q.endDate) filters.push(sql`t."createdAt"<${q.endDate}::date+interval '16 hours'`);
|
||||
const [result] = await db.execute(sql`with filtered as not materialized (
|
||||
select t.id,u.name as "userName",t.status,t."createdAt"+interval '8 hours' as "createdAt",t.error,coalesce(t.request->>'modelId',t.request->>'model') as model,
|
||||
extract(epoch from (t."completedAt"-t."startedAt"))*1000 as "elapsedMs"
|
||||
from "CanvasImageTask" t left join "User" u on u.id=t."userId" where ${sql.join(filters, sql` and `)}
|
||||
) select (select count(*)::int from filtered) as total,
|
||||
coalesce((select jsonb_agg(p) from (select * from filtered order by "createdAt" desc,id desc limit ${q.pageSize} offset ${(q.page - 1) * q.pageSize}) p),'[]'::jsonb) as tasks`);
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof ChatSDKError) return error.toResponse();
|
||||
return NextResponse.json({ error: "任务记录加载失败,请重试" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -106,22 +106,6 @@ export async function POST(request: Request) {
|
||||
? catalogPresets.filter((preset) => existingModelIds.has(preset.modelId))
|
||||
: catalogPresets;
|
||||
|
||||
if (body?.dryRun === true) {
|
||||
const catalogIds = new Set(catalogPresets.map(preset => preset.modelId));
|
||||
const fields = ["displayName", "description", "supportsVision", "supportsImageGen", "isHidden", "sortOrder", "capabilities", "defaultParams", "imageGenConfig"] as const;
|
||||
const added = presets.filter(preset => !existingModelIds.has(preset.modelId)).map(preset => ({ modelId: preset.modelId, displayName: preset.displayName }));
|
||||
const updated = presets.flatMap(preset => {
|
||||
const existing = existingModels.find(model => model.modelId === preset.modelId);
|
||||
if (!existing) return [];
|
||||
const changedFields: string[] = fields.filter(field => preset[field] !== undefined && JSON.stringify(existing[field]) !== JSON.stringify(preset[field]));
|
||||
if (existing.avatarUrl) changedFields.push("avatarUrl");
|
||||
if (requestedModelIds !== null && !existing.isEnabled) changedFields.push("isEnabled");
|
||||
return changedFields.length ? [{ modelId: preset.modelId, displayName: existing.displayName, changedFields }] : [];
|
||||
});
|
||||
const disabled = requestedModelIds === null ? existingModels.filter(model => !catalogIds.has(model.modelId) && (model.isEnabled || !model.isHidden)).map(model => ({ modelId: model.modelId, displayName: model.displayName })) : [];
|
||||
return NextResponse.json({ preview: { added, updated, disabled }, total: catalogPresets.length });
|
||||
}
|
||||
|
||||
const addedModels: AiModel[] = [];
|
||||
const updatedModels: AiModel[] = [];
|
||||
const disabledModels: AiModel[] = [];
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { canvasProject } from "@/lib/db/schema";
|
||||
@ -57,20 +56,14 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const requestedId = body.id === undefined ? undefined : z.string().uuid().safeParse(body.id);
|
||||
if (requestedId && !requestedId.success) {
|
||||
return NextResponse.json({ success: false, error: "项目编号无效" }, { status: 400 });
|
||||
}
|
||||
const id = requestedId?.data;
|
||||
const title = String(body.title || "").trim() || "未命名生图项目";
|
||||
const description = String(body.description || "").trim() || null;
|
||||
const thumbnail = String(body.thumbnail || "").trim() || null;
|
||||
const projectState = normalizeAgentGenerationProjectPersistedState(body.projectState);
|
||||
|
||||
const [insertedProject] = await db
|
||||
const [project] = await db
|
||||
.insert(canvasProject)
|
||||
.values({
|
||||
id,
|
||||
userId: session.user.id,
|
||||
title,
|
||||
description,
|
||||
@ -85,22 +78,8 @@ export async function POST(request: NextRequest) {
|
||||
agentProjectState: projectState,
|
||||
} as any,
|
||||
})
|
||||
.onConflictDoNothing({ target: canvasProject.id })
|
||||
.returning();
|
||||
|
||||
const project = insertedProject || (id ? (await db
|
||||
.select()
|
||||
.from(canvasProject)
|
||||
.where(and(
|
||||
eq(canvasProject.id, id),
|
||||
eq(canvasProject.userId, session.user.id),
|
||||
eq(canvasProject.workspaceType, "agent")
|
||||
))
|
||||
.limit(1))[0] : undefined);
|
||||
if (!project) {
|
||||
return NextResponse.json({ success: false, error: "项目编号不可用,请重试" }, { status: 409 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, data: mapAgentProjectRow(project) });
|
||||
} catch (error) {
|
||||
console.error("[AgentProjects API] 创建项目失败:", error);
|
||||
|
||||
@ -450,7 +450,7 @@ async function analyzeFunctionalShowcaseImage(params: {
|
||||
},
|
||||
],
|
||||
temperature: 0,
|
||||
maxOutputTokens: 120,
|
||||
maxTokens: 120,
|
||||
abortSignal: AbortSignal.timeout(25_000),
|
||||
} as any);
|
||||
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { resolveAgentWorkflowComposerSelections } from "@/lib/agents/workflow-composer";
|
||||
import { AGENT_WORKFLOW_UI_CONFIG_KEY, normalizeAgentWorkflowUiConfig } from "@/lib/agents/workflow-ui-config";
|
||||
import { getSystemSetting } from "@/lib/db/queries";
|
||||
|
||||
const selectionsSchema = z.record(z.string().max(160), z.string().max(8192))
|
||||
.refine((selections) => Object.keys(selections).length <= 100);
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) return Response.json({ error: "请先登录" }, { status: 401 });
|
||||
|
||||
const selections = selectionsSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!selections.success) return Response.json({ error: "风格模板选择无效" }, { status: 400 });
|
||||
|
||||
const setting = await getSystemSetting({ key: AGENT_WORKFLOW_UI_CONFIG_KEY });
|
||||
const config = normalizeAgentWorkflowUiConfig(setting?.value);
|
||||
return Response.json({ selections: resolveAgentWorkflowComposerSelections({ config, selections: selections.data }) });
|
||||
}
|
||||
@ -4,7 +4,6 @@ import { auth } from "@/app/(auth)/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { canvasImageTask, canvasProject, message } from "@/lib/db/schema";
|
||||
import { extractAgentProjectStateFromCanvasData, isAgentProjectRow } from "@/lib/agents/agent-project-compat";
|
||||
import { MAX_DETAIL_REPLACEMENT_REFERENCES } from "@/lib/agents/mode-workspace-state";
|
||||
import {
|
||||
createCanvasImageTask,
|
||||
enqueueCanvasImageTask,
|
||||
@ -147,14 +146,6 @@ export async function POST(request: Request) {
|
||||
.map((item) => [String(item.id), String(item.imageUrl)]),
|
||||
);
|
||||
const requested = Array.isArray(body.references) ? body.references : [];
|
||||
if (requested.length === 0) {
|
||||
return NextResponse.json({ error: "请先选择详情参考图" }, { status: 400 });
|
||||
}
|
||||
if (requested.length > MAX_DETAIL_REPLACEMENT_REFERENCES) {
|
||||
return NextResponse.json({
|
||||
error: `本次选中了 ${requested.length} 张详情参考图,一次最多替换 ${MAX_DETAIL_REPLACEMENT_REFERENCES} 张,请减少本次选择后重试`,
|
||||
}, { status: 400 });
|
||||
}
|
||||
const references: DetailReplacementBatchReference[] = requested.map((raw: unknown) => {
|
||||
const item = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
|
||||
return {
|
||||
@ -169,6 +160,7 @@ export async function POST(request: Request) {
|
||||
};
|
||||
});
|
||||
if (
|
||||
references.length === 0 || references.length > 40 ||
|
||||
new Set(references.map((item) => item.id)).size !== references.length ||
|
||||
references.some((item) => !item.id || knownReferences.get(item.id) !== item.imageUrl)
|
||||
) {
|
||||
@ -195,12 +187,6 @@ export async function POST(request: Request) {
|
||||
if (!model || model === "auto" || !models.some((entry) => entry.model.id === model)) {
|
||||
return NextResponse.json({ error: "详情替换模型不可用,请检查模型配置" }, { status: 400 });
|
||||
}
|
||||
if (typeof body.expectedModelId === "string" && body.expectedModelId !== model) {
|
||||
return NextResponse.json({
|
||||
code: "DETAIL_REPLACEMENT_MODEL_CHANGED",
|
||||
error: "详情替换模型已更新,请确认页面显示的模型后重新提交",
|
||||
}, { status: 409 });
|
||||
}
|
||||
const quota = await checkUserImageQuota(session.user.id);
|
||||
if (!quota.allowed) {
|
||||
return NextResponse.json({ error: "本月图片生成配额已用完" }, { status: 429 });
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export function GET() {
|
||||
return NextResponse.json({ version: process.env.NEXT_PUBLIC_APP_RELEASE || "development" }, {
|
||||
headers: { "Cache-Control": "no-store, max-age=0" },
|
||||
});
|
||||
}
|
||||
@ -1,5 +1,4 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { buildThreeAssetUrl } from "@/lib/canvas/three-asset-url";
|
||||
|
||||
@ -13,6 +12,7 @@ const ALLOWED_MODEL_HOST_DOMAINS = [
|
||||
"tripo3d.ai",
|
||||
"tripo3d.com",
|
||||
"worldlabs.ai",
|
||||
"s3.1080p.hk",
|
||||
"img.yydd.ai",
|
||||
"scqny.jiansun.vip",
|
||||
"blob.vercel-storage.com",
|
||||
@ -25,6 +25,7 @@ const ALLOWED_MODEL_HOST_DOMAINS = [
|
||||
|
||||
const ALLOWED_HTTP_MODEL_HOST_DOMAINS = [
|
||||
"bbyy.ai",
|
||||
"s3.1080p.hk",
|
||||
"img.yydd.ai",
|
||||
];
|
||||
|
||||
@ -164,9 +165,6 @@ async function handleRequest(request: Request, method: "GET" | "HEAD") {
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const rawUrl = String(searchParams.get("url") || "").trim();
|
||||
if (isRetiredStorageUrl(rawUrl)) {
|
||||
return NextResponse.json({ success: false, error: RETIRED_STORAGE_MESSAGE, code: "storage_retired" }, { status: 410 });
|
||||
}
|
||||
if (!rawUrl) {
|
||||
return NextResponse.json({ success: false, error: "缺少 url 参数" }, { status: 400 });
|
||||
}
|
||||
@ -182,18 +180,6 @@ async function handleRequest(request: Request, method: "GET" | "HEAD") {
|
||||
return NextResponse.json({ success: false, error: "仅支持 http/https 模型地址" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (normalizeLegacyAliyunStorageUrl(targetUrl.toString())) {
|
||||
try {
|
||||
const { resolveLegacyAliyunStorageUrl } = await import("@/lib/storage/image-archive-db");
|
||||
targetUrl = new URL(await resolveLegacyAliyunStorageUrl(targetUrl.toString()));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("HTTP 410")) {
|
||||
return NextResponse.json({ success: false, error: RETIRED_STORAGE_MESSAGE, code: "storage_retired" }, { status: 410 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAllowedModelHost(targetUrl.hostname)) {
|
||||
return NextResponse.json({ success: false, error: "不允许的模型地址域名" }, { status: 403 });
|
||||
}
|
||||
|
||||
@ -2,14 +2,12 @@ import { NextResponse } from "next/server";
|
||||
import { ZodError } from "zod";
|
||||
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { RmbgServiceError } from "@/lib/ai/rmbg/service";
|
||||
import { canvasCapabilityClientCommandSchema } from "@/lib/canvas/capabilities/client-command";
|
||||
import { CanvasCapabilityRuntimeError } from "@/lib/canvas/capabilities/context";
|
||||
import { getCanvasCapabilityManifest } from "@/lib/canvas/capabilities/registry";
|
||||
import { executeCanvasCapabilityRuntime } from "@/lib/canvas/capabilities/runtime";
|
||||
import { getCanvasCapabilityTask } from "@/lib/canvas/capabilities/task-store";
|
||||
import { CanvasAgentMutationError } from "@/lib/canvas/agent-mutations";
|
||||
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const maxDuration = 600;
|
||||
@ -41,8 +39,7 @@ export async function GET(
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
const failure = task.status === "failed" ? getRequestFailureDetails(task.error) : undefined;
|
||||
return NextResponse.json({ success: true, task: { ...task, failure, error: failure ? formatRequestFailure(failure, task.id) : task.error } });
|
||||
return NextResponse.json({ success: true, task });
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
@ -54,11 +51,9 @@ export async function POST(
|
||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
let requestId: string | undefined;
|
||||
try {
|
||||
const { id } = await params;
|
||||
const command = canvasCapabilityClientCommandSchema.parse(await request.json());
|
||||
requestId = command.requestId;
|
||||
const result = await executeCanvasCapabilityRuntime({
|
||||
command,
|
||||
projectId: id,
|
||||
@ -72,9 +67,8 @@ export async function POST(
|
||||
error instanceof CanvasCapabilityRuntimeError ||
|
||||
error instanceof CanvasAgentMutationError
|
||||
) {
|
||||
const failure = getRequestFailureDetails(error);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: formatRequestFailure(failure, requestId), code: error.code, failure, requestId },
|
||||
{ success: false, error: error.message, code: error.code },
|
||||
{ status: error.status }
|
||||
);
|
||||
}
|
||||
@ -88,10 +82,10 @@ export async function POST(
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const failure = getRequestFailureDetails(error, "执行画布能力失败");
|
||||
const message = error instanceof Error ? error.message : "执行画布能力失败";
|
||||
return NextResponse.json(
|
||||
{ success: false, error: formatRequestFailure(failure, requestId), failure, requestId },
|
||||
{ status: error instanceof RmbgServiceError ? error.status : 500 }
|
||||
{ success: false, error: message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -207,11 +207,7 @@ export async function PUT(
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: saved,
|
||||
previousCanvasRevision: existingProject?.updatedAt.toISOString() ?? null,
|
||||
});
|
||||
return NextResponse.json({ success: true, data: saved });
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("更新/创建画布失败:", error);
|
||||
|
||||
@ -329,7 +329,6 @@ export async function POST(request: Request) {
|
||||
withModel,
|
||||
imageSize: snapshot.imagePreferences?.parameters?.imageSize,
|
||||
imagePreferences: snapshot.imagePreferences,
|
||||
priorCalls: snapshot.calls,
|
||||
preferredModelId: snapshot.imagePreferences?.modelId || (preset?.type === "image" ? preset.defaultModelId || undefined : undefined),
|
||||
operationSelectedNodeIds: selectedNodeIds,
|
||||
objective: [snapshot.objective, ...snapshot.inputs.map((input) => input.text)].join(
|
||||
|
||||
@ -9,10 +9,10 @@ export async function GET() {
|
||||
const models = await listCanvasAudioModels();
|
||||
return NextResponse.json(
|
||||
{
|
||||
models: models.map(({ model, provider }) => ({
|
||||
models: models.map(({ model }) => ({
|
||||
id: model.id,
|
||||
modelId: model.modelId,
|
||||
name: `${model.displayName} · ${provider.type === "vip98k" ? "98K" : "阿里云"}`,
|
||||
name: model.displayName,
|
||||
...audioContract(model.modelId),
|
||||
})),
|
||||
},
|
||||
|
||||
@ -1,15 +1,100 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { executeBoxCutoutPOST } from "@/lib/canvas/operations/box-cutout";
|
||||
import {
|
||||
BoxCutoutServiceError,
|
||||
executeBoxCutoutJob,
|
||||
} from "@/lib/ai/box-cutout/service";
|
||||
import { RmbgServiceError } from "@/lib/ai/rmbg/service";
|
||||
import { getPointsSystemConfig } from "@/lib/db/queries";
|
||||
import { prepareFeaturePointsCharge } from "@/lib/points/feature-charge";
|
||||
import { getImageToolCreditCost } from "@/lib/points/config";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 60;
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ success: false, error: "未授权,请先登录" }, { status: 401 });
|
||||
type BoxCutoutRequest = {
|
||||
imageUrl?: string;
|
||||
cropRect?: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
paddingRatio?: number;
|
||||
prompt?: string;
|
||||
chatId?: string | null;
|
||||
messageId?: string | null;
|
||||
skipGallerySave?: boolean;
|
||||
sourceNodeId?: string;
|
||||
};
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ success: false, error: "未授权,请先登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = (await request.json()) as BoxCutoutRequest;
|
||||
const rawImageUrl = String(body.imageUrl || "").trim();
|
||||
if (!rawImageUrl) {
|
||||
return NextResponse.json({ success: false, error: "缺少 imageUrl 参数" }, { status: 400 });
|
||||
}
|
||||
|
||||
const resolvedImageUrl = new URL(rawImageUrl, request.url).toString();
|
||||
const pointsConfig = await getPointsSystemConfig();
|
||||
const pointsCharge = await prepareFeaturePointsCharge({
|
||||
userId: session.user.id,
|
||||
unitCost: getImageToolCreditCost(pointsConfig, "box-cutout"),
|
||||
reason: "image_box_cutout",
|
||||
modelId: "box-cutout",
|
||||
note: "框选抠图消耗积分",
|
||||
pointsConfig,
|
||||
});
|
||||
if (!pointsCharge.ok) {
|
||||
return NextResponse.json(pointsCharge.payload, { status: pointsCharge.status });
|
||||
}
|
||||
|
||||
const result = await executeBoxCutoutJob({
|
||||
userId: session.user.id,
|
||||
imageUrl: resolvedImageUrl,
|
||||
cropRect: body.cropRect || {},
|
||||
paddingRatio: body.paddingRatio,
|
||||
prompt: body.prompt || "框选抠图",
|
||||
chatId: body.chatId || null,
|
||||
messageId: body.messageId || null,
|
||||
skipGallerySave: body.skipGallerySave === true,
|
||||
sourceNodeId: body.sourceNodeId,
|
||||
});
|
||||
|
||||
if (pointsCharge.chargeable) {
|
||||
try {
|
||||
await pointsCharge.consume();
|
||||
} catch (pointsError) {
|
||||
console.error("[Points] Failed to consume box cutout points:", pointsError);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof BoxCutoutServiceError || error instanceof RmbgServiceError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error.detail || error.message,
|
||||
},
|
||||
{ status: error.status },
|
||||
);
|
||||
}
|
||||
|
||||
console.error("[BoxCutout] 处理失败:", error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "框选抠图失败",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
return executeBoxCutoutPOST(request, session.user.id);
|
||||
}
|
||||
|
||||
@ -1804,7 +1804,7 @@ async function runDualDirectorPlanPreflight(params: {
|
||||
? "You are both an art director and a marketing director for high-conversion e-commerce detail pages. Output JSON only."
|
||||
: "你同时扮演高转化电商详情页的平面设计总监与营销总监。仅输出JSON。",
|
||||
temperature: params.isLocalMoonshot ? 1 : 0.1,
|
||||
maxOutputTokens: 2000,
|
||||
maxTokens: 2000,
|
||||
...(params.kimiOptions || {}),
|
||||
}, params.timeoutMs || DETAIL_PLAN_PREFLIGHT_TIMEOUT_MS);
|
||||
|
||||
@ -2040,7 +2040,7 @@ export async function POST(request: Request) {
|
||||
kimiDetailProfile: plannerKimiOptions.headers
|
||||
? {
|
||||
thinking: plannerKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
||||
maxOutputTokens: plannerKimiOptions.maxOutputTokens,
|
||||
maxTokens: plannerKimiOptions.maxTokens,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
@ -2177,7 +2177,7 @@ export async function POST(request: Request) {
|
||||
`{"summary":"简述","globalStyle":{"designLanguage":"一句话风格方向","typography":{"fontFamily":"字体家族","title":"主标题规范","subtitle":"副标题规范","body":"正文规范"},"layout":{"grid":"栅格","safeArea":"安全区","rhythm":"留白节奏"},"palette":"配色规范"},"screens":[{"index":1,"screenType":"B","objective":"本屏目标","title":"首屏示例:甩甩杆,自拍不手抖(6-20字)","subtitle":"一句副标题","copy":"正文文案","layoutNote":"排版说明","useModel":false,"modelReason":"是否需要人物及原因","bundleShowcase":false,"bundleReason":"是否为搭配展示页及原因","fabe":{"b":"利益","f":"特征","a":"优势","e":"证据"},"visualPrompt":"用于生图的完整提示词,必须包含790x1300与统一字体排版"}],"dslV2Screens":[{"version":"detail-ui-dsl/v2","screenIndex":1,"layoutVariant":"hero-left-panel","region":{"x":0.06,"y":0.05,"width":0.88,"height":0.46},"nodes":[{"kind":"panel","id":"hero-panel","variant":"glass","tone":"light","direction":"column","gap":18,"children":[{"kind":"badge","id":"screen-badge","icon":"sparkle","text":"核心升级","tone":"primary"},{"kind":"heading","id":"hero-title","text":"护腰椅,久坐不腰酸","level":1,"emphasis":"hero"},{"kind":"body","id":"hero-subtitle","text":"在家里加班,也能护腰/舒适","emphasis":"strong"}]}]}]}`,
|
||||
temperature: 0.25,
|
||||
...(localDetailAgentResolved ? { temperature: 1 } : {}),
|
||||
maxOutputTokens: 1800,
|
||||
maxTokens: 1800,
|
||||
...plannerKimiOptions,
|
||||
});
|
||||
|
||||
|
||||
@ -323,7 +323,7 @@ export async function POST(request: Request) {
|
||||
kimiDetailProfile: reviewKimiOptions.headers
|
||||
? {
|
||||
thinking: reviewKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
||||
maxOutputTokens: reviewKimiOptions.maxOutputTokens,
|
||||
maxTokens: reviewKimiOptions.maxTokens,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
@ -438,7 +438,7 @@ export async function POST(request: Request) {
|
||||
? "You are both an Art Director and a Marketing Director for high-conversion e-commerce detail pages. Evaluate with strict professional standards and output JSON only."
|
||||
: "你同时是高转化电商详情页的平面设计总监与营销总监。按严格专业标准评估,仅输出JSON。",
|
||||
temperature: localDetailAgentResolved ? 1 : 0.1,
|
||||
maxOutputTokens: 800,
|
||||
maxTokens: 800,
|
||||
...reviewKimiOptions,
|
||||
} as any);
|
||||
text = String(result?.text || "");
|
||||
|
||||
@ -1,9 +1,5 @@
|
||||
import { resolveCanvasCdnDownload } from "@/lib/storage/canvas-cdn-download";
|
||||
import { isRetiredStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
import { scheduleImageDownloadPreparation } from "@/lib/storage/image-download-preparation";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { formatDownloadFailure, getDownloadFailure, type DownloadFailure } from "@/lib/canvas/download-error";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { prepareImageArchiveDownload } from "@/lib/storage/image-download-preparation";
|
||||
import { after, NextRequest, NextResponse } from "next/server";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getDownloadPreparationQueue, type DownloadPreparationInput } from "@/lib/canvas/download-preparation";
|
||||
@ -16,23 +12,6 @@ import {
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 120;
|
||||
const logger = createLogger("canvas.download");
|
||||
|
||||
function failed(failure: DownloadFailure, requestId: string) {
|
||||
logger.warn("request_failed", { requestId, code: failure.code, status: failure.status });
|
||||
return NextResponse.json({ success: false, error: formatDownloadFailure(failure, requestId), failure, requestId }, {
|
||||
status: failure.status,
|
||||
headers: { "Cache-Control": "no-store", ...(failure.status === 429 ? { "Retry-After": "3" } : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
function preparing(requestId: string, converting = false) {
|
||||
return NextResponse.json({ delivery: "preparing", retryAfter: 2, requestId,
|
||||
phase: converting ? "converting" : "preparing",
|
||||
message: converting ? "正在转换为兼容 PNG 并保存,完成后自动下载" : "正在准备原图,完成后将自动开始下载" }, {
|
||||
status: 202, headers: { "Retry-After": "2", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
async function prepareDownload(input: DownloadPreparationInput, signal: AbortSignal) {
|
||||
// A proxy candidate for the same original must not repeat the same slow
|
||||
@ -41,25 +20,22 @@ async function prepareDownload(input: DownloadPreparationInput, signal: AbortSig
|
||||
const source = extractImageProxySourceUrl(url) || url;
|
||||
return inferOriginalImageUrl(source) || source;
|
||||
}))];
|
||||
let lastError: unknown;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
signal.throwIfAborted();
|
||||
for (const url of sources) {
|
||||
signal.throwIfAborted();
|
||||
const result = await fetchCanvasDownloadAsset({
|
||||
file: { url, name: "original" }, index: 0,
|
||||
requestOrigin: input.requestOrigin, cookie: input.cookie,
|
||||
includeSequencePrefix: false, timeoutMs: 60_000, retryCount: 1, signal,
|
||||
includeSequencePrefix: false, timeoutMs: 12_000, retryCount: 1, signal,
|
||||
});
|
||||
if (result.ok) return { buffer: result.bytes, contentType: result.contentType };
|
||||
lastError = result.error;
|
||||
}
|
||||
// Each pass resolves the latest archive URL inside fetchCanvasDownloadAsset.
|
||||
// No AI/model request is involved and a completed source fetch is shared.
|
||||
if (attempt < 1 && getDownloadFailure(lastError).retryable) await new Promise(resolve => setTimeout(resolve, 1_000));
|
||||
else break;
|
||||
if (attempt < 2) await new Promise(resolve => setTimeout(resolve, 1_000));
|
||||
}
|
||||
throw new Error(String(lastError || "Original image sources unavailable"));
|
||||
throw new Error("Original image sources unavailable");
|
||||
}
|
||||
|
||||
function getRequestOrigin(request: NextRequest): string {
|
||||
@ -99,44 +75,28 @@ function resolveDownloadUrls(body: Record<string, unknown>, origin: string): str
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const requestId = randomUUID();
|
||||
try {
|
||||
const session = await auth();
|
||||
if (!session?.user?.id) {
|
||||
return failed(getDownloadFailure("未登录"), requestId);
|
||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
const requestOrigin = getRequestOrigin(request);
|
||||
const candidates = resolveDownloadUrls(body, requestOrigin);
|
||||
if (candidates.length && candidates.every(isRetiredStorageUrl)) {
|
||||
return failed(getDownloadFailure(RETIRED_STORAGE_MESSAGE), requestId);
|
||||
}
|
||||
const urls = candidates.filter(url => !isRetiredStorageUrl(url));
|
||||
const urls = resolveDownloadUrls(body, requestOrigin);
|
||||
const requestedUrls = [...urls];
|
||||
if (urls.length === 0) {
|
||||
return failed(getDownloadFailure("图片地址无效"), requestId);
|
||||
return NextResponse.json({ success: false, error: "图片地址无效" }, { status: 400 });
|
||||
}
|
||||
|
||||
const name = sanitizeCanvasDownloadFileName(String(body.name || ""), "canvas-image");
|
||||
if (body.preferDirect === true) {
|
||||
const { task, direct, canPrepareDirect } = await resolveCanvasCdnDownload(urls, `${name}.png`);
|
||||
const { task, direct } = await resolveCanvasCdnDownload(urls, `${name}.png`).catch(() => ({ task: null, direct: null }));
|
||||
if (direct) return NextResponse.json(direct, { headers: { "Cache-Control": "no-store" } });
|
||||
if (task && canPrepareDirect) {
|
||||
const asset = (task.metadata as { downloadAsset?: { status?: string; failure?: DownloadFailure; retryAt?: string } } | null)?.downloadAsset;
|
||||
if (asset?.status === "abandoned" || (asset?.status === "failed" && Date.parse(asset.retryAt || "") > Date.now())) {
|
||||
return failed(asset.failure || getDownloadFailure(null), task.id);
|
||||
}
|
||||
scheduleImageDownloadPreparation(task.id);
|
||||
return preparing(task.id, true);
|
||||
if (task?.targetUrl) {
|
||||
if (!urls.includes(task.targetUrl)) urls.unshift(task.targetUrl);
|
||||
after(() => prepareImageArchiveDownload(task.id));
|
||||
}
|
||||
if (task && !task.targetUrl) {
|
||||
const { originalImagePreparing, prepareOriginalImageArchive } = await import("@/lib/storage/original-image-download");
|
||||
const pending = await prepareOriginalImageArchive(task.sourceUrl);
|
||||
return NextResponse.json(originalImagePreparing(pending), { status: 202,
|
||||
headers: { "Retry-After": "3", "Cache-Control": "no-store" } });
|
||||
}
|
||||
throw new Error("下载文件暂时无法从存储桶直接下载");
|
||||
}
|
||||
const cookie = request.headers.get("cookie") || "";
|
||||
if (body.preparation === "async") {
|
||||
@ -144,10 +104,13 @@ export async function POST(request: NextRequest) {
|
||||
userId: session.user.id, urls: requestedUrls, requestOrigin, cookie,
|
||||
});
|
||||
if (result.status === "preparing") {
|
||||
return preparing(result.requestId);
|
||||
return NextResponse.json({ delivery: "preparing", retryAfter: 3,
|
||||
message: "正在准备原图,完成后将自动下载" }, {
|
||||
status: 202, headers: { "Retry-After": "3", "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
if (result.status === "failed") {
|
||||
return failed(result.failure, result.requestId);
|
||||
return NextResponse.json({ success: false, error: result.error }, { status: 502 });
|
||||
}
|
||||
return new NextResponse(new Uint8Array(result.asset.buffer), { headers: {
|
||||
"Content-Type": result.asset.contentType,
|
||||
@ -168,14 +131,17 @@ export async function POST(request: NextRequest) {
|
||||
includeSequencePrefix: false,
|
||||
});
|
||||
if (result.ok) break;
|
||||
failures.push(result.error);
|
||||
failures.push(`${url}: ${result.error}`);
|
||||
}
|
||||
|
||||
if (!result?.ok) {
|
||||
if (failures.length > 0) {
|
||||
logger.warn("all_sources_failed", { requestId, failures });
|
||||
console.warn("[CanvasDownloadImage] All candidates failed:", failures);
|
||||
}
|
||||
return failed(getDownloadFailure(result?.error), requestId);
|
||||
return NextResponse.json(
|
||||
{ success: false, error: result?.error || "图片源文件暂时不可访问" },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
return new NextResponse(result.bytes, {
|
||||
@ -188,7 +154,7 @@ export async function POST(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("download_failed", error, { requestId });
|
||||
return failed(getDownloadFailure(error), requestId);
|
||||
console.error("[CanvasDownloadImage] Failed:", error);
|
||||
return NextResponse.json({ success: false, error: "图片下载失败" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,13 +10,11 @@ import JSZip from "jszip";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { fetchCanvasDownloadAsset } from "@/lib/canvas/photoshop-safe-download";
|
||||
import { publishCanvasZip } from "@/lib/storage/canvas-zip-delivery";
|
||||
import { trackRuntimeWork } from "@/lib/observability/active-work";
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 300;
|
||||
type DownloadFileItem = { url: string; name?: string };
|
||||
const MAX_DOWNLOAD_FILES = 200;
|
||||
const TASK_TTL_MS = 24 * 60 * 60_000;
|
||||
const PREPARATION_TTL_MS = 6 * 60 * 60_000;
|
||||
const TASK_TTL_MS = 60 * 60_000;
|
||||
const running = (globalThis as typeof globalThis & { __canvasZipRunning?: Set<string> });
|
||||
const active = running.__canvasZipRunning ??= new Set<string>();
|
||||
function sanitizeFolderName(value: string): string {
|
||||
@ -100,71 +98,63 @@ async function processTask(id: string, userId: string, requestOrigin: string, co
|
||||
task = await loadZipTask(id, userId);
|
||||
if (!task || task.status === "completed" || task.status === "failed") return;
|
||||
await assertZipDiskSpace();
|
||||
const existingZip = task.zipFile && task.contentDisposition && await stat(task.zipFile.path).catch(() => null);
|
||||
const reuseZip = existingZip && existingZip.size === task.zipFile!.bytes;
|
||||
task.status = "running"; task.stage = reuseZip ? "正在准备加速下载" : "正在准备原图"; task.updatedAt = Date.now();
|
||||
task.status = "running"; task.stage = "正在准备原图"; task.updatedAt = Date.now();
|
||||
await saveZipTask(task);
|
||||
if (!reuseZip) {
|
||||
delete task.zipFile; delete task.contentDisposition; delete task.cdnUrl;
|
||||
// Stage each image on disk, not all PNG buffers in the web process heap.
|
||||
// A restart resumes from these files using the current owner's session.
|
||||
let cursor = 0;
|
||||
let writes = Promise.resolve();
|
||||
const persist = () => { const current = task!; writes = writes.then(() => saveZipTask(current)); return writes; };
|
||||
const results = await Promise.allSettled(Array.from({ length: Math.min(2, task.files.length) }, async () => {
|
||||
while (cursor < task!.files.length) {
|
||||
const index = cursor++; const file = task!.files[index];
|
||||
const path = join(zipTaskPath(id), `${index}.image`);
|
||||
if (file.prepared && file.filename && (await stat(path).catch(() => null))?.size) continue;
|
||||
delete file.prepared; delete file.filename;
|
||||
const result = await fetchCanvasDownloadAsset({ file, index, requestOrigin, cookie,
|
||||
signal: AbortSignal.timeout(120_000) }).catch(() => ({ ok: false as const, error: "原图读取超时或源地址暂时不可用" }));
|
||||
if (result.ok) {
|
||||
await assertZipDiskSpace(result.bytes.length);
|
||||
await writeFile(path, result.bytes, { mode: 0o600 });
|
||||
file.prepared = `${index}.image`; file.filename = result.filename; delete file.error;
|
||||
} else file.error = result.error;
|
||||
task!.processedCount = task!.files.filter(f => f.prepared || f.error).length;
|
||||
task!.successCount = task!.files.filter(f => f.prepared).length;
|
||||
task!.failedCount = task!.files.filter(f => f.error).length;
|
||||
task!.stage = `正在准备原图 ${task!.processedCount}/${task!.totalCount}`;
|
||||
task!.updatedAt = Date.now(); await persist();
|
||||
}
|
||||
}));
|
||||
const rejected = results.find(result => result.status === "rejected");
|
||||
if (rejected?.status === "rejected") throw rejected.reason;
|
||||
if (!task.successCount) throw new Error("所选原图暂时都无法读取,请稍后重试;画布图片不会被删除");
|
||||
const zip = new JSZip(); const folder = zip.folder(task.folderName) || zip;
|
||||
for (const file of task.files) if (file.prepared && file.filename)
|
||||
folder.file(file.filename, createReadStream(join(zipTaskPath(id), file.prepared))
|
||||
.once("close", () => { void rm(join(zipTaskPath(id), file.prepared!), { force: true }).catch(() => undefined); }));
|
||||
if (task.failedCount) folder.file("_download-failures.txt", task.files.filter(f => f.error)
|
||||
.map(f => `${f.name || "图片"}:${f.error}`).join("\n"));
|
||||
task.stage = "正在生成完整 ZIP 文件"; await saveZipTask(task);
|
||||
task.zipFile = await writeDownloadZip(zip, task.id, percent => { task!.compressPercent = percent; });
|
||||
task.contentDisposition = buildContentDisposition(task.folderName);
|
||||
}
|
||||
// Stage each image on disk, not all PNG buffers in the web process heap.
|
||||
// A restart resumes from these files using the current owner's session.
|
||||
let cursor = 0;
|
||||
let writes = Promise.resolve();
|
||||
const persist = () => { const current = task!; writes = writes.then(() => saveZipTask(current)); return writes; };
|
||||
const results = await Promise.allSettled(Array.from({ length: Math.min(2, task.files.length) }, async () => {
|
||||
while (cursor < task!.files.length) {
|
||||
const index = cursor++; const file = task!.files[index];
|
||||
const path = join(zipTaskPath(id), `${index}.image`);
|
||||
if (file.prepared && file.filename && (await stat(path).catch(() => null))?.size) continue;
|
||||
delete file.prepared; delete file.filename;
|
||||
const result = await fetchCanvasDownloadAsset({ file, index, requestOrigin, cookie,
|
||||
signal: AbortSignal.timeout(120_000) }).catch(() => ({ ok: false as const, error: "原图读取超时或源地址暂时不可用" }));
|
||||
if (result.ok) {
|
||||
await assertZipDiskSpace(result.bytes.length);
|
||||
await writeFile(path, result.bytes, { mode: 0o600 });
|
||||
file.prepared = `${index}.image`; file.filename = result.filename; delete file.error;
|
||||
} else file.error = result.error;
|
||||
task!.processedCount = task!.files.filter(f => f.prepared || f.error).length;
|
||||
task!.successCount = task!.files.filter(f => f.prepared).length;
|
||||
task!.failedCount = task!.files.filter(f => f.error).length;
|
||||
task!.stage = `正在准备原图 ${task!.processedCount}/${task!.totalCount}`;
|
||||
task!.updatedAt = Date.now(); await persist();
|
||||
}
|
||||
}));
|
||||
const rejected = results.find(result => result.status === "rejected");
|
||||
if (rejected?.status === "rejected") throw rejected.reason;
|
||||
if (!task.successCount) throw new Error("所选原图暂时都无法读取,请稍后重试;画布图片不会被删除");
|
||||
const zip = new JSZip(); const folder = zip.folder(task.folderName) || zip;
|
||||
for (const file of task.files) if (file.prepared && file.filename)
|
||||
folder.file(file.filename, createReadStream(join(zipTaskPath(id), file.prepared))
|
||||
.once("close", () => { void rm(join(zipTaskPath(id), file.prepared!), { force: true }).catch(() => undefined); }));
|
||||
if (task.failedCount) folder.file("_download-failures.txt", task.files.filter(f => f.error)
|
||||
.map(f => `${f.name || "图片"}:${f.error}`).join("\n"));
|
||||
task.stage = "正在生成完整 ZIP 文件"; await saveZipTask(task);
|
||||
task.zipFile = await writeDownloadZip(zip, task.id, percent => { task!.compressPercent = percent; });
|
||||
task.contentDisposition = buildContentDisposition(task.folderName);
|
||||
task.stage = "正在准备下载链接"; await saveZipTask(task);
|
||||
const cdn = await publishCanvasZip({ id: task.id, ...task.zipFile!, disposition: task.contentDisposition!,
|
||||
onProgress: async bytes => {
|
||||
task!.stage = `正在传送至七牛 ${Math.round(bytes / task!.zipFile!.bytes * 100)}%`;
|
||||
task!.updatedAt = Date.now(); await saveZipTask(task!);
|
||||
} });
|
||||
if (cdn) {
|
||||
task.cdnObject = { storageConfigId: cdn.storageConfigId, key: cdn.key };
|
||||
if (!cdn.url) throw new Error(cdn.error || `ZIP 已打包,但加速下载未就绪,请再次点击下载继续传送原 ZIP。下载编号:${task.id}`);
|
||||
task.cdnUrl = cdn.url;
|
||||
}
|
||||
try {
|
||||
const cdn = await publishCanvasZip({ id: task.id, ...task.zipFile, disposition: task.contentDisposition });
|
||||
if (cdn) {
|
||||
task.cdnObject = { storageConfigId: cdn.storageConfigId, key: cdn.key };
|
||||
if (cdn.url) task.cdnUrl = cdn.url;
|
||||
}
|
||||
} catch { console.warn("[CanvasDownloadZipTask] CDN delivery unavailable; complete local ZIP retained", { taskId: id }); }
|
||||
task.status = "completed"; task.stage = task.failedCount ? `已打包 ${task.successCount} 张,${task.failedCount} 张未能读取` : "打包完成";
|
||||
task.compressPercent = 100; task.updatedAt = Date.now(); task.expiresAt = Date.now() + TASK_TTL_MS;
|
||||
await saveZipTask(task);
|
||||
// The complete ZIP is enough for retries; release staged duplicate bytes.
|
||||
await Promise.all(task.files.filter(f => f.prepared).map(f => rm(join(zipTaskPath(id), f.prepared!), { force: true }).catch(() => undefined)));
|
||||
console.info("[CanvasDownloadZipTask] Complete", { taskId: id, count: task.successCount, failed: task.failedCount,
|
||||
bytes: task.zipFile!.bytes, delivery: task.cdnUrl ? "cdn" : "local" });
|
||||
bytes: task.zipFile.bytes, delivery: task.cdnUrl ? "cdn" : "local" });
|
||||
} catch (error) {
|
||||
if (task) {
|
||||
task.status = "failed"; task.stage = task.zipFile ? "ZIP 已打包,加速下载未就绪" : "打包未完成";
|
||||
task.status = "failed"; task.stage = "打包未完成";
|
||||
task.error = error instanceof Error ? error.message : "打包失败,请稍后重试";
|
||||
task.updatedAt = Date.now(); task.expiresAt = Date.now() + TASK_TTL_MS; await saveZipTask(task).catch(() => undefined);
|
||||
}
|
||||
@ -172,7 +162,7 @@ async function processTask(id: string, userId: string, requestOrigin: string, co
|
||||
} finally { await release?.().catch(() => undefined); active.delete(id); }
|
||||
}
|
||||
function schedule(task: ZipTask, request: NextRequest) {
|
||||
const run = () => trackRuntimeWork(() => processTask(task.id, task.userId, getRequestOrigin(request), request.headers.get("cookie") || ""));
|
||||
const run = () => processTask(task.id, task.userId, getRequestOrigin(request), request.headers.get("cookie") || "");
|
||||
after(run);
|
||||
}
|
||||
export async function POST(request: NextRequest) {
|
||||
@ -197,17 +187,14 @@ export async function POST(request: NextRequest) {
|
||||
const now = Date.now();
|
||||
task = { id, userId: session.user.id, folderName: sanitizeFolderName(String(body.folderName || "")), files,
|
||||
totalCount: files.length, processedCount: 0, successCount: 0, failedCount: 0, compressPercent: 0,
|
||||
status: "pending", stage: "等待后台准备", createdAt: now, updatedAt: now, expiresAt: now + PREPARATION_TTL_MS };
|
||||
status: "pending", stage: "等待后台准备", createdAt: now, updatedAt: now, expiresAt: now + 6 * TASK_TTL_MS };
|
||||
await saveZipTask(task);
|
||||
} else if ((task.status === "failed" || task.status === "completed" && task.cdnObject && !task.cdnUrl) && body.retry === true) {
|
||||
} else if (task.status === "failed" && body.retry === true) {
|
||||
task.status = "pending"; task.error = undefined;
|
||||
await assertZipTaskCapacity(session.user.id);
|
||||
if (!task.zipFile) {
|
||||
for (const file of task.files) delete file.error;
|
||||
task.processedCount = task.successCount = task.files.filter(file => file.prepared).length;
|
||||
task.failedCount = 0;
|
||||
}
|
||||
task.updatedAt = Date.now(); task.expiresAt = Date.now() + PREPARATION_TTL_MS;
|
||||
for (const file of task.files) delete file.error;
|
||||
task.processedCount = task.successCount = task.files.filter(file => file.prepared).length;
|
||||
task.failedCount = 0; task.updatedAt = Date.now(); task.expiresAt = Date.now() + 6 * TASK_TTL_MS;
|
||||
await saveZipTask(task);
|
||||
}
|
||||
if (task.status === "pending" || task.status === "running") schedule(task, request);
|
||||
|
||||
@ -2,7 +2,6 @@ import { executeCanvasImageResponse } from "@/lib/canvas/generate-image-response
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getCanvasImageTaskForUser } from "@/lib/canvas/image-task-queue";
|
||||
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
|
||||
|
||||
export const maxDuration = 1200;
|
||||
|
||||
@ -24,15 +23,13 @@ export async function GET(request: Request) {
|
||||
return NextResponse.json({ success: false, error: "任务不存在" }, { status: 404 });
|
||||
}
|
||||
|
||||
const failure = task.status === "failed" ? getRequestFailureDetails(task.error) : undefined;
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
task: {
|
||||
id: task.id,
|
||||
status: task.status,
|
||||
attempts: task.attempts,
|
||||
error: failure ? formatRequestFailure(failure, task.id) : null,
|
||||
failure,
|
||||
error: task.error || null,
|
||||
result: task.result || null,
|
||||
createdAt: task.createdAt,
|
||||
startedAt: task.startedAt,
|
||||
|
||||
@ -976,8 +976,7 @@ export async function POST(request: NextRequest) {
|
||||
const annotatedFilename = `canvas-local-edit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`;
|
||||
const annotatedUpload = await uploadFile(
|
||||
annotatedFilename,
|
||||
toArrayBuffer(annotatedBuffer),
|
||||
{ preferQiniuForm: true }
|
||||
toArrayBuffer(annotatedBuffer)
|
||||
);
|
||||
const prompt = buildLocalEditPrompt(regions);
|
||||
const manualRegionReferenceImageUrls = regions.flatMap((region) =>
|
||||
|
||||
@ -1,11 +1,7 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { callQwen3Vl } from "@/lib/ai/qwen3-vl";
|
||||
import { executeConfiguredVip98kTask, getVip98kRuntimeProviders } from "@/lib/ai/vip98k-runtime";
|
||||
import { db } from "@/lib/db";
|
||||
import { aiModel } from "@/lib/db/schema";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import sharp from "sharp";
|
||||
|
||||
@ -94,39 +90,6 @@ function fallbackItemsFromRaw(raw: string): OcrItem[] {
|
||||
}));
|
||||
}
|
||||
|
||||
async function detectTextWithVip98k(imageUrl: string): Promise<OcrItem[] | null> {
|
||||
const providers = await getVip98kRuntimeProviders();
|
||||
if (!providers.length) return null;
|
||||
|
||||
const model = await db.query.aiModel.findFirst({
|
||||
columns: { providerId: true },
|
||||
where: and(
|
||||
inArray(aiModel.providerId, providers.map(({ id }) => id)),
|
||||
eq(aiModel.modelId, "ocr"),
|
||||
eq(aiModel.isEnabled, true),
|
||||
),
|
||||
});
|
||||
if (!model) return null;
|
||||
|
||||
const result = await executeConfiguredVip98kTask({
|
||||
modelId: "ocr",
|
||||
kind: "image-tool",
|
||||
imageUrls: [imageUrl],
|
||||
preferredProviderId: model.providerId,
|
||||
});
|
||||
const textUrl = result.outputUrls[0];
|
||||
if (!textUrl) throw new Error("98K 文字识别未返回文本文件");
|
||||
|
||||
const response = await fetch(textUrl, { signal: AbortSignal.timeout(15_000) });
|
||||
const type = response.headers.get("content-type") || "";
|
||||
if (!response.ok || !/^(?:text\/plain|application\/octet-stream)(?:;|$)/i.test(type)) {
|
||||
await response.body?.cancel();
|
||||
throw new Error(`无法读取 98K 文字识别结果(HTTP ${response.status})`);
|
||||
}
|
||||
return (await response.text()).split(/\r\n?|\n/).map((line) => line.trim())
|
||||
.filter(Boolean).slice(0, 50).map((text, index) => ({ id: String(index + 1), text }));
|
||||
}
|
||||
|
||||
function shouldUseDataUrlFallback(error: unknown) {
|
||||
const message =
|
||||
error instanceof Error ? error.message.toLowerCase() : String(error || "").toLowerCase();
|
||||
@ -184,11 +147,6 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ success: false, error: "仅支持 URL 图片,不允许 base64 传输" }, { status: 400 });
|
||||
}
|
||||
|
||||
const detected = await detectTextWithVip98k(imageUrl);
|
||||
if (detected !== null) {
|
||||
return NextResponse.json({ success: true, data: { items: detected, model: "ocr" } });
|
||||
}
|
||||
|
||||
logger.debug("model_selected", { model: "qwen3-vl" });
|
||||
const prompt = [
|
||||
"你是图片文字识别助手。",
|
||||
@ -233,9 +191,15 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
const parsedJson = parseJsonText(text || "");
|
||||
const items = Array.isArray(parsedJson?.items)
|
||||
? sanitizeItems(parsedJson.items)
|
||||
: fallbackItemsFromRaw(text);
|
||||
let items: OcrItem[] = [];
|
||||
|
||||
if (parsedJson && Array.isArray(parsedJson.items)) {
|
||||
items = sanitizeItems(parsedJson.items);
|
||||
}
|
||||
|
||||
if (items.length === 0 && text) {
|
||||
items = fallbackItemsFromRaw(text);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
@ -249,7 +213,7 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "图片文字识别暂不可用,请稍后重试",
|
||||
error: error instanceof Error ? error.message : "文字识别失败",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { db } from "@/lib/db";
|
||||
import { generatedImage, user, aiModel } from "@/lib/db/schema";
|
||||
import { and, eq, desc, sql } from "drizzle-orm";
|
||||
import { isRetiredStorageUrl, RETIRED_STORAGE_URL_PATTERN } from "@/lib/storage/retired-storage";
|
||||
import { eq, desc, sql } from "drizzle-orm";
|
||||
import { cachedPublicJson } from "@/lib/public-api/performance";
|
||||
|
||||
const FEATURED_TIMEOUT_MS = 1800;
|
||||
@ -58,17 +57,13 @@ export async function GET(request: NextRequest) {
|
||||
userName: user.name,
|
||||
userEmail: user.email,
|
||||
userDepartment: user.department,
|
||||
modelName: sql<string | null>`(select ${aiModel.displayName} from ${aiModel}
|
||||
where ${aiModel.modelId} = ${generatedImage.modelId}
|
||||
order by ${aiModel.isEnabled} desc, ${aiModel.createdAt} desc, ${aiModel.id} asc limit 1)`,
|
||||
modelName: aiModel.displayName,
|
||||
totalCount: sql<number>`count(*) over()::int`,
|
||||
})
|
||||
.from(generatedImage)
|
||||
.leftJoin(user, eq(generatedImage.userId, user.id))
|
||||
.where(and(
|
||||
eq(generatedImage.isFeatured, true),
|
||||
sql`${generatedImage.originalUrl} !~* ${RETIRED_STORAGE_URL_PATTERN}`,
|
||||
))
|
||||
.leftJoin(aiModel, eq(generatedImage.modelId, aiModel.modelId))
|
||||
.where(eq(generatedImage.isFeatured, true))
|
||||
.orderBy(desc(generatedImage.featuredAt))
|
||||
.limit(pageSize)
|
||||
.offset(offset);
|
||||
@ -79,7 +74,7 @@ export async function GET(request: NextRequest) {
|
||||
return {
|
||||
images: featuredImages.map((img) => ({
|
||||
id: img.id,
|
||||
thumbnailUrl: isRetiredStorageUrl(img.thumbnailUrl) ? img.originalUrl : img.thumbnailUrl,
|
||||
thumbnailUrl: img.thumbnailUrl,
|
||||
originalUrl: img.originalUrl,
|
||||
imageSize: img.imageSize,
|
||||
prompt: img.prompt,
|
||||
|
||||
@ -1,12 +1,7 @@
|
||||
import crypto from "node:crypto";
|
||||
import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { formatDownloadFailure, getDownloadFailure } from "@/lib/canvas/download-error";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
import { buildImageProxyUrl, isAlibabaModelImageUrl } from "@/lib/image-delivery";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
const logger = createLogger("image.download");
|
||||
|
||||
const DEFAULT_QUALITY = 82;
|
||||
const MAX_WIDTH = 4096;
|
||||
@ -14,7 +9,6 @@ const MIN_WIDTH = 64;
|
||||
const MIN_QUALITY = 40;
|
||||
const MAX_QUALITY = 100;
|
||||
const FETCH_TIMEOUT_MS = 15000;
|
||||
const SMALL_PREVIEW_FETCH_TIMEOUT_MS = 45000;
|
||||
const DEFAULT_MEMORY_CACHE_MAX_BYTES = 64 * 1024 * 1024;
|
||||
const DEFAULT_MEMORY_CACHE_MAX_ITEMS = 256;
|
||||
|
||||
@ -133,13 +127,15 @@ function buildImageResponse(
|
||||
etag: string;
|
||||
vary?: string;
|
||||
cacheStatus?: "HIT" | "MISS";
|
||||
cacheControl?: string;
|
||||
attachment?: boolean;
|
||||
}
|
||||
) {
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": params.contentType,
|
||||
"Content-Length": String(body.length),
|
||||
ETag: params.etag,
|
||||
"Cache-Control": "public, max-age=31536000, immutable, stale-while-revalidate=86400",
|
||||
"Cache-Control": params.cacheControl || "public, max-age=31536000, immutable, stale-while-revalidate=86400",
|
||||
};
|
||||
if (params.vary) {
|
||||
headers.Vary = params.vary;
|
||||
@ -147,6 +143,11 @@ function buildImageResponse(
|
||||
if (params.cacheStatus) {
|
||||
headers["X-Image-Proxy-Cache"] = params.cacheStatus;
|
||||
}
|
||||
if (params.attachment) {
|
||||
headers["Content-Disposition"] = "attachment";
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["Content-Security-Policy"] = "default-src 'none'; sandbox";
|
||||
}
|
||||
return new NextResponse(body, {
|
||||
status: 200,
|
||||
headers,
|
||||
@ -236,7 +237,6 @@ function resolveDirectImageTarget(
|
||||
requestedQuality: number | null,
|
||||
requestedFormat: string | null
|
||||
): URL | null {
|
||||
if (isAlibabaModelImageUrl(target.toString())) return null;
|
||||
if (!isBrowserImageRequest(request)) {
|
||||
return null;
|
||||
}
|
||||
@ -265,19 +265,7 @@ function redirectToDirectImage(target: URL): NextResponse {
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = request.nextUrl;
|
||||
const requestId = crypto.randomUUID();
|
||||
const downloadFailure = (error: unknown) => {
|
||||
const failure = getDownloadFailure(error);
|
||||
logger.warn("original_download_failed", error, { requestId, code: failure.code, status: failure.status });
|
||||
return NextResponse.json({ error: formatDownloadFailure(failure, requestId), failure, requestId }, {
|
||||
status: failure.status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
};
|
||||
const rawUrl = (searchParams.get("url") || "").trim();
|
||||
if (isRetiredStorageUrl(rawUrl)) {
|
||||
if (searchParams.get("original") === "1") return downloadFailure(RETIRED_STORAGE_MESSAGE);
|
||||
return NextResponse.json({ error: RETIRED_STORAGE_MESSAGE, code: "storage_retired" }, { status: 410 });
|
||||
}
|
||||
if (!rawUrl) {
|
||||
return NextResponse.json({ error: "Missing url parameter" }, { status: 400 });
|
||||
}
|
||||
@ -293,24 +281,6 @@ export async function GET(request: NextRequest) {
|
||||
return NextResponse.json({ error: "Only http/https is supported" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (normalizeLegacyAliyunStorageUrl(target.toString())) {
|
||||
try {
|
||||
if (searchParams.get("original") === "1") {
|
||||
const { buildImageProxyUrl } = await import("@/lib/image-delivery");
|
||||
buildImageProxyUrl(target.toString(), { delivery: "original" });
|
||||
}
|
||||
const { resolveLegacyAliyunStorageUrl } = await import("@/lib/storage/image-archive-db");
|
||||
target = new URL(await resolveLegacyAliyunStorageUrl(target.toString()));
|
||||
} catch (error) {
|
||||
if (searchParams.get("original") === "1") return downloadFailure(error);
|
||||
const failure = getDownloadFailure(error);
|
||||
return NextResponse.json({ error: formatDownloadFailure(failure, requestId), failure, requestId,
|
||||
code: failure.code === "STORAGE_RETIRED" ? "storage_retired" : failure.code }, {
|
||||
status: failure.status, headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (isBlockedHost(target.hostname)) {
|
||||
return NextResponse.json({ error: "Blocked target host" }, { status: 403 });
|
||||
}
|
||||
@ -331,50 +301,6 @@ export async function GET(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!original && !forceProxy && isBrowserImageRequest(request)) {
|
||||
const direct = buildImageProxyUrl(target.toString(), {
|
||||
width: width || undefined, quality: directQuality || undefined,
|
||||
format: ["webp", "avif", "jpeg", "png"].includes(requestedFormat || "") ? requestedFormat as OutputFormat : undefined,
|
||||
});
|
||||
if (process.env.NEXT_PUBLIC_CANVAS_CDN_ORIGIN && /^https:\/\//.test(direct) &&
|
||||
new URL(direct).origin === new URL(process.env.NEXT_PUBLIC_CANVAS_CDN_ORIGIN).origin) {
|
||||
return redirectToDirectImage(new URL(direct));
|
||||
}
|
||||
}
|
||||
|
||||
if (!original && (isAlibabaModelImageUrl(target.toString()) || (!forceProxy && isBrowserImageRequest(request)))) {
|
||||
try {
|
||||
const { getArchivedImageUrlMappings } = await import("@/lib/storage/image-archive-db");
|
||||
const mappings = await getArchivedImageUrlMappings([target.toString()]);
|
||||
const archived = mappings[target.toString()];
|
||||
if (archived) {
|
||||
const preview = buildImageProxyUrl(archived, {
|
||||
width: width || undefined,
|
||||
quality,
|
||||
format: ["webp", "avif", "jpeg", "png"].includes(requestedFormat || "") ? requestedFormat as OutputFormat : undefined,
|
||||
});
|
||||
if (/^https?:\/\//i.test(preview)) return redirectToDirectImage(new URL(preview));
|
||||
target = new URL(archived);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn("preview_archive_lookup_failed", error, { requestId });
|
||||
}
|
||||
}
|
||||
|
||||
if (original && searchParams.get("download") === "resolve") {
|
||||
try {
|
||||
const { buildImageProxyUrl } = await import("@/lib/image-delivery");
|
||||
buildImageProxyUrl(target.toString(), { delivery: "original" });
|
||||
const { resolveOriginalCdnDownload } = await import("@/lib/storage/original-image-download");
|
||||
const direct = await resolveOriginalCdnDownload(target.toString(), searchParams.get("name") || "", request.signal);
|
||||
if (!direct) throw new Error("下载文件暂时无法从存储桶直接下载");
|
||||
return NextResponse.json(direct, { status: direct.delivery === "preparing" ? 202 : 200,
|
||||
headers: { "Cache-Control": "no-store", ...(direct.delivery === "preparing" ? { "Retry-After": "3" } : {}) } });
|
||||
} catch (error) {
|
||||
return downloadFailure(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!forceProxy && !original) {
|
||||
const directImageTarget = resolveDirectImageTarget(
|
||||
request,
|
||||
@ -413,81 +339,39 @@ export async function GET(request: NextRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
const fetchSignal = AbortSignal.any([
|
||||
request.signal,
|
||||
AbortSignal.timeout(original ? 60_000 : isAlibabaModelImageUrl(target.toString()) || width && width <= 256 ? SMALL_PREVIEW_FETCH_TIMEOUT_MS : FETCH_TIMEOUT_MS),
|
||||
]);
|
||||
const upstreamFailure = (error: unknown) => {
|
||||
if (request.signal.aborted) return new NextResponse(null, { status: 499 });
|
||||
if (original) return downloadFailure(error);
|
||||
const timedOut = (error instanceof Error && error.name === "TimeoutError") || fetchSignal.reason?.name === "TimeoutError";
|
||||
return NextResponse.json(
|
||||
{ error: timedOut ? "读取源图片超时,请重试" : "源图片传输中断,请重试" },
|
||||
{ status: timedOut ? 504 : 502 },
|
||||
);
|
||||
};
|
||||
let contentType: string;
|
||||
let originalBuffer: Buffer;
|
||||
if (!original && isAlibabaModelImageUrl(target.toString())) {
|
||||
try {
|
||||
const { fetchImageBytes } = await import("@/lib/storage/image-byte-cache");
|
||||
const data = await fetchImageBytes(target.toString(), { timeoutMs: SMALL_PREVIEW_FETCH_TIMEOUT_MS });
|
||||
originalBuffer = data.buffer;
|
||||
contentType = data.contentType;
|
||||
if (request.signal.aborted) return new NextResponse(null, { status: 499 });
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
} else {
|
||||
let upstreamResponse: Response;
|
||||
try {
|
||||
upstreamResponse = await fetch(target.toString(), {
|
||||
signal: fetchSignal,
|
||||
headers: {
|
||||
Accept: original ? "*/*" : "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
let upstreamResponse: Response;
|
||||
try {
|
||||
upstreamResponse = await fetch(target.toString(), {
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
headers: {
|
||||
Accept: original ? "*/*" : "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[ImageProxy] Upstream fetch failed:", error);
|
||||
return NextResponse.json({ error: "Failed to fetch upstream image" }, { status: 502 });
|
||||
}
|
||||
|
||||
if (!upstreamResponse.ok) {
|
||||
if (original) return downloadFailure(`HTTP ${upstreamResponse.status}`);
|
||||
return NextResponse.json(
|
||||
{ error: `Upstream responded with ${upstreamResponse.status}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
contentType = upstreamResponse.headers.get("content-type") || "application/octet-stream";
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
if (original) return downloadFailure("Source is not an image");
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
if (original) {
|
||||
if (upstreamResponse.status !== 200 || !upstreamResponse.body) {
|
||||
await upstreamResponse.body?.cancel();
|
||||
return downloadFailure("源图片传输中断,请重试");
|
||||
}
|
||||
const headers = new Headers({
|
||||
"Content-Type": contentType,
|
||||
"Content-Disposition": "attachment",
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||
});
|
||||
const length = upstreamResponse.headers.get("content-length");
|
||||
const encoding = upstreamResponse.headers.get("content-encoding");
|
||||
if (length && (!encoding || encoding.toLowerCase() === "identity")) headers.set("Content-Length", length);
|
||||
return new NextResponse(upstreamResponse.body, { headers });
|
||||
}
|
||||
try {
|
||||
originalBuffer = Buffer.from(await upstreamResponse.arrayBuffer());
|
||||
} catch (error) {
|
||||
return upstreamFailure(error);
|
||||
}
|
||||
if (!upstreamResponse.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `Upstream responded with ${upstreamResponse.status}` },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
|
||||
const contentType = upstreamResponse.headers.get("content-type") || "application/octet-stream";
|
||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
||||
}
|
||||
|
||||
const originalBuffer = Buffer.from(await upstreamResponse.arrayBuffer());
|
||||
if (original) {
|
||||
return buildImageResponse(originalBuffer, {
|
||||
contentType,
|
||||
etag: `"${crypto.createHash("sha256").update(originalBuffer).digest("hex")}"`,
|
||||
cacheControl: "private, no-store",
|
||||
attachment: true,
|
||||
});
|
||||
}
|
||||
const isSvg = contentType.toLowerCase().includes("image/svg");
|
||||
const isGif = contentType.toLowerCase().includes("image/gif");
|
||||
|
||||
@ -114,7 +114,7 @@ export async function POST(request: NextRequest) {
|
||||
},
|
||||
],
|
||||
temperature: 0.2,
|
||||
maxOutputTokens: 1200,
|
||||
maxTokens: 1200,
|
||||
} as any);
|
||||
|
||||
return NextResponse.json({
|
||||
|
||||
@ -6,7 +6,6 @@
|
||||
*/
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { preprocessProductImageWithRmbg } from "@/lib/scene-fusion/preprocess-product";
|
||||
import { z } from "zod";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { db } from "@/lib/db";
|
||||
@ -70,6 +69,7 @@ const SCENE_FUSION_REQUEST_STAGGER_MS = 350;
|
||||
const SCENE_FUSION_AGENT_TIMEOUT_MS = 20000;
|
||||
const SCENE_FUSION_AGENT_MAX_WORKERS = 3;
|
||||
const SCENE_FUSION_PROCESS_MAX_WORKERS = 4;
|
||||
const SCENE_FUSION_PRE_RMBG_TIMEOUT_MS = 60_000;
|
||||
const SCENE_FUSION_ECHO_HASH_TIMEOUT_MS = 20_000;
|
||||
const SCENE_FUSION_ECHO_HASH_THRESHOLD = 8;
|
||||
const SCENE_FUSION_REVIEW_TIMEOUT_MS = 25_000;
|
||||
@ -236,6 +236,41 @@ function isSceneFusionReviewRejectError(message: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function buildPreRmbgCandidateUrls(request: Request): string[] {
|
||||
const urls: string[] = [];
|
||||
const requestUrl = new URL(request.url);
|
||||
const requestHost = requestUrl.hostname.toLowerCase();
|
||||
const requestProtocol = requestUrl.protocol.replace(":", "");
|
||||
if (!(requestProtocol === "https" && (requestHost === "localhost" || requestHost === "127.0.0.1"))) {
|
||||
urls.push(new URL("/api/rmbg", request.url).toString());
|
||||
}
|
||||
|
||||
const host = request.headers.get("host")?.trim();
|
||||
const protoHint = request.headers
|
||||
.get("x-forwarded-proto")
|
||||
?.split(",")[0]
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
const protocol = protoHint === "https" || protoHint === "http" ? protoHint : requestUrl.protocol.replace(":", "");
|
||||
|
||||
if (host) {
|
||||
const normalizedHost = host.split(":")[0]?.toLowerCase() || "";
|
||||
const isLocalHost = normalizedHost === "localhost" || normalizedHost === "127.0.0.1";
|
||||
if (!(protocol === "https" && isLocalHost)) {
|
||||
urls.push(`${protocol}://${host}/api/rmbg`);
|
||||
}
|
||||
if (isLocalHost) {
|
||||
urls.push(`http://${host}/api/rmbg`);
|
||||
}
|
||||
}
|
||||
|
||||
const localPort = requestUrl.port || process.env.PORT || "3125";
|
||||
urls.push(`http://127.0.0.1:${localPort}/api/rmbg`);
|
||||
urls.push(`http://localhost:${localPort}/api/rmbg`);
|
||||
|
||||
return Array.from(new Set(urls));
|
||||
}
|
||||
|
||||
function normalizeUrlForCompare(input: string): string {
|
||||
try {
|
||||
const parsed = new URL(input);
|
||||
@ -953,6 +988,102 @@ async function getSceneFusionConfig() {
|
||||
};
|
||||
}
|
||||
|
||||
async function preprocessProductImageWithRmbg(
|
||||
request: Request,
|
||||
requestId: string,
|
||||
productImageUrl: string,
|
||||
preRmbgEnabled: boolean
|
||||
): Promise<{
|
||||
productImageUrl: string;
|
||||
usedPreRmbg: boolean;
|
||||
provider?: string;
|
||||
reason?: string;
|
||||
}> {
|
||||
if (!preRmbgEnabled) {
|
||||
return {
|
||||
productImageUrl,
|
||||
usedPreRmbg: false,
|
||||
reason: "disabled_by_config",
|
||||
};
|
||||
}
|
||||
|
||||
const cookie = request.headers.get("cookie");
|
||||
if (!cookie) {
|
||||
return {
|
||||
productImageUrl,
|
||||
usedPreRmbg: false,
|
||||
reason: "missing_cookie",
|
||||
};
|
||||
}
|
||||
|
||||
const candidateUrls = buildPreRmbgCandidateUrls(request);
|
||||
let lastReason = "no_candidate_url";
|
||||
|
||||
logger.info("pre_rmbg_started", {
|
||||
requestId,
|
||||
candidateCount: candidateUrls.length,
|
||||
});
|
||||
|
||||
for (const rmbgUrl of candidateUrls) {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), SCENE_FUSION_PRE_RMBG_TIMEOUT_MS);
|
||||
try {
|
||||
const response = await fetch(rmbgUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
cookie,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
imageUrl: productImageUrl,
|
||||
prompt: "场景裂变预处理-抠图",
|
||||
skipGallerySave: true,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
const payload = await response.json().catch(() => null) as Record<string, unknown> | null;
|
||||
|
||||
if (!response.ok) {
|
||||
lastReason = `request_failed_${response.status}`;
|
||||
logger.warn("pre_rmbg_candidate_failed", {
|
||||
requestId,
|
||||
status: response.status,
|
||||
detail: payload?.detail || payload?.error || "unknown",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const cleanedUrl = String(payload?.original_url || payload?.thumbnail_url || "").trim();
|
||||
if (!cleanedUrl || cleanedUrl === productImageUrl) {
|
||||
lastReason = cleanedUrl ? "same_as_source" : "empty_result";
|
||||
logger.warn("pre_rmbg_candidate_invalid", {
|
||||
requestId,
|
||||
reason: lastReason,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
productImageUrl: cleanedUrl,
|
||||
usedPreRmbg: true,
|
||||
provider: String(payload?.provider || "unknown"),
|
||||
};
|
||||
} catch (error) {
|
||||
lastReason = error instanceof Error ? error.message : "exception";
|
||||
logger.warn("pre_rmbg_candidate_exception", error, { requestId });
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
productImageUrl,
|
||||
usedPreRmbg: false,
|
||||
reason: lastReason,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建缩略图
|
||||
*/
|
||||
@ -2305,13 +2436,12 @@ export async function POST(request: Request) {
|
||||
productImageUrl = await uploadBase64ToS3(productImage, "scene-fusion-product");
|
||||
}
|
||||
const shouldForcePreRmbg = resolvedSceneMode === "random-bg";
|
||||
const preprocessedProduct = await preprocessProductImageWithRmbg({
|
||||
const preprocessedProduct = await preprocessProductImageWithRmbg(
|
||||
request,
|
||||
requestId,
|
||||
userId: session.user.id,
|
||||
productImageUrl,
|
||||
preRmbgEnabled: shouldForcePreRmbg ? true : config.preRmbgEnabled,
|
||||
});
|
||||
shouldForcePreRmbg ? true : config.preRmbgEnabled
|
||||
);
|
||||
const fusionProductImageUrl = preprocessedProduct.productImageUrl;
|
||||
logger.info("pre_rmbg_resolved", {
|
||||
requestId,
|
||||
|
||||
@ -1,18 +1,15 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { resolveSiteBranding } from "@/lib/site-branding";
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import {
|
||||
aiModel,
|
||||
aiProvider,
|
||||
siteSettings,
|
||||
systemSettingHistory,
|
||||
systemSettingSnapshot,
|
||||
systemSettings,
|
||||
} from "@/lib/db/schema";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { omitAgentWorkflowPrompts } from "@/lib/agents/workflow-loading";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { isAgentWorkflowAdminType, isSiteAdminType } from "@/lib/middleware/admin";
|
||||
import {
|
||||
@ -155,7 +152,7 @@ import {
|
||||
} from "@/lib/ai-wash/config";
|
||||
import { STYLE_PRO_CONFIG_KEY, normalizeStyleProConfig } from "@/lib/style-pro/config";
|
||||
import { withTimeout } from "@/lib/public-api/performance";
|
||||
import type { AgentCategoryTreeConfig, AgentWorkflowUiConfig } from "@/types/agent";
|
||||
import type { AgentCategoryTreeConfig } from "@/types/agent";
|
||||
|
||||
// Historically stored as "home_surprise_categories" but used for the featured gallery categories.
|
||||
const HOME_SURPRISE_CATEGORIES_KEY = "home_surprise_categories";
|
||||
@ -555,9 +552,6 @@ function normalizeAgentCategoryTreeConfig(value: unknown): AgentCategoryTreeConf
|
||||
type PublicSiteSettingsScope =
|
||||
| "agent-brand-model"
|
||||
| "agent-canvas"
|
||||
| "agent-canvas-base"
|
||||
| "agent-workflow-templates"
|
||||
| "agent-entry"
|
||||
| "agent-presets"
|
||||
| "auth"
|
||||
| "branding"
|
||||
@ -569,9 +563,6 @@ type PublicSiteSettingsScope =
|
||||
const PUBLIC_SITE_SETTINGS_SCOPES = new Set<string>([
|
||||
"agent-brand-model",
|
||||
"agent-canvas",
|
||||
"agent-canvas-base",
|
||||
"agent-workflow-templates",
|
||||
"agent-entry",
|
||||
"agent-presets",
|
||||
"auth",
|
||||
"branding",
|
||||
@ -615,60 +606,22 @@ const HOME_SITE_SETTINGS_FALLBACK: Record<string, unknown> = {
|
||||
lovartHomeSidebarConfig: normalizeLovartHomeSidebarConfig(undefined),
|
||||
};
|
||||
|
||||
const AGENT_CANVAS_SETTING_KEYS = [
|
||||
REALTIME_CANVAS_CONFIG_KEY,
|
||||
REALTIME_CANVAS_MODE_ICON_CONFIG_KEY,
|
||||
CANVAS_TOOLBAR_CONFIG_SETTING_KEY,
|
||||
LAYER_SPLIT_CONFIG_KEY,
|
||||
ANGLE_EDIT_CONFIG_KEY,
|
||||
CANVAS_AGENT_MODE_ENABLED_KEY,
|
||||
...CANVAS_AGENT_FEATURE_SETTING_KEYS,
|
||||
VIDEO_CANVAS_ENABLED_KEY,
|
||||
VIDEO_CANVAS_SIDEBAR_ENABLED_KEY,
|
||||
ENHANCE_PRO_KREA_SETTING_KEY,
|
||||
AI_WASH_CONFIG_KEY,
|
||||
STYLE_PRO_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_UI_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY,
|
||||
];
|
||||
|
||||
async function getAgentCanvasSettingsEtag(scope: string) {
|
||||
const [settings, rows, providers] = await Promise.all([
|
||||
db.select({ id: siteSettings.id, updatedAt: siteSettings.updatedAt })
|
||||
.from(siteSettings).limit(1),
|
||||
db.select({ key: systemSettings.key, updatedAt: systemSettings.updatedAt })
|
||||
.from(systemSettings)
|
||||
.where(inArray(systemSettings.key, AGENT_CANVAS_SETTING_KEYS)),
|
||||
db.select({ id: aiProvider.id, updatedAt: aiProvider.updatedAt, enabled: aiProvider.isEnabled })
|
||||
.from(aiProvider)
|
||||
.where(inArray(aiProvider.type, ["tripo-3d", "worldlabs-3d"])),
|
||||
]);
|
||||
const versions = [
|
||||
...settings.map((row) => `${row.id}:${row.updatedAt.getTime()}`),
|
||||
...rows.map((row) => `${row.key}:${row.updatedAt.getTime()}`),
|
||||
...providers.map((row) => `${row.id}:${row.updatedAt.getTime()}:${row.enabled}`),
|
||||
].sort();
|
||||
return `W/"${scope}/${versions.join(",")}"`;
|
||||
}
|
||||
|
||||
function createScopedSiteSettingsResponse(
|
||||
scope: PublicSiteSettingsScope,
|
||||
data: Record<string, unknown>,
|
||||
cacheStatus: "HIT" | "MISS" | "STALE" | "FALLBACK" = "MISS",
|
||||
cacheKey: string = scope,
|
||||
options: { fallback?: boolean; startedAt?: number; etag?: string } = {}
|
||||
options: { fallback?: boolean; startedAt?: number } = {}
|
||||
) {
|
||||
if (cacheStatus === "MISS") {
|
||||
setScopedSiteSettingsCache(
|
||||
cacheKey,
|
||||
data,
|
||||
PUBLIC_SITE_SETTINGS_CACHE_TTL_MS,
|
||||
options.etag
|
||||
PUBLIC_SITE_SETTINGS_CACHE_TTL_MS
|
||||
);
|
||||
}
|
||||
|
||||
const response = NextResponse.json(data);
|
||||
if (options.etag) response.headers.set("ETag", options.etag);
|
||||
// Lightweight public settings change rarely; keep them browser-local briefly
|
||||
// so page opens do not repeatedly wait on the large full settings endpoint.
|
||||
response.headers.set(
|
||||
@ -688,7 +641,7 @@ function createScopedSiteSettingsResponse(
|
||||
return response;
|
||||
}
|
||||
|
||||
async function readScopedSiteSettings(keys: string[], omitWorkflowSteps = false) {
|
||||
async function readScopedSiteSettings(keys: string[]) {
|
||||
const [settings, settingRows] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
@ -696,14 +649,8 @@ async function readScopedSiteSettings(keys: string[], omitWorkflowSteps = false)
|
||||
.limit(1)
|
||||
.then((rows) => rows[0]),
|
||||
keys.length > 0
|
||||
? (omitWorkflowSteps
|
||||
? db.select({
|
||||
key: systemSettings.key,
|
||||
value: sql<unknown>`case when ${systemSettings.key} = ${AGENT_WORKFLOW_UI_CONFIG_KEY}
|
||||
and jsonb_typeof(${systemSettings.value}) = 'object'
|
||||
then ${systemSettings.value} - 'steps' else ${systemSettings.value} end`,
|
||||
})
|
||||
: db.select())
|
||||
? db
|
||||
.select()
|
||||
.from(systemSettings)
|
||||
.where(inArray(systemSettings.key, keys))
|
||||
: Promise.resolve([]),
|
||||
@ -716,12 +663,12 @@ async function readScopedSiteSettings(keys: string[], omitWorkflowSteps = false)
|
||||
}
|
||||
|
||||
function createBrandingSettings(settings: Record<string, unknown> | undefined) {
|
||||
return resolveSiteBranding({
|
||||
return {
|
||||
siteName: String(settings?.siteName || "𝗕𝘂𝗬𝗶"),
|
||||
siteLogo: String(settings?.siteLogo || ""),
|
||||
siteLogoDark: String(settings?.siteLogoDark || ""),
|
||||
favicon: String(settings?.favicon || ""),
|
||||
});
|
||||
siteLogo: settings?.siteLogo || null,
|
||||
siteLogoDark: settings?.siteLogoDark || null,
|
||||
favicon: settings?.favicon || null,
|
||||
};
|
||||
}
|
||||
|
||||
async function getScopedPublicSiteSettings(
|
||||
@ -729,7 +676,6 @@ async function getScopedPublicSiteSettings(
|
||||
options: {
|
||||
brandName?: string;
|
||||
cacheKey?: string;
|
||||
etag?: string;
|
||||
} = {}
|
||||
) {
|
||||
if (scope === "auth") {
|
||||
@ -791,17 +737,23 @@ async function getScopedPublicSiteSettings(
|
||||
});
|
||||
}
|
||||
|
||||
if (scope === "agent-workflow-templates") {
|
||||
const [setting] = await db.select({ value: systemSettings.value })
|
||||
.from(systemSettings).where(eq(systemSettings.key, AGENT_WORKFLOW_UI_CONFIG_KEY)).limit(1);
|
||||
const config = normalizeAgentWorkflowUiConfig(setting?.value);
|
||||
return createScopedSiteSettingsResponse(scope, {
|
||||
steps: omitAgentWorkflowPrompts(config.steps),
|
||||
}, "MISS", options.cacheKey || scope, { etag: options.etag });
|
||||
}
|
||||
|
||||
if (scope === "agent-canvas" || scope === "agent-canvas-base" || scope === "agent-entry") {
|
||||
const { settings, valueByKey } = await readScopedSiteSettings(AGENT_CANVAS_SETTING_KEYS, scope !== "agent-canvas");
|
||||
if (scope === "agent-canvas") {
|
||||
const { settings, valueByKey } = await readScopedSiteSettings([
|
||||
REALTIME_CANVAS_CONFIG_KEY,
|
||||
REALTIME_CANVAS_MODE_ICON_CONFIG_KEY,
|
||||
CANVAS_TOOLBAR_CONFIG_SETTING_KEY,
|
||||
LAYER_SPLIT_CONFIG_KEY,
|
||||
ANGLE_EDIT_CONFIG_KEY,
|
||||
CANVAS_AGENT_MODE_ENABLED_KEY,
|
||||
...CANVAS_AGENT_FEATURE_SETTING_KEYS,
|
||||
VIDEO_CANVAS_ENABLED_KEY,
|
||||
VIDEO_CANVAS_SIDEBAR_ENABLED_KEY,
|
||||
ENHANCE_PRO_KREA_SETTING_KEY,
|
||||
AI_WASH_CONFIG_KEY,
|
||||
STYLE_PRO_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_UI_CONFIG_KEY,
|
||||
AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY,
|
||||
]);
|
||||
const canvasFeatureAvailability = await readCanvasFeatureAvailability(
|
||||
valueByKey
|
||||
);
|
||||
@ -809,8 +761,6 @@ async function getScopedPublicSiteSettings(
|
||||
const videoCanvasSidebarEnabled = normalizeVideoCanvasSidebarEnabled(
|
||||
valueByKey.get(VIDEO_CANVAS_SIDEBAR_ENABLED_KEY)
|
||||
);
|
||||
const rawUiConfig = valueByKey.get(AGENT_WORKFLOW_UI_CONFIG_KEY) as
|
||||
Partial<AgentWorkflowUiConfig> | undefined;
|
||||
return createScopedSiteSettingsResponse(scope, {
|
||||
...createBrandingSettings(typedSettings),
|
||||
agentEnabled: typedSettings?.agentEnabled ?? true,
|
||||
@ -846,20 +796,12 @@ async function getScopedPublicSiteSettings(
|
||||
tripo3dEnabled: canvasFeatureAvailability.tripo3dEnabled,
|
||||
worldlabs3dEnabled: canvasFeatureAvailability.worldlabs3dEnabled,
|
||||
agentWorkflowUiConfig: normalizeAgentWorkflowUiConfig(
|
||||
scope === "agent-entry"
|
||||
? {
|
||||
steps: [],
|
||||
pageFeatureSettings: rawUiConfig?.pageFeatureSettings,
|
||||
businessModeSettings: rawUiConfig?.businessModeSettings,
|
||||
}
|
||||
: scope === "agent-canvas-base"
|
||||
? { ...rawUiConfig, steps: [] }
|
||||
: rawUiConfig
|
||||
valueByKey.get(AGENT_WORKFLOW_UI_CONFIG_KEY)
|
||||
),
|
||||
agentWorkflowShowcaseConfig: normalizeAgentWorkflowShowcaseConfig(
|
||||
valueByKey.get(AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY)
|
||||
),
|
||||
}, "MISS", options.cacheKey || scope, { etag: options.etag });
|
||||
});
|
||||
}
|
||||
|
||||
if (scope === "branding") {
|
||||
@ -1113,24 +1055,13 @@ export async function GET(request: NextRequest) {
|
||||
const cacheKey = brandName.trim()
|
||||
? `${scopedScope}:${brandName.trim().toLowerCase()}`
|
||||
: scopedScope;
|
||||
const etag = scopedScope === "agent-canvas" || scopedScope === "agent-entry" ||
|
||||
scopedScope === "agent-canvas-base" || scopedScope === "agent-workflow-templates"
|
||||
? await getAgentCanvasSettingsEtag(scopedScope)
|
||||
: undefined;
|
||||
if (etag && request.headers.get("If-None-Match") === etag) {
|
||||
return new NextResponse(null, {
|
||||
status: 304,
|
||||
headers: { ETag: etag, "Cache-Control": "private, no-cache" },
|
||||
});
|
||||
}
|
||||
const cached = getScopedSiteSettingsCache(cacheKey);
|
||||
if (cached && cached.expiresAt > Date.now() && (!etag || cached.etag === etag)) {
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return createScopedSiteSettingsResponse(
|
||||
scopedScope,
|
||||
cached.data,
|
||||
"HIT",
|
||||
cacheKey,
|
||||
{ etag }
|
||||
cacheKey
|
||||
);
|
||||
}
|
||||
if (cached && scopedScope !== "home") {
|
||||
@ -1141,7 +1072,6 @@ export async function GET(request: NextRequest) {
|
||||
const responsePromise = getScopedPublicSiteSettings(scopedScope, {
|
||||
brandName,
|
||||
cacheKey,
|
||||
etag,
|
||||
});
|
||||
return scopedScope === "home"
|
||||
? await withTimeout(responsePromise, 1600, "site-settings:home")
|
||||
@ -1611,7 +1541,7 @@ export async function GET(request: NextRequest) {
|
||||
};
|
||||
|
||||
const response = NextResponse.json({
|
||||
...resolveSiteBranding(baseSettings),
|
||||
...baseSettings,
|
||||
lovartPromoText:
|
||||
baseSettings.lovartPromoText ||
|
||||
"现在升级,立享 Kling 3.0 与 Nano Banana Pro,最高 5 折优惠",
|
||||
@ -2213,14 +2143,6 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
const data = updateSchema.parse(body);
|
||||
if (data.canvasAutoModeDefaultModelId) {
|
||||
const [available] = await db.select({ id: aiModel.id }).from(aiModel)
|
||||
.innerJoin(aiProvider, eq(aiProvider.id, aiModel.providerId))
|
||||
.where(and(eq(aiModel.id, data.canvasAutoModeDefaultModelId),
|
||||
eq(aiModel.isEnabled, true), eq(aiProvider.isEnabled, true),
|
||||
eq(aiModel.isSubModel, false), eq(aiModel.supportsImageGen, true))).limit(1);
|
||||
if (!available) return NextResponse.json({ error: "默认生图模型或其上游已停用,请选择可用的生图模型,或改为系统智能选择。" }, { status: 400 });
|
||||
}
|
||||
const {
|
||||
surpriseCategories,
|
||||
aiDetailGenerationEnabled,
|
||||
|
||||
@ -6,7 +6,6 @@ import { eq } from "drizzle-orm";
|
||||
import { uploadFile } from "@/lib/storage/service";
|
||||
import {
|
||||
createMediaAssetRelation,
|
||||
getDefaultStorageConfig,
|
||||
getPointsSystemConfig,
|
||||
getMediaAssetsByUserAndUrls,
|
||||
upsertMediaAsset,
|
||||
@ -22,27 +21,6 @@ export const maxDuration = 600;
|
||||
const WATERMARK_SYNC_WAIT_TIMEOUT_MS = 20_000;
|
||||
const WATERMARK_POLL_INTERVAL_MS = 1200;
|
||||
|
||||
async function resolveStoredQiniuImageUrl(source: string): Promise<string | null> {
|
||||
const config = await getDefaultStorageConfig().catch(() => null);
|
||||
if (config?.type !== "qiniu-kodo" || !config.isEnabled || !config.publicUrl) return null;
|
||||
|
||||
try {
|
||||
const base = new URL(config.publicUrl);
|
||||
const url = new URL(source);
|
||||
const prefix = base.pathname.replace(/\/$/, "") + "/";
|
||||
if (base.protocol !== "https:" || url.origin !== base.origin ||
|
||||
url.username || url.password || url.search || url.hash ||
|
||||
!url.pathname.startsWith(prefix)) return null;
|
||||
|
||||
const objectKey = url.pathname.slice(prefix.length);
|
||||
return /^uploads\/(?:direct\/[0-9a-f-]{36}\/)?[\w.-]+$/i.test(objectKey)
|
||||
? url.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取去水印API配置
|
||||
async function getWatermarkRemoveConfig() {
|
||||
try {
|
||||
@ -153,16 +131,13 @@ async function persistWatermarkResult(params: {
|
||||
processing_time?: number;
|
||||
}> {
|
||||
try {
|
||||
let resultUrl = await resolveStoredQiniuImageUrl(params.processedImageUrl);
|
||||
if (!resultUrl) {
|
||||
const imageResponse = await fetch(params.processedImageUrl);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error("下载处理后的图片失败");
|
||||
}
|
||||
const imageBuffer = await imageResponse.arrayBuffer();
|
||||
const filename = `watermark-removed-${Date.now()}.png`;
|
||||
resultUrl = (await uploadFile(filename, imageBuffer)).url;
|
||||
const imageResponse = await fetch(params.processedImageUrl);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error("下载处理后的图片失败");
|
||||
}
|
||||
const imageBuffer = await imageResponse.arrayBuffer();
|
||||
const filename = `watermark-removed-${Date.now()}.png`;
|
||||
const uploadResult = await uploadFile(filename, imageBuffer);
|
||||
|
||||
let saved = false;
|
||||
let saveError: unknown = null;
|
||||
@ -175,8 +150,8 @@ async function persistWatermarkResult(params: {
|
||||
try {
|
||||
([savedImage] = await db.insert(generatedImage).values({
|
||||
userId: params.userId,
|
||||
thumbnailUrl: resultUrl,
|
||||
originalUrl: resultUrl,
|
||||
thumbnailUrl: uploadResult.url,
|
||||
originalUrl: uploadResult.url,
|
||||
imageSize: "2K",
|
||||
prompt: "去水印处理",
|
||||
modelId: "watermark-remove",
|
||||
@ -209,9 +184,9 @@ async function persistWatermarkResult(params: {
|
||||
mediaType: "image",
|
||||
sourceType: "edited",
|
||||
status: "ready",
|
||||
originalUrl: resultUrl,
|
||||
previewUrl: resultUrl,
|
||||
thumbnailUrl: resultUrl,
|
||||
originalUrl: uploadResult.url,
|
||||
previewUrl: uploadResult.url,
|
||||
thumbnailUrl: uploadResult.url,
|
||||
displayName: "去水印处理",
|
||||
prompt: "去水印处理",
|
||||
modelId: "watermark-remove",
|
||||
@ -242,8 +217,8 @@ async function persistWatermarkResult(params: {
|
||||
|
||||
return {
|
||||
success: true,
|
||||
original_url: resultUrl,
|
||||
thumbnail_url: resultUrl,
|
||||
original_url: uploadResult.url,
|
||||
thumbnail_url: uploadResult.url,
|
||||
processing_time:
|
||||
typeof params.startedAt === "number" ? (Date.now() - params.startedAt) / 1000 : undefined,
|
||||
};
|
||||
@ -387,7 +362,7 @@ export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { image_url } = body;
|
||||
|
||||
if (typeof image_url !== "string" || !image_url) {
|
||||
if (!image_url) {
|
||||
return NextResponse.json(
|
||||
{ error: "请提供图片URL" },
|
||||
{ status: 400 }
|
||||
@ -438,24 +413,24 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
}
|
||||
// 七牛上的公开图片可以直接交给去水印服务读取。
|
||||
// 如果是 HTTP/HTTPS URL,下载后重新上传确保公网可访问
|
||||
else if (image_url.startsWith("http://") || image_url.startsWith("https://")) {
|
||||
const storedImageUrl = await resolveStoredQiniuImageUrl(image_url);
|
||||
publicImageUrl = storedImageUrl || image_url;
|
||||
if (!storedImageUrl) {
|
||||
try {
|
||||
console.log("[WatermarkRemove] 下载原图并上传到S3...");
|
||||
const imageResponse = await fetch(image_url);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error("下载原图失败");
|
||||
}
|
||||
const imageBuffer = await imageResponse.arrayBuffer();
|
||||
const filename = `watermark-input-${Date.now()}.jpg`;
|
||||
publicImageUrl = (await uploadFile(filename, imageBuffer)).url;
|
||||
console.log("[WatermarkRemove] 图片已上传到S3:", publicImageUrl);
|
||||
} catch (downloadError) {
|
||||
console.error("[WatermarkRemove] 下载/上传原图失败,使用原始URL:", downloadError);
|
||||
try {
|
||||
console.log("[WatermarkRemove] 下载原图并上传到S3...");
|
||||
const imageResponse = await fetch(image_url);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error("下载原图失败");
|
||||
}
|
||||
const imageBuffer = await imageResponse.arrayBuffer();
|
||||
const filename = `watermark-input-${Date.now()}.jpg`;
|
||||
const uploadResult = await uploadFile(filename, imageBuffer);
|
||||
publicImageUrl = uploadResult.url;
|
||||
console.log("[WatermarkRemove] 图片已上传到S3:", publicImageUrl);
|
||||
} catch (downloadError) {
|
||||
console.error("[WatermarkRemove] 下载/上传原图失败:", downloadError);
|
||||
// 如果下载失败,尝试使用原始URL
|
||||
console.log("[WatermarkRemove] 尝试使用原始URL");
|
||||
publicImageUrl = image_url;
|
||||
}
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -48,13 +48,8 @@ export default function CanvasStyleProPage() {
|
||||
const canvasData = result.data.canvasData;
|
||||
const latestState = useCanvasStore.getState();
|
||||
setProject(result.data.id, result.data.title);
|
||||
if (
|
||||
latestState.projectId !== id ||
|
||||
(latestState.nodes.length === 0 && latestState.edges.length === 0)
|
||||
) {
|
||||
if (latestState.nodes.length === 0 && latestState.edges.length === 0) {
|
||||
loadCanvas(canvasData);
|
||||
const revision = String(result.data.updatedAt || "");
|
||||
useCanvasStore.getState().setCanvasRevision(revision, revision);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@ -3,8 +3,6 @@ import { Toaster } from "sonner";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { FaviconUpdater } from "@/components/favicon-updater";
|
||||
import { ImageDeliveryOptimizer } from "@/components/image-delivery-optimizer";
|
||||
import { AppUpdateNotice } from "@/components/app-update-notice";
|
||||
import { PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE } from "@/lib/client/page-refresh";
|
||||
import { getSiteSettings } from "@/lib/db/queries";
|
||||
|
||||
import "./globals.css";
|
||||
@ -143,7 +141,7 @@ const CHUNK_ERROR_RECOVERY_SCRIPT = `\
|
||||
showManualRecoveryNotice();
|
||||
return;
|
||||
}
|
||||
if (lastReloadAt || document.documentElement.hasAttribute('${PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE}')) return;
|
||||
if (lastReloadAt) return;
|
||||
var now = Date.now();
|
||||
// If storage is blocked, a reload cannot remember its attempt and must not run.
|
||||
if (!safeSetSessionStorage(RECOVERY_KEY, String(now))) return;
|
||||
@ -154,10 +152,6 @@ const CHUNK_ERROR_RECOVERY_SCRIPT = `\
|
||||
showManualRecoveryNotice();
|
||||
return;
|
||||
}
|
||||
if (document.documentElement.hasAttribute('${PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE}')) {
|
||||
if (safeSetSessionStorage(RECOVERY_KEY, '0')) lastReloadAt = 0;
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
}, 800);
|
||||
}
|
||||
@ -221,7 +215,6 @@ export default function RootLayout({
|
||||
enableSystem
|
||||
>
|
||||
<Toaster position="top-center" />
|
||||
<AppUpdateNotice />
|
||||
<SessionProvider>{children}</SessionProvider>
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
"use client";
|
||||
import { useEffect, useRef, type ReactNode } from "react";
|
||||
|
||||
export function AdminSurface({ children }: { children: ReactNode }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
|
||||
let context: { revert: () => void } | undefined;
|
||||
let disposed = false;
|
||||
import("gsap").then(({ gsap }) => {
|
||||
if (disposed) return;
|
||||
context = gsap.context(() => {
|
||||
gsap.fromTo(
|
||||
ref.current,
|
||||
{ y: 6, opacity: 0.85 },
|
||||
{ y: 0, opacity: 1, duration: 0.25, ease: "power3.out", clearProps: "transform,opacity" },
|
||||
);
|
||||
}, ref);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
context?.revert();
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div ref={ref} className="space-y-6">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,603 +0,0 @@
|
||||
"use client";
|
||||
import { useEffect, useState } from "react";
|
||||
import useSWR from "swr";
|
||||
import {
|
||||
RefreshCw,
|
||||
Search,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
Download,
|
||||
Star,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { toast } from "sonner";
|
||||
import { MediaThumbnail } from "./media-thumbnail";
|
||||
import { AdminSurface } from "./admin-surface";
|
||||
import { formatRecordTime } from "@/lib/admin/record-time";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
|
||||
export type MediaRecord = {
|
||||
id: string;
|
||||
recordType: "image" | "video";
|
||||
userName: string | null;
|
||||
userEmail: string | null;
|
||||
userDepartment: string | null;
|
||||
createdAt: string;
|
||||
modelId: string | null;
|
||||
chatId: string | null;
|
||||
thumbnailUrl: string;
|
||||
originalUrl: string;
|
||||
videoUrl?: string | null;
|
||||
prompt: string | null;
|
||||
imageSize: string | null;
|
||||
isFeatured: boolean;
|
||||
featuredCategory: string | null;
|
||||
featuredAt?: string | null;
|
||||
};
|
||||
type MediaResponse = {
|
||||
images: MediaRecord[];
|
||||
pagination: {
|
||||
total: number;
|
||||
totalPages: number;
|
||||
totalImages: number;
|
||||
totalVideos: number;
|
||||
page: number;
|
||||
};
|
||||
};
|
||||
export async function adminFetcher(url: string) {
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || data.message || "加载失败,请重试");
|
||||
return data;
|
||||
}
|
||||
const selectClass =
|
||||
"h-10 rounded-md border bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
function recentDate() {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - 6);
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Shanghai" }).format(d);
|
||||
}
|
||||
|
||||
export function MediaRecordsPanel({ categories }: { categories: string[] }) {
|
||||
const [view, setView] = useState("assets");
|
||||
const [search, setSearch] = useState("");
|
||||
const [filters, setFilters] = useState({
|
||||
search: "",
|
||||
type: "all",
|
||||
startDate: recentDate(),
|
||||
endDate: "",
|
||||
model: "",
|
||||
featured: "false",
|
||||
status: "all",
|
||||
});
|
||||
const [page, setPage] = useState(1);
|
||||
const [selected, setSelected] = useState<MediaRecord | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [originalFailed, setOriginalFailed] = useState(false);
|
||||
const update = (changes: Partial<typeof filters>) => {
|
||||
setFilters((f) => ({ ...f, ...changes }));
|
||||
setPage(1);
|
||||
};
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setFilters((f) => (f.search === search ? f : { ...f, search }));
|
||||
setPage(1);
|
||||
}, 350);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
const { data: options } = useSWR<{
|
||||
models: Array<{ id: string; modelId: string; displayName: string; providerName: string }>;
|
||||
}>("/api/admin/ai-models?view=options", adminFetcher, { revalidateOnFocus: false });
|
||||
const modelNames = new Map<string, string>();
|
||||
for (const model of options?.models || [])
|
||||
if (!modelNames.has(model.modelId)) modelNames.set(model.modelId, model.displayName);
|
||||
const recordModelNames = new Map(modelNames);
|
||||
for (const model of options?.models || []) recordModelNames.set(model.id, model.displayName);
|
||||
const openDetails = (item: MediaRecord) => {
|
||||
setSelected(item);
|
||||
setOriginalFailed(false);
|
||||
};
|
||||
const query = new URLSearchParams({ ...filters, page: String(page), pageSize: "40" });
|
||||
const { data, error, isLoading, isValidating, mutate } = useSWR<MediaResponse>(
|
||||
view === "assets" ? `/api/admin/images?${query}` : null,
|
||||
adminFetcher,
|
||||
{ keepPreviousData: true, revalidateOnFocus: false },
|
||||
);
|
||||
const tasks = useSWR<{
|
||||
tasks: Array<{
|
||||
id: string;
|
||||
userName: string;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
error: string | null;
|
||||
model: string | null;
|
||||
elapsedMs: number | null;
|
||||
}>;
|
||||
total: number;
|
||||
}>(view === "tasks" ? `/api/admin/media-tasks?${query}` : null, adminFetcher, {
|
||||
keepPreviousData: true,
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
const busy = view === "assets" ? isValidating : tasks.isValidating;
|
||||
const failure = view === "assets" ? error : tasks.error;
|
||||
const loading = view === "assets" ? isLoading : tasks.isLoading;
|
||||
const total = view === "assets" ? data?.pagination.total : tasks.data?.total;
|
||||
const pages = Math.max(1, Math.ceil((total || 0) / 40));
|
||||
async function save(changes: Partial<MediaRecord>) {
|
||||
if (!selected || saving) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const response = await fetch("/api/admin/images", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ imageId: selected.id, ...changes }),
|
||||
});
|
||||
if (!response.ok) throw new Error("保存失败,请重试");
|
||||
setSelected({ ...selected, ...changes });
|
||||
toast.success("已保存");
|
||||
await mutate();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "保存失败");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<AdminSurface>
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">生成记录</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
查看图片与视频产物,追踪画布任务。时间统一按北京时间展示。
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => (view === "assets" ? mutate() : tasks.mutate())}
|
||||
>
|
||||
<RefreshCw className={`mr-2 size-4 ${busy ? "motion-safe:animate-spin" : ""}`} />
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex gap-2" role="tablist" aria-label="记录视图">
|
||||
{[
|
||||
["assets", "产物记录"],
|
||||
["tasks", "画布任务"],
|
||||
].map(([key, label]) => (
|
||||
<Button
|
||||
key={key}
|
||||
role="tab"
|
||||
aria-selected={view === key}
|
||||
variant={view === key ? "default" : "ghost"}
|
||||
onClick={() => {
|
||||
setView(key);
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-3 rounded-xl border bg-background p-4">
|
||||
<label className="min-w-48 flex-1 text-xs font-medium">
|
||||
用户
|
||||
<div className="relative mt-2">
|
||||
<Search className="absolute left-3 top-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-10 pl-9"
|
||||
placeholder="搜索姓名或邮箱"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
{view === "assets" ? (
|
||||
<label className="text-xs font-medium">
|
||||
类型
|
||||
<select
|
||||
aria-label="产物类型"
|
||||
className={`${selectClass} mt-2 block`}
|
||||
value={filters.type}
|
||||
onChange={(e) => update({ type: e.target.value })}
|
||||
>
|
||||
<option value="all">图片与视频</option>
|
||||
<option value="image">只看图片</option>
|
||||
<option value="video">只看视频</option>
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
<label className="text-xs font-medium">
|
||||
任务状态
|
||||
<select
|
||||
aria-label="任务状态"
|
||||
className={`${selectClass} mt-2 block`}
|
||||
value={filters.status}
|
||||
onChange={(e) => update({ status: e.target.value })}
|
||||
>
|
||||
<option value="all">全部状态</option>
|
||||
<option value="failed">失败</option>
|
||||
<option value="running">运行中</option>
|
||||
<option value="pending">排队中</option>
|
||||
<option value="succeeded">成功</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<label className="text-xs font-medium">
|
||||
开始日期
|
||||
<Input
|
||||
aria-label="开始日期"
|
||||
className="mt-2 h-10 w-40"
|
||||
type="date"
|
||||
value={filters.startDate}
|
||||
onChange={(e) => update({ startDate: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="text-xs font-medium">
|
||||
结束日期
|
||||
<Input
|
||||
aria-label="结束日期"
|
||||
className="mt-2 h-10 w-40"
|
||||
type="date"
|
||||
value={filters.endDate}
|
||||
onChange={(e) => update({ endDate: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setSearch("");
|
||||
update({
|
||||
search: "",
|
||||
startDate: "",
|
||||
endDate: "",
|
||||
model: "",
|
||||
featured: "false",
|
||||
type: "all",
|
||||
status: "all",
|
||||
});
|
||||
}}
|
||||
>
|
||||
全部时间 / 重置
|
||||
</Button>
|
||||
{view === "assets" && (
|
||||
<div className="flex w-full flex-wrap items-center gap-3">
|
||||
<select
|
||||
aria-label="记录模型"
|
||||
className={`${selectClass} max-w-full sm:max-w-96`}
|
||||
value={filters.model}
|
||||
onChange={(e) => update({ model: e.target.value })}
|
||||
>
|
||||
<option value="">全部模型</option>
|
||||
{Array.from(modelNames, ([id, name]) => (
|
||||
<option key={id} value={id}>
|
||||
{name} · {id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={filters.featured === "true"}
|
||||
onChange={(e) => update({ featured: String(e.target.checked) })}
|
||||
/>
|
||||
只看精选
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
aria-live="polite"
|
||||
className="flex items-center justify-between text-sm text-muted-foreground"
|
||||
>
|
||||
<span>
|
||||
{total === undefined ? "正在读取记录…" : `共 ${total.toLocaleString()} 条记录`}
|
||||
{view === "assets" && data
|
||||
? ` · 图片 ${data.pagination.totalImages.toLocaleString()} · 视频 ${data.pagination.totalVideos.toLocaleString()}`
|
||||
: ""}
|
||||
</span>
|
||||
{busy && !loading && <span>正在更新…</span>}
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 text-sm text-muted-foreground">
|
||||
<span>
|
||||
第 {page} / {pages} 页 · 每页 40 条
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={busy || page === 1}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={busy || page >= pages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{failure ? (
|
||||
<div role="alert" className="rounded-xl border border-destructive/30 p-6 text-sm">
|
||||
<p>{failure.message}</p>
|
||||
<Button
|
||||
className="mt-3"
|
||||
variant="outline"
|
||||
onClick={() => (view === "assets" ? mutate() : tasks.mutate())}
|
||||
>
|
||||
重试加载
|
||||
</Button>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div role="status" className="space-y-3 rounded-xl border p-6">
|
||||
{[0, 1, 2, 3].map((x) => (
|
||||
<div key={x} className="h-16 rounded-lg bg-muted motion-safe:animate-pulse" />
|
||||
))}
|
||||
<span className="sr-only">正在加载记录</span>
|
||||
</div>
|
||||
) : total === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-12 text-center text-sm text-muted-foreground">
|
||||
没有符合条件的记录,请调整筛选条件。
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-xl border bg-background" aria-busy={busy}>
|
||||
{view === "assets" ? (
|
||||
<table className="w-full min-w-[720px] text-left text-sm">
|
||||
<thead className="bg-muted/50 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
{["产物", "用户", "生成时间", "模型 / 尺寸", "精选", ""].map((v, i) => (
|
||||
<th key={i} className="px-4 py-3 font-medium">
|
||||
{v}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{data?.images.map((item) => (
|
||||
<tr key={item.id} className="hover:bg-muted/30">
|
||||
<td className="p-4">
|
||||
<div>
|
||||
<MediaThumbnail
|
||||
url={item.thumbnailUrl}
|
||||
video={item.recordType === "video"}
|
||||
onOpen={() => openDetails(item)}
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium">{item.userName || item.userEmail}</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{item.userDepartment || "未设置部门"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-3 tabular-nums">
|
||||
{formatRecordTime(item.createdAt)}
|
||||
</td>
|
||||
<td className="max-w-64 px-4 py-3">
|
||||
<div className="truncate" title={item.modelId || ""}>
|
||||
{recordModelNames.get(item.modelId || "") || item.modelId || "未记录模型"}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{item.recordType === "video" ? "视频" : "图片"} ·{" "}
|
||||
{item.imageSize || "未知尺寸"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
{item.isFeatured ? (
|
||||
<span className="inline-flex items-center gap-1 text-amber-700 dark:text-amber-300">
|
||||
<Star className="size-3" />
|
||||
{item.featuredCategory || "精选"}
|
||||
</span>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => openDetails(item)}>
|
||||
详情
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<table className="w-full min-w-[720px] text-left text-sm">
|
||||
<thead className="bg-muted/50">
|
||||
<tr>
|
||||
{["用户 / 时间", "状态", "模型", "耗时", "失败原因 / 任务编号"].map((x) => (
|
||||
<th key={x} className="px-4 py-3 font-medium">
|
||||
{x}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{tasks.data?.tasks.map((task) => (
|
||||
<tr key={task.id}>
|
||||
<td className="px-4 py-4">
|
||||
{task.userName}
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{formatRecordTime(task.createdAt)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-4">
|
||||
{{ failed: "失败", running: "运行中", succeeded: "成功", pending: "排队中" }[
|
||||
task.status
|
||||
] || task.status}
|
||||
</td>
|
||||
<td className="max-w-48 break-words px-4 py-4">{task.model || "自动选择"}</td>
|
||||
<td className="px-4 py-4 tabular-nums">
|
||||
{task.elapsedMs === null ? "—" : `${Math.round(task.elapsedMs / 1000)} 秒`}
|
||||
</td>
|
||||
<td className="max-w-xl break-words px-4 py-4">
|
||||
<p className={task.error ? "text-destructive" : "text-muted-foreground"}>
|
||||
{task.error || "—"}
|
||||
</p>
|
||||
<code className="mt-2 block text-xs text-muted-foreground">{task.id}</code>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
每页 40 条 · 第 {page} / {pages} 页
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" disabled={busy || page === 1} onClick={() => setPage(1)}>
|
||||
首页
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="上一页"
|
||||
variant="outline"
|
||||
disabled={busy || page === 1}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="下一页"
|
||||
variant="outline"
|
||||
disabled={busy || page >= pages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
<Button variant="outline" disabled={busy || page >= pages} onClick={() => setPage(pages)}>
|
||||
末页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Dialog
|
||||
open={!!selected}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelected(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-h-[90vh] max-w-4xl overflow-y-auto bg-background">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{selected?.recordType === "video" ? "视频详情" : "图片详情"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{selected && (
|
||||
<div className="space-y-6">
|
||||
<div className="flex min-h-40 justify-center rounded-xl bg-muted">
|
||||
{selected.recordType === "video" ? (
|
||||
<video
|
||||
src={selected.videoUrl || selected.originalUrl}
|
||||
controls
|
||||
preload="none"
|
||||
className="max-h-[45vh] w-full"
|
||||
/>
|
||||
) : originalFailed ? (
|
||||
<div role="alert" className="p-8 text-sm">
|
||||
原图无法加载,源文件可能已过期或存储不可达。
|
||||
<Button
|
||||
className="ml-3"
|
||||
variant="outline"
|
||||
onClick={() => setOriginalFailed(false)}
|
||||
>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={selected.originalUrl}
|
||||
alt="生成原图"
|
||||
className="max-h-[45vh] object-contain"
|
||||
onError={() => setOriginalFailed(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<dl className="grid gap-4 text-sm sm:grid-cols-2">
|
||||
{[
|
||||
["用户", selected.userName || selected.userEmail],
|
||||
["部门", selected.userDepartment],
|
||||
["生成时间", formatRecordTime(selected.createdAt)],
|
||||
["尺寸", selected.imageSize],
|
||||
["模型", recordModelNames.get(selected.modelId || "") || selected.modelId],
|
||||
["精选时间", selected.featuredAt ? formatRecordTime(selected.featuredAt) : "—"],
|
||||
].map(([k, v]) => (
|
||||
<div key={k}>
|
||||
<dt className="text-xs text-muted-foreground">{k}</dt>
|
||||
<dd className="mt-1 break-words">{v || "未记录"}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<div>
|
||||
<h3 className="text-sm font-medium">提示词</h3>
|
||||
<p className="mt-2 whitespace-pre-wrap break-words text-sm text-muted-foreground">
|
||||
{selected.prompt || "未记录提示词"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button variant="outline" asChild>
|
||||
<a href={selected.originalUrl} target="_blank" rel="noreferrer">
|
||||
<ExternalLink className="mr-2 size-4" />
|
||||
打开原文件
|
||||
</a>
|
||||
</Button>
|
||||
{selected.recordType === "image" && (
|
||||
<Button variant="outline" asChild>
|
||||
<a
|
||||
href={buildImageProxyUrl(selected.originalUrl, { delivery: "original" })}
|
||||
download
|
||||
>
|
||||
<Download className="mr-2 size-4" />
|
||||
下载原图
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{selected.recordType === "image" && (
|
||||
<div className="flex flex-wrap items-center gap-3 rounded-xl border p-4">
|
||||
<select
|
||||
aria-label="精选分类"
|
||||
className={selectClass}
|
||||
value={selected.featuredCategory || ""}
|
||||
onChange={(e) =>
|
||||
setSelected({ ...selected, featuredCategory: e.target.value || null })
|
||||
}
|
||||
>
|
||||
<option value="">未分类</option>
|
||||
{[...new Set([...categories, selected.featuredCategory].filter(Boolean))].map(
|
||||
(c) => (
|
||||
<option key={c} value={c!}>
|
||||
{c}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
onClick={() => save({ featuredCategory: selected.featuredCategory })}
|
||||
>
|
||||
保存分类
|
||||
</Button>
|
||||
<Button
|
||||
disabled={saving}
|
||||
onClick={() => save({ isFeatured: !selected.isFeatured })}
|
||||
>
|
||||
<Star className="mr-2 size-4" />
|
||||
{selected.isFeatured ? "取消精选" : "设为精选"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</AdminSurface>
|
||||
);
|
||||
}
|
||||
@ -1,150 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ImageOff, Video, RotateCw } from "lucide-react";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { isRetiredStorageUrl } from "@/lib/storage/retired-storage";
|
||||
|
||||
import { queuePreview } from "@/lib/admin/preview-queue";
|
||||
|
||||
export function MediaThumbnail({
|
||||
url,
|
||||
video = false,
|
||||
onOpen,
|
||||
}: {
|
||||
url: string;
|
||||
video?: boolean;
|
||||
onOpen?: () => void;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const [state, setState] = useState<"waiting" | "loading" | "ready" | "error">("waiting");
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [source, setSource] = useState("");
|
||||
const [failure, setFailure] = useState("");
|
||||
const retired = isRetiredStorageUrl(url);
|
||||
useEffect(() => {
|
||||
setState("waiting");
|
||||
setSource("");
|
||||
setFailure("");
|
||||
if (video || retired || !url || !container.current) return;
|
||||
let dispose: (() => void) | undefined;
|
||||
let abort = () => {};
|
||||
let objectUrl = "";
|
||||
let alive = true;
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (!entry.isIntersecting || dispose) return;
|
||||
observer.disconnect();
|
||||
dispose = queuePreview((release) => {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 48000);
|
||||
setState("loading");
|
||||
// Fetch is abortable, so leaving a page also stops in-flight previews.
|
||||
const parsed = new URL(url, window.location.origin);
|
||||
const target =
|
||||
parsed.hostname === "scqnycdn.jiansun.vip" && !parsed.search
|
||||
? `${url}?imageView2/2/w/192/q/72/format/webp`
|
||||
: buildImageProxyUrl(url, {
|
||||
width: 192,
|
||||
quality: 72,
|
||||
format: "webp",
|
||||
delivery: "proxy",
|
||||
});
|
||||
fetch(target, { signal: controller.signal })
|
||||
.then(async (response) => {
|
||||
if (!response.ok) {
|
||||
const detail = await response.json().catch(() => null);
|
||||
throw new Error(`${detail?.error || "预览请求失败"}(HTTP ${response.status})`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
if (!blob.type.startsWith("image/")) throw new Error("Not an image");
|
||||
if (alive) {
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setSource(objectUrl);
|
||||
setState("ready");
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (alive) {
|
||||
setFailure(
|
||||
error.name === "AbortError" ? "预览加载超时" : error.message || "预览加载失败",
|
||||
);
|
||||
setState("error");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
release();
|
||||
});
|
||||
abort = () => {
|
||||
controller.abort();
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
});
|
||||
},
|
||||
{ rootMargin: "80px" },
|
||||
);
|
||||
observer.observe(container.current);
|
||||
return () => {
|
||||
alive = false;
|
||||
observer.disconnect();
|
||||
abort();
|
||||
dispose?.();
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
}, [url, video, retired, attempt]);
|
||||
return (
|
||||
<div
|
||||
ref={container}
|
||||
className="relative flex h-16 w-20 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted"
|
||||
data-preview-state={state}
|
||||
>
|
||||
{video ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="查看视频详情"
|
||||
className="flex h-full w-full items-center justify-center"
|
||||
onClick={onOpen}
|
||||
>
|
||||
<Video className="size-5 text-muted-foreground" aria-label="视频,点击查看后播放" />
|
||||
</button>
|
||||
) : retired ? (
|
||||
<span className="text-center text-xs text-muted-foreground">
|
||||
旧存储
|
||||
<br />
|
||||
已停用
|
||||
</span>
|
||||
) : source && state === "ready" ? (
|
||||
<button type="button" aria-label="查看图片详情" className="h-full w-full" onClick={onOpen}>
|
||||
<img
|
||||
src={source}
|
||||
alt="生成结果预览"
|
||||
className="h-full w-full object-contain"
|
||||
onError={() => {
|
||||
setFailure("图片内容无法解码");
|
||||
setState("error");
|
||||
}}
|
||||
/>
|
||||
</button>
|
||||
) : state === "error" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-full w-full flex-col items-center justify-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
title={`${failure},点击重试`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setAttempt((x) => x + 1);
|
||||
}}
|
||||
>
|
||||
<ImageOff className="size-4" />
|
||||
加载失败
|
||||
</button>
|
||||
) : (
|
||||
<RotateCw
|
||||
className={`size-4 text-muted-foreground ${state === "loading" ? "motion-safe:animate-spin" : ""}`}
|
||||
aria-label={state === "loading" ? "正在加载预览" : "等待进入可见区域"}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,191 +0,0 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import useSWR from "swr";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { adminFetcher } from "./media-records-panel";
|
||||
import { formatRecordTime } from "@/lib/admin/record-time";
|
||||
type Event = {
|
||||
id: string;
|
||||
modelDisplayName: string;
|
||||
modelRuntimeId: string;
|
||||
providerName: string;
|
||||
eventType: string;
|
||||
createdAt: string;
|
||||
errorMessage: string;
|
||||
elapsedMs: number | null;
|
||||
consecutiveFailures: number;
|
||||
autoDisabled: boolean;
|
||||
};
|
||||
export function ModelHealthPanel({
|
||||
providers,
|
||||
models,
|
||||
initialModelId = "",
|
||||
}: {
|
||||
initialModelId?: string;
|
||||
providers: Array<{ id: string; name: string }>;
|
||||
models: Array<{ id: string; displayName: string; providerId: string }>;
|
||||
}) {
|
||||
const [filters, setFilters] = useState({
|
||||
providerId: "",
|
||||
modelId: initialModelId,
|
||||
eventType: "",
|
||||
startDate: "",
|
||||
endDate: "",
|
||||
});
|
||||
const [page, setPage] = useState(1);
|
||||
const query = new URLSearchParams({ ...filters, page: String(page), limit: "20" });
|
||||
const { data, error, isLoading, isValidating, mutate } = useSWR<{
|
||||
events: Event[];
|
||||
hasMore: boolean;
|
||||
}>(`/api/admin/ai-model-health?${query}`, adminFetcher, {
|
||||
keepPreviousData: true,
|
||||
revalidateOnFocus: false,
|
||||
});
|
||||
const update = (change: Partial<typeof filters>) => {
|
||||
setFilters((f) => ({ ...f, ...change }));
|
||||
setPage(1);
|
||||
};
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">运行健康</h3>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
按上游和模型追踪故障,查看完整原因与发生时间。
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{[
|
||||
["providerId", "全部上游", providers.map((p) => [p.id, p.name])],
|
||||
[
|
||||
"modelId",
|
||||
"全部模型",
|
||||
models
|
||||
.filter((m) => !filters.providerId || m.providerId === filters.providerId)
|
||||
.map((m) => [m.id, m.displayName]),
|
||||
],
|
||||
[
|
||||
"eventType",
|
||||
"全部错误",
|
||||
[
|
||||
["quota", "额度 / 余额"],
|
||||
["timeout", "超时"],
|
||||
["unavailable", "不可用"],
|
||||
["invalid_model", "模型不可用"],
|
||||
["download_error", "结果下载失败"],
|
||||
["error", "其他错误"],
|
||||
["success", "成功"],
|
||||
],
|
||||
],
|
||||
].map(([key, label, options]) => (
|
||||
<select
|
||||
key={key as string}
|
||||
aria-label={label as string}
|
||||
className="h-10 max-w-64 rounded-md border bg-background px-3 text-sm"
|
||||
value={filters[key as keyof typeof filters]}
|
||||
onChange={(e) =>
|
||||
update({
|
||||
[key as string]: e.target.value,
|
||||
...(key === "providerId" ? { modelId: "" } : {}),
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">{label as string}</option>
|
||||
{(options as string[][]).map(([value, text]) => (
|
||||
<option key={value} value={value}>
|
||||
{text}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
))}
|
||||
<Input
|
||||
aria-label="故障开始日期"
|
||||
className="h-10 w-40"
|
||||
type="date"
|
||||
value={filters.startDate}
|
||||
onChange={(e) => update({ startDate: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
aria-label="故障结束日期"
|
||||
className="h-10 w-40"
|
||||
type="date"
|
||||
value={filters.endDate}
|
||||
onChange={(e) => update({ endDate: e.target.value })}
|
||||
/>
|
||||
<Button variant="outline" disabled={isValidating} onClick={() => mutate()}>
|
||||
刷新日志
|
||||
</Button>
|
||||
</div>
|
||||
{error ? (
|
||||
<p role="alert" className="p-6 text-sm text-destructive">
|
||||
日志加载失败,请点击刷新重试。
|
||||
</p>
|
||||
) : isLoading ? (
|
||||
<p role="status" className="p-6 text-sm">
|
||||
正在加载故障日志…
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y rounded-xl border">
|
||||
{data?.events.map((event) => (
|
||||
<div key={event.id} className="p-4">
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<strong className="font-semibold">
|
||||
{event.modelDisplayName || event.modelRuntimeId || "已删除模型"}
|
||||
</strong>
|
||||
<span className="text-muted-foreground">{event.providerName || "未知上游"}</span>
|
||||
<span className="rounded bg-muted px-2 py-1 text-xs">
|
||||
{{
|
||||
quota: "额度 / 余额",
|
||||
timeout: "超时",
|
||||
unavailable: "不可用",
|
||||
error: "服务错误",
|
||||
invalid_model: "模型不可用",
|
||||
download_error: "结果下载失败",
|
||||
success: "成功",
|
||||
}[event.eventType] || event.eventType}
|
||||
</span>
|
||||
<time className="ml-auto text-xs tabular-nums text-muted-foreground">
|
||||
{formatRecordTime(event.createdAt)}
|
||||
</time>
|
||||
</div>
|
||||
<p className="mt-3 whitespace-pre-wrap break-words text-sm">
|
||||
{event.errorMessage || "未记录详细原因"}
|
||||
</p>
|
||||
<div className="mt-2 flex gap-4 text-xs text-muted-foreground">
|
||||
<span>连续失败 {event.consecutiveFailures} 次</span>
|
||||
{event.elapsedMs !== null && (
|
||||
<span>耗时 {Math.round(event.elapsedMs / 1000)} 秒</span>
|
||||
)}
|
||||
{event.autoDisabled && <span>已自动停用</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!data?.events.length && (
|
||||
<p className="p-12 text-center text-sm text-muted-foreground">该范围内没有故障记录。</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
第 {page} 页{isValidating && " · 正在更新…"}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={page === 1 || isValidating}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={!data?.hasMore || isValidating}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,326 +0,0 @@
|
||||
"use client";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Search, RefreshCw, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { AiModel } from "@/lib/db/schema";
|
||||
import {
|
||||
is3DModelDescriptor,
|
||||
isVideoModelDescriptor,
|
||||
isImageGenerationModelDescriptor,
|
||||
} from "@/lib/ai/model-classification";
|
||||
|
||||
type Model = AiModel & { isAgentModel?: boolean; isMultimodal?: boolean };
|
||||
type Provider = { id: string; name: string; type: string; isEnabled: boolean };
|
||||
const selectClass = "h-10 rounded-md border bg-background px-3 text-sm";
|
||||
export function ModelManagementList({
|
||||
models,
|
||||
providers,
|
||||
error,
|
||||
loading,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onRestore,
|
||||
onRefresh,
|
||||
onHealth,
|
||||
}: {
|
||||
models: Model[];
|
||||
providers: Provider[];
|
||||
error?: Error;
|
||||
loading: boolean;
|
||||
onEdit: (model: Model) => Promise<void>;
|
||||
onDelete: (id: string) => void;
|
||||
onRestore: (model: Model) => void;
|
||||
onRefresh: () => void;
|
||||
onHealth?: (id: string) => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [provider, setProvider] = useState("");
|
||||
const [status, setStatus] = useState("enabled");
|
||||
const [kind, setKind] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [opening, setOpening] = useState<string | null>(null);
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
models
|
||||
.map((model) => {
|
||||
const upstream = providers.find((p) => p.id === model.providerId);
|
||||
const descriptor = { ...model, providerType: upstream?.type };
|
||||
const type = is3DModelDescriptor(descriptor)
|
||||
? "3d"
|
||||
: isVideoModelDescriptor(descriptor)
|
||||
? "video"
|
||||
: isImageGenerationModelDescriptor(descriptor)
|
||||
? "image"
|
||||
: "chat";
|
||||
return { model, upstream, type };
|
||||
})
|
||||
.filter(({ model, upstream, type }) => {
|
||||
const text =
|
||||
`${model.displayName} ${model.modelId} ${upstream?.name || ""}`.toLowerCase();
|
||||
return (
|
||||
text.includes(search.trim().toLowerCase()) &&
|
||||
(!provider || model.providerId === provider) &&
|
||||
(!kind || kind === type) &&
|
||||
(status === "all" ||
|
||||
(status === "enabled" && model.isEnabled) ||
|
||||
(status === "disabled" && !model.isEnabled) ||
|
||||
(status === "unhealthy" && model.healthStatus !== "healthy") ||
|
||||
(status === "visible" && !model.isHidden))
|
||||
);
|
||||
}),
|
||||
[models, providers, search, provider, status, kind],
|
||||
);
|
||||
const pages = Math.max(1, Math.ceil(rows.length / 25));
|
||||
const currentPage = Math.min(page, pages);
|
||||
const change = (fn: () => void) => {
|
||||
fn();
|
||||
setPage(1);
|
||||
};
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<div className="relative min-w-56 flex-1">
|
||||
<Search className="absolute left-3 top-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-10 pl-9"
|
||||
aria-label="搜索模型"
|
||||
placeholder="搜索模型名称、ID 或上游"
|
||||
value={search}
|
||||
onChange={(e) => change(() => setSearch(e.target.value))}
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
aria-label="模型上游"
|
||||
className={selectClass}
|
||||
value={provider}
|
||||
onChange={(e) => change(() => setProvider(e.target.value))}
|
||||
>
|
||||
<option value="">全部上游</option>
|
||||
{providers.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="模型类型"
|
||||
className={selectClass}
|
||||
value={kind}
|
||||
onChange={(e) => change(() => setKind(e.target.value))}
|
||||
>
|
||||
<option value="">全部类型</option>
|
||||
<option value="image">生图</option>
|
||||
<option value="video">视频</option>
|
||||
<option value="chat">对话</option>
|
||||
<option value="3d">3D / CAD</option>
|
||||
</select>
|
||||
<select
|
||||
aria-label="模型状态"
|
||||
className={selectClass}
|
||||
value={status}
|
||||
onChange={(e) => change(() => setStatus(e.target.value))}
|
||||
>
|
||||
<option value="enabled">已启用</option>
|
||||
<option value="all">全部模型</option>
|
||||
<option value="disabled">已停用</option>
|
||||
<option value="unhealthy">运行异常</option>
|
||||
<option value="visible">前台可见</option>
|
||||
</select>
|
||||
<Button variant="outline" onClick={onRefresh} aria-label="刷新模型">
|
||||
<RefreshCw className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{loading
|
||||
? "正在加载模型…"
|
||||
: `筛选结果 ${rows.length} 个 · 已启用 ${models.filter((m) => m.isEnabled).length} 个 · 全部 ${models.length} 个`}
|
||||
</p>
|
||||
<div className="flex items-center justify-end gap-2 text-sm text-muted-foreground">
|
||||
<span>
|
||||
第 {currentPage} / {pages} 页
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setPage(currentPage - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={currentPage === pages}
|
||||
onClick={() => setPage(currentPage + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
{error ? (
|
||||
<div role="alert" className="rounded-xl border p-6 text-sm">
|
||||
模型加载失败。
|
||||
<Button variant="outline" onClick={onRefresh}>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div role="status" className="h-48 rounded-xl bg-muted motion-safe:animate-pulse" />
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<table className="w-full min-w-[850px] text-left text-sm">
|
||||
<thead className="bg-muted/50 text-xs text-muted-foreground">
|
||||
<tr>
|
||||
{["模型", "上游 / 类型", "启用", "前台展示", "运行健康", "操作"].map((x) => (
|
||||
<th key={x} className="px-4 py-3 font-medium">
|
||||
{x}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{rows
|
||||
.slice((currentPage - 1) * 25, currentPage * 25)
|
||||
.map(({ model, upstream, type }) => (
|
||||
<tr key={model.id} className="hover:bg-muted/30">
|
||||
<td className="max-w-64 px-4 py-4">
|
||||
<div className="font-medium">{model.displayName}</div>
|
||||
<div
|
||||
className="mt-1 truncate text-xs text-muted-foreground"
|
||||
title={model.modelId}
|
||||
>
|
||||
{model.modelId}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground">
|
||||
{model.isDefault && <span>默认模型</span>}
|
||||
{model.isDefaultTextEditModel && <span>文字编辑默认</span>}
|
||||
{model.isAgentModel && <span>Agent</span>}
|
||||
{model.isMultimodal && <span>多模态</span>}
|
||||
{model.isSubModel && <span>子模型</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-4">
|
||||
{upstream?.name || "未知上游"}
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
{{ image: "生图", video: "视频", chat: "对话", "3d": "3D / CAD" }[type]}
|
||||
{upstream && !upstream.isEnabled ? " · 上游已停用" : ""}
|
||||
</div>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-4 py-4">
|
||||
<span
|
||||
className={`rounded-md px-2 py-1 text-xs ${model.isEnabled ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-200" : "bg-muted text-muted-foreground"}`}
|
||||
>
|
||||
{model.isEnabled ? "已启用" : "已停用"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-4">
|
||||
{model.isHidden || model.isSubModel ? "隐藏" : "可见"}
|
||||
</td>
|
||||
<td className="max-w-72 px-4 py-4">
|
||||
<span
|
||||
className={
|
||||
model.healthStatus !== "healthy"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-muted-foreground"
|
||||
}
|
||||
>
|
||||
{model.healthStatus === "auto_disabled"
|
||||
? "自动停用"
|
||||
: model.healthStatus === "degraded"
|
||||
? "观察中"
|
||||
: "正常"}
|
||||
</span>
|
||||
{model.healthConsecutiveFailures > 0 && (
|
||||
<span className="ml-2 text-xs text-muted-foreground">
|
||||
连续失败 {model.healthConsecutiveFailures} 次
|
||||
</span>
|
||||
)}
|
||||
{model.healthLastError && (
|
||||
<details className="mt-2 text-xs">
|
||||
<summary className="cursor-pointer text-muted-foreground">
|
||||
查看最近原因
|
||||
</summary>
|
||||
<p className="mt-2 whitespace-pre-wrap break-words">
|
||||
{model.healthLastError}
|
||||
</p>
|
||||
</details>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="mt-2 block text-xs underline underline-offset-4"
|
||||
onClick={() => onHealth?.(model.id)}
|
||||
>
|
||||
故障记录
|
||||
</button>
|
||||
<div className="mt-2 text-xs text-muted-foreground">
|
||||
{model.excludeFromHealthBan && "不自动封禁 "}
|
||||
{model.excludeFromFailover && "不参与迁移"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-4">
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={opening !== null}
|
||||
onClick={async () => {
|
||||
setOpening(model.id);
|
||||
try {
|
||||
await onEdit(model);
|
||||
} finally {
|
||||
setOpening(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{opening === model.id ? "加载中…" : "编辑"}
|
||||
</Button>
|
||||
{model.healthStatus === "auto_disabled" && (
|
||||
<Button variant="outline" size="sm" onClick={() => onRestore(model)}>
|
||||
恢复
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-destructive"
|
||||
onClick={() => onDelete(model.id)}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{rows.length === 0 && (
|
||||
<p className="p-12 text-center text-sm text-muted-foreground">没有符合条件的模型。</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between text-sm text-muted-foreground">
|
||||
<span>
|
||||
每页 25 个 · 第 {currentPage} / {pages} 页
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
aria-label="上一页模型"
|
||||
variant="outline"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setPage(currentPage - 1)}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="下一页模型"
|
||||
variant="outline"
|
||||
disabled={currentPage === pages}
|
||||
onClick={() => setPage(currentPage + 1)}
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import { DefaultChatTransport } from "ai";
|
||||
@ -576,11 +575,31 @@ export function AgentGenerationWorkspace({
|
||||
toast.error("图片地址无效");
|
||||
return;
|
||||
}
|
||||
|
||||
const filename = buildDownloadFilename(raw);
|
||||
try {
|
||||
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||
toast.success("原图已开始下载");
|
||||
} catch (error) {
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
const response = await fetch(raw);
|
||||
if (!response.ok) {
|
||||
throw new Error(`download failed: ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} catch {
|
||||
const link = document.createElement("a");
|
||||
link.href = raw;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
toast.message("已打开原图,可右键另存为");
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@ -1,10 +1,7 @@
|
||||
"use client";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import { BEFORE_PAGE_REFRESH, type PageRefreshRequest } from "@/lib/client/page-refresh";
|
||||
import { appendGenerationMessage, mergeGenerationHistory, parseAppendedGenerationMessage, recoverReplacementRun } from "@/lib/agents/replacement-run-recovery";
|
||||
import { getSceneRunResult } from "@/lib/agents/scene-run-recovery";
|
||||
import type { DetailReplacementBatchCard } from "@/lib/agents/detail-replacement-batch";
|
||||
import { DefaultChatTransport } from "ai";
|
||||
import {
|
||||
@ -159,7 +156,6 @@ import type {
|
||||
} from "@/types/agent";
|
||||
import {
|
||||
createEmptyAgentModeWorkspaceState,
|
||||
MAX_DETAIL_REPLACEMENT_REFERENCES,
|
||||
} from "@/lib/agents/mode-workspace-state";
|
||||
import {
|
||||
createEmptyAgentGenerationProjectWorkspaceState,
|
||||
@ -177,7 +173,6 @@ export interface AgentGenerationWorkspaceDarkV2Props {
|
||||
workflowFeatureSettings?: AgentWorkflowPageFeatureSettings | null;
|
||||
workflowPromptOptimizationEnabled?: boolean;
|
||||
getLatestWorkflowContext?: () => AgentWorkflowComposerContext | null;
|
||||
getWorkflowPromptStatus?: () => "ready" | "loading" | "error";
|
||||
onBack?: () => void;
|
||||
brandStorePanel?: ReactNode;
|
||||
materialSelectionPanel?: ReactNode;
|
||||
@ -214,7 +209,6 @@ export interface AgentGenerationWorkspaceDarkV2Props {
|
||||
interface AgentWorkflowModelOption {
|
||||
id: string;
|
||||
displayName: string;
|
||||
providerName?: string;
|
||||
providerType: string;
|
||||
supportsImageGen?: boolean;
|
||||
isMultimodal?: boolean;
|
||||
@ -2645,9 +2639,7 @@ function getStoredAgentPendingGenerations(): LocalGenerationPendingState[] {
|
||||
? record.requestedCardIds
|
||||
.map((entry) => String(entry || "").trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, record.modeType === "detail_replacement"
|
||||
? MAX_DETAIL_REPLACEMENT_REFERENCES
|
||||
: MAX_AGENT_MODE_REFERENCE_COUNT)
|
||||
.slice(0, MAX_AGENT_MODE_REFERENCE_COUNT)
|
||||
: null,
|
||||
} satisfies LocalGenerationPendingState;
|
||||
});
|
||||
@ -3090,7 +3082,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
workflowFeatureSettings = null,
|
||||
workflowPromptOptimizationEnabled = true,
|
||||
getLatestWorkflowContext,
|
||||
getWorkflowPromptStatus,
|
||||
onBack,
|
||||
brandStorePanel,
|
||||
materialSelectionPanel,
|
||||
@ -3388,13 +3379,12 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
}
|
||||
);
|
||||
|
||||
const { data: modelsData, error: modelsError, mutate: refreshModels } = useSWR<{
|
||||
const { data: modelsData } = useSWR<{
|
||||
models: AgentWorkflowModelOption[];
|
||||
defaultModelId?: string | null;
|
||||
agentWorkflowConfiguredDefaultModelId?: string | null;
|
||||
agentWorkflowDefaultModelId?: string | null;
|
||||
agentWorkflowConfiguredModels?: AgentWorkflowModelOption[];
|
||||
detailReplacementModel?: AgentWorkflowModelOption | null;
|
||||
agentModel?: any;
|
||||
}>("/api/models", fetcher);
|
||||
|
||||
@ -3440,6 +3430,17 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
const activeBusinessModeDefaultModelId = !requiresPresetSelection
|
||||
? String(activeBusinessMode?.defaultModelId || "").trim() || null
|
||||
: null;
|
||||
const lockedWorkflowModelId =
|
||||
activeBusinessModeDefaultModelId ||
|
||||
selectedAgentPreset?.defaultModelId ||
|
||||
modelsData?.agentWorkflowConfiguredDefaultModelId ||
|
||||
modelsData?.agentWorkflowDefaultModelId ||
|
||||
null;
|
||||
const isWorkflowModelLocked = Boolean(lockedWorkflowModelId);
|
||||
const effectiveDefaultModelId =
|
||||
lockedWorkflowModelId ||
|
||||
modelsData?.defaultModelId ||
|
||||
null;
|
||||
const presetDrivenResultModeType: AgentGenerationResultModeType =
|
||||
selectedAgentPreset?.type === "image" && presetModeConfig.modeType === "detail_replacement"
|
||||
? detailReplacementMethod === "ai_detail_generate"
|
||||
@ -3455,19 +3456,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
const currentResultModeType: AgentGenerationResultModeType = requiresPresetSelection
|
||||
? presetDrivenResultModeType
|
||||
: businessModeResultModeType;
|
||||
const detailReplacementModel = currentResultModeType === "detail_replacement"
|
||||
? modelsData?.detailReplacementModel
|
||||
: null;
|
||||
const isDetailReplacementModelLoading = currentResultModeType === "detail_replacement" && !modelsData;
|
||||
const lockedWorkflowModelId =
|
||||
detailReplacementModel?.id ||
|
||||
activeBusinessModeDefaultModelId ||
|
||||
selectedAgentPreset?.defaultModelId ||
|
||||
modelsData?.agentWorkflowConfiguredDefaultModelId ||
|
||||
modelsData?.agentWorkflowDefaultModelId ||
|
||||
null;
|
||||
const isWorkflowModelLocked = Boolean(lockedWorkflowModelId);
|
||||
const effectiveDefaultModelId = lockedWorkflowModelId || modelsData?.defaultModelId || null;
|
||||
const isSceneGenerationPreset = currentResultModeType === "scene_generation";
|
||||
const isDetailReplacementPreset =
|
||||
currentResultModeType === "detail_replacement" ||
|
||||
@ -4119,15 +4107,12 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
);
|
||||
const executableModelOptions = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const workflowModels = detailReplacementModel
|
||||
? [detailReplacementModel, ...configuredWorkflowModels]
|
||||
: configuredWorkflowModels;
|
||||
return [...selectableModels, ...workflowModels].filter((model) => {
|
||||
return [...selectableModels, ...configuredWorkflowModels].filter((model) => {
|
||||
if (seen.has(model.id)) return false;
|
||||
seen.add(model.id);
|
||||
return true;
|
||||
});
|
||||
}, [configuredWorkflowModels, detailReplacementModel, selectableModels]);
|
||||
}, [configuredWorkflowModels, selectableModels]);
|
||||
const executableModelIdSet = useMemo(
|
||||
() => new Set(executableModelOptions.map((model) => model.id)),
|
||||
[executableModelOptions]
|
||||
@ -4146,9 +4131,8 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
selectableModels[0],
|
||||
[executableModelOptions, lockedWorkflowModel, selectableModels, selectedModelId]
|
||||
);
|
||||
const lockedWorkflowModelLabel = detailReplacementModel?.providerName
|
||||
? `${detailReplacementModel.displayName} 「${detailReplacementModel.providerName}」`
|
||||
: lockedWorkflowModel?.displayName ||
|
||||
const lockedWorkflowModelLabel =
|
||||
lockedWorkflowModel?.displayName ||
|
||||
selectedAgentPreset?.defaultModel?.displayName ||
|
||||
(lockedWorkflowModelId ? `配置模型不可用(${lockedWorkflowModelId})` : "未配置");
|
||||
const [activeToolStep, setActiveToolStep] = useState<ToolStepKey>("settings");
|
||||
@ -4185,7 +4169,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
? "agent-anchor-materials"
|
||||
: "agent-anchor-generate";
|
||||
|
||||
const [finishedSceneRequestId, setFinishedSceneRequestId] = useState<string | null>(null);
|
||||
const {
|
||||
messages,
|
||||
setMessages,
|
||||
@ -4206,11 +4189,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
void refreshHistory();
|
||||
}
|
||||
},
|
||||
onFinish({ messages: finishedMessages }) {
|
||||
const lastUser = finishedMessages.filter((message) => message.role === "user").at(-1);
|
||||
setFinishedSceneRequestId(lastUser?.id || null);
|
||||
void refreshHistory();
|
||||
},
|
||||
onFinish() { void refreshHistory(); },
|
||||
experimental_throttle: 100,
|
||||
generateId: generateUUID,
|
||||
transport: new DefaultChatTransport({
|
||||
@ -4893,14 +4872,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
return recoverReplacementRun({ messages, ...pendingGeneration });
|
||||
}, [messages, pendingGeneration]);
|
||||
const transportIsGenerating = status === "streaming" || status === "submitted";
|
||||
useEffect(() => {
|
||||
const beforeRefresh = (event: Event) => {
|
||||
if (transportIsGenerating || pendingGeneration)
|
||||
(event as CustomEvent<PageRefreshRequest>).detail.block("当前生图任务仍在处理中,请等待结果返回后再刷新。原任务无需重新提交。");
|
||||
};
|
||||
window.addEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
return () => window.removeEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
}, [transportIsGenerating, pendingGeneration]);
|
||||
const pendingGenerationProgressCount = useMemo(() => {
|
||||
if (!pendingGeneration) {
|
||||
return 0;
|
||||
@ -5511,17 +5482,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
setActiveResultModeType(currentResultModeType);
|
||||
}, [currentResultModeType]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingGeneration?.requestMessageId || pendingGeneration.modeType !== "scene_generation" || transportIsGenerating) return;
|
||||
const result = getSceneRunResult(messages, pendingGeneration.requestMessageId);
|
||||
const persisted = getSceneRunResult(historyMessages, pendingGeneration.requestMessageId);
|
||||
if (!result || (finishedSceneRequestId !== pendingGeneration.requestMessageId && !persisted?.count)) return;
|
||||
setPendingGeneration(null);
|
||||
if (result.count < pendingGeneration.expectedCount) {
|
||||
toast.warning(`本次生成已结束,收到 ${result.count}/${pendingGeneration.expectedCount} 张图片。缺少的图片未继续生成,可调整张数后重新提交。`);
|
||||
}
|
||||
}, [pendingGeneration, transportIsGenerating, finishedSceneRequestId, messages, historyMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingGeneration || pendingGeneration.backendTaskId || !replacementRunRecovery.done) return;
|
||||
// The backend has settled every requested card; an open SSE connection is no longer work.
|
||||
@ -6327,24 +6287,10 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
toast.error(`请先查询并选择${detailReferenceSourceLabel}参考图`);
|
||||
return;
|
||||
}
|
||||
if (isDetailReplacementModelLoading) {
|
||||
if (modelsError) {
|
||||
toast.error("详情替换模型加载失败,正在重新读取");
|
||||
void refreshModels().catch(() => {});
|
||||
} else {
|
||||
toast.info("正在读取详情替换模型,请稍候");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isSkuReplacementPreset && skuReplacementReferenceCards.length === 0) {
|
||||
toast.error(`请先查询并选择${skuReferenceSourceLabel}参考图`);
|
||||
return;
|
||||
}
|
||||
const promptStatus = getWorkflowPromptStatus?.();
|
||||
if (promptStatus === "loading" || promptStatus === "error") {
|
||||
toast.error(promptStatus === "error" ? "请先在风格模板区重试加载提示词" : "正在加载所选模板的提示词,请稍候");
|
||||
return;
|
||||
}
|
||||
const resolvedWorkflowContext = getLatestWorkflowContext?.() ?? workflowContext;
|
||||
if (
|
||||
isDetailReplacementPreset &&
|
||||
@ -6403,10 +6349,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
}
|
||||
if (replacementModeType === "detail_replacement") {
|
||||
if (detailBatchSubmittingRef.current) return;
|
||||
if (replacementExecutionCards.length > MAX_DETAIL_REPLACEMENT_REFERENCES) {
|
||||
toast.error(`本次选中了 ${replacementExecutionCards.length} 张详情参考图,一次最多替换 ${MAX_DETAIL_REPLACEMENT_REFERENCES} 张,请减少本次选择后重试`);
|
||||
return;
|
||||
}
|
||||
if (!isValidChatUuid(projectId)) {
|
||||
toast.error("当前风格化项目尚未保存,请先保存项目后再执行详情替换");
|
||||
return;
|
||||
@ -6427,14 +6369,13 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
const saved = await onPersistProject?.();
|
||||
if (saved === false) throw new Error("项目尚未保存,请重试");
|
||||
const requestId = generateUUID();
|
||||
const response = await fetch("/api/agents/detail-replacement/batches", {
|
||||
const response = await fetchWithErrorHandlers("/api/agents/detail-replacement/batches", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
projectId,
|
||||
requestId,
|
||||
model: resolvedModelId,
|
||||
expectedModelId: resolvedModelId === "auto" ? undefined : resolvedModelId,
|
||||
imageSize: imageParams.imageSize,
|
||||
replacementStrategy: detailReplacementStrategy,
|
||||
prompt: detailReplacementStrategy === "product_only"
|
||||
@ -6458,7 +6399,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !payload?.task?.id) {
|
||||
if (payload?.code === "DETAIL_REPLACEMENT_MODEL_CHANGED") void refreshModels().catch(() => {});
|
||||
throw new Error(payload?.error || "详情替换任务提交失败");
|
||||
}
|
||||
setPendingGeneration({
|
||||
@ -6646,8 +6586,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
input,
|
||||
isDetailAiGenerationMethod,
|
||||
isDetailReplacementPreset,
|
||||
isDetailReplacementModelLoading,
|
||||
modelsError,
|
||||
isSelectedBusinessModeUnavailable,
|
||||
isSkuReplacementPreset,
|
||||
effectiveDefaultModelId,
|
||||
@ -6664,7 +6602,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
skuResultCards,
|
||||
userMessageCount,
|
||||
getLatestWorkflowContext,
|
||||
getWorkflowPromptStatus,
|
||||
isSceneGenerationPreset,
|
||||
workflowContext,
|
||||
sceneMessageAttachments,
|
||||
@ -6675,7 +6612,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
onPersistProject,
|
||||
projectId,
|
||||
refreshDetailBatch,
|
||||
refreshModels,
|
||||
]);
|
||||
const handleStopGeneration = useCallback(() => {
|
||||
detailGenerationCancelRef.current = true;
|
||||
@ -6840,11 +6776,31 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
toast.error("图片地址无效");
|
||||
return;
|
||||
}
|
||||
|
||||
const filename = buildDownloadFilename(raw);
|
||||
try {
|
||||
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||
toast.success("原图已开始下载");
|
||||
} catch (error) {
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
const response = await fetch(raw);
|
||||
if (!response.ok) {
|
||||
throw new Error(`download failed: ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} catch {
|
||||
const link = document.createElement("a");
|
||||
link.href = raw;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
toast.message("已打开原图,可右键另存为");
|
||||
}
|
||||
}, []);
|
||||
const uploadBase64ResultToStorage = useCallback(async (base64Url: string) => {
|
||||
@ -7839,11 +7795,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
toast.error(detailGenerationValidationIssues[0] || "请先补齐 AI详情生成参数");
|
||||
return;
|
||||
}
|
||||
const promptStatus = getWorkflowPromptStatus?.();
|
||||
if (promptStatus === "loading" || promptStatus === "error") {
|
||||
toast.error(promptStatus === "error" ? "请先在风格模板区重试加载提示词" : "正在加载所选模板的提示词,请稍候");
|
||||
return;
|
||||
}
|
||||
|
||||
const productAttachments = detailGenerationProductSlotIndexes.map((index) =>
|
||||
detailGenerationSlots[index]
|
||||
@ -9448,11 +9399,9 @@ export function AgentGenerationWorkspaceDarkV2({
|
||||
</Select>
|
||||
) : (
|
||||
<div className="rounded-[24px] border border-white/10 bg-black/30 px-4 py-3 text-sm text-white/70">
|
||||
{isDetailReplacementModelLoading
|
||||
? modelsError ? "详情替换模型加载失败,点击批量替换可重试" : "正在读取详情替换模型"
|
||||
: isWorkflowModelLocked ? "后台已锁定生图模型:" : "当前生图模式使用默认模型:"}
|
||||
{isWorkflowModelLocked ? "后台已锁定生图模型:" : "当前生图模式使用默认模型:"}
|
||||
<span className="ml-2 font-medium text-white">
|
||||
{isDetailReplacementModelLoading ? null : isWorkflowModelLocked
|
||||
{isWorkflowModelLocked
|
||||
? lockedWorkflowModelLabel
|
||||
: currentModel?.displayName || "自动选择"}
|
||||
</span>
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import { DefaultChatTransport } from "ai";
|
||||
@ -726,11 +725,30 @@ export function AgentGenerationWorkspaceNew({
|
||||
toast.error("图片地址无效");
|
||||
return;
|
||||
}
|
||||
const filename = buildDownloadFilename(raw);
|
||||
try {
|
||||
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||
toast.success("原图已开始下载");
|
||||
} catch (error) {
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
const response = await fetch(raw);
|
||||
if (!response.ok) {
|
||||
throw new Error(`download failed: ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} catch {
|
||||
const link = document.createElement("a");
|
||||
link.href = raw;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
toast.message("已打开原图,可右键另存为");
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
import { useMemo } from "react";
|
||||
import useSWR from "swr";
|
||||
import { Check, ImageIcon, Loader2, UserRound } from "lucide-react";
|
||||
import { AgentPreviewImage } from "@/components/agents/AgentPreviewImage";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn, fetcher } from "@/lib/utils";
|
||||
import { normalizeAgentWorkflowBrandModelConfig } from "@/lib/agents/workflow-brand-model-config";
|
||||
@ -230,11 +229,12 @@ export function AgentWorkflowBrandModelPicker({
|
||||
isDark ? "bg-white/[0.04]" : "bg-muted/40"
|
||||
)}
|
||||
>
|
||||
<AgentPreviewImage
|
||||
<img
|
||||
src={image.imageUrl}
|
||||
alt={image.displayName || `${normalizedBrand} 模特图`}
|
||||
className="h-full w-full object-cover"
|
||||
previewWidth={360}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<div className="absolute inset-x-0 top-0 flex items-center justify-between px-2 py-2">
|
||||
<span className="rounded-full bg-black/60 px-2 py-1 text-[11px] text-white">
|
||||
|
||||
@ -1,77 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter } from "@/components/ui/alert-dialog";
|
||||
import { isPageDownloadActive, preparePageRefresh, subscribeToPageDownloadActivity } from "@/lib/client/page-refresh";
|
||||
|
||||
export function AppUpdateNotice() {
|
||||
const [availableVersion, setAvailableVersion] = useState("");
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const downloading = useSyncExternalStore(subscribeToPageDownloadActivity, isPageDownloadActive, () => false);
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let controller: AbortController | undefined;
|
||||
let checking = false;
|
||||
const check = async () => {
|
||||
if (disposed || checking || document.visibilityState !== "visible") return;
|
||||
checking = true;
|
||||
controller = new AbortController();
|
||||
const current = controller;
|
||||
const timeout = window.setTimeout(() => current.abort(), 8000);
|
||||
try {
|
||||
const response = await fetch("/api/app-version", { cache: "no-store", signal: current.signal });
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
if (!disposed && !current.signal.aborted && typeof data.version === "string" && data.version)
|
||||
setAvailableVersion(data.version !== (process.env.NEXT_PUBLIC_APP_RELEASE || "development") ? data.version : "");
|
||||
} catch {
|
||||
// A failed version read leaves the current workspace available.
|
||||
} finally {
|
||||
window.clearTimeout(timeout);
|
||||
checking = false;
|
||||
}
|
||||
};
|
||||
void check();
|
||||
const interval = window.setInterval(check, 60_000);
|
||||
window.addEventListener("focus", check);
|
||||
window.addEventListener("online", check);
|
||||
document.addEventListener("visibilitychange", check);
|
||||
return () => {
|
||||
disposed = true;
|
||||
controller?.abort();
|
||||
clearInterval(interval);
|
||||
window.removeEventListener("focus", check);
|
||||
window.removeEventListener("online", check);
|
||||
document.removeEventListener("visibilitychange", check);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refresh = async () => {
|
||||
if (refreshing) return;
|
||||
setRefreshing(true);
|
||||
setError("");
|
||||
try {
|
||||
await preparePageRefresh();
|
||||
window.location.reload();
|
||||
setRefreshing(false);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "当前内容同步失败,请保留此页并重试。");
|
||||
setRefreshing(false);
|
||||
}
|
||||
};
|
||||
return <AlertDialog open={Boolean(availableVersion) && !downloading}>
|
||||
<AlertDialogContent className="z-[10001]" overlayClassName="z-[10000]" onEscapeKeyDown={event => event.preventDefault()}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>平台已更新</AlertDialogTitle>
|
||||
<AlertDialogDescription>需要刷新页面后继续使用。点击后会先同步当前画布并保留输入;正在处理的任务完成后再刷新。</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}
|
||||
<AlertDialogFooter>
|
||||
{error ? <Button variant="outline" disabled={refreshing} onClick={() => { setAvailableVersion(""); setError(""); }}>返回处理</Button> : null}
|
||||
<Button disabled={refreshing} onClick={() => void refresh()}>{refreshing ? "正在同步内容…" : "同步并刷新"}</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>;
|
||||
}
|
||||
@ -72,13 +72,13 @@ export function AudioGenerationComposer({
|
||||
setError("");
|
||||
setSending(true);
|
||||
try {
|
||||
if (!model) throw Error("当前模式没有已启用的模型");
|
||||
if (!model) throw Error("当前模式没有已启用的官方模型");
|
||||
const params = audioRequestSchema.parse({
|
||||
...draft,
|
||||
text: [draft.text, connectedText].filter(Boolean).join("\n\n"),
|
||||
modelRef: model.id,
|
||||
voice,
|
||||
format: format || "wav",
|
||||
format,
|
||||
...(!contract?.controls ? { rate: 1, pitch: 1, volume: 50 } : {}),
|
||||
...(!contract?.instructions ? { instructions: "" } : {}),
|
||||
});
|
||||
@ -96,9 +96,9 @@ export function AudioGenerationComposer({
|
||||
<section
|
||||
className="fixed bottom-8 left-1/2 z-[100] max-h-[75vh] w-[min(620px,94vw)] -translate-x-1/2 overflow-y-auto rounded-2xl border border-white/10 bg-[#222] p-5 text-white shadow-xl"
|
||||
data-canvas-overlay="true"
|
||||
aria-label="语音与音乐"
|
||||
aria-label="阿里云音频生成"
|
||||
>
|
||||
<h3 className="font-semibold">语音与音乐</h3>
|
||||
<h3 className="font-semibold">语音与音乐 · 阿里云官方</h3>
|
||||
<fieldset disabled={busy || sending} className="mt-3 space-y-3 disabled:opacity-60">
|
||||
{connectedText && <p className="mb-3 whitespace-pre-wrap rounded bg-white/5 p-2 text-xs" aria-label="已连接文本">已连接文本:{connectedText}</p>}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
@ -112,9 +112,6 @@ export function AudioGenerationComposer({
|
||||
>
|
||||
<option value="tts">文字配音</option>
|
||||
<option value="music">音乐 / 歌曲</option>
|
||||
<option value="asr">语音转文字</option>
|
||||
<option value="voiceclone">声音克隆配音</option>
|
||||
<option value="voicedesign">声音设计配音</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
@ -137,40 +134,20 @@ export function AudioGenerationComposer({
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{["asr", "voiceclone"].includes(draft.mode) && (
|
||||
<label className="block">
|
||||
{draft.mode === "asr" ? "待识别音频" : "参考声音"}(MP3 / WAV,最多 20 MiB)
|
||||
<input type="file" accept="audio/mpeg,audio/wav,.mp3,.wav" aria-label="上传参考音频" className={input}
|
||||
onChange={async event => {
|
||||
const file = event.target.files?.[0]; event.target.value = ""; if (!file) return;
|
||||
if (file.size > 20 * 1024 * 1024) { setError("参考音频需小于 20 MiB"); return; }
|
||||
setSending(true); setError("");
|
||||
try {
|
||||
const form = new FormData(); form.append("file", file);
|
||||
const response = await fetch("/api/canvas/media/upload", { method: "POST", body: form, signal: AbortSignal.timeout(120000) });
|
||||
const result = await response.json(); const url = result.url || result.data?.url;
|
||||
if (!response.ok || !url) throw Error(result.error || "参考音频上传失败");
|
||||
patch({ referenceAudioUrl: String(url), referenceAudioName: file.name });
|
||||
} catch (error) { setError(error instanceof Error ? error.message : "上传失败"); }
|
||||
finally { setSending(false); }
|
||||
}} />
|
||||
{draft.referenceAudioUrl && <span className="mt-1 block text-sm text-white/80">已上传:{draft.referenceAudioName || "参考音频"}</span>}
|
||||
</label>
|
||||
)}
|
||||
{draft.mode !== "asr" && <label className="block">
|
||||
{draft.mode !== "music" ? "配音文本(最多 600 字)" : `音乐描述(最多 ${contract?.descriptionLimit || 2000} 字)`}
|
||||
<label className="block">
|
||||
{draft.mode === "tts" ? "配音文本(最多 600 字)" : "音乐描述"}
|
||||
<textarea
|
||||
aria-label="音频内容"
|
||||
className={input}
|
||||
rows={4}
|
||||
maxLength={draft.mode !== "music" ? 600 : contract?.descriptionLimit || 2000}
|
||||
maxLength={draft.mode === "tts" ? 600 : 2000}
|
||||
value={draft.text}
|
||||
onChange={(e) => patch({ text: e.target.value })}
|
||||
/>
|
||||
</label>}
|
||||
{!["music", "asr"].includes(draft.mode) ? (
|
||||
</label>
|
||||
{draft.mode === "tts" ? (
|
||||
<>
|
||||
{!!contract?.voices.length && <div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<label>
|
||||
音色
|
||||
<select
|
||||
@ -186,7 +163,7 @@ export function AudioGenerationComposer({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{contract?.supportsLanguageControl !== false && <label>
|
||||
<label>
|
||||
语言
|
||||
<select
|
||||
aria-label="配音语言"
|
||||
@ -198,8 +175,8 @@ export function AudioGenerationComposer({
|
||||
<option value="English">英文</option>
|
||||
<option value="Auto">自动 / 中英混合</option>
|
||||
</select>
|
||||
</label>}
|
||||
</div>}
|
||||
</label>
|
||||
</div>
|
||||
{contract?.instructions ? (
|
||||
<label className="block">
|
||||
声音风格指令
|
||||
@ -233,7 +210,7 @@ export function AudioGenerationComposer({
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : draft.mode === "music" ? (
|
||||
) : (
|
||||
<>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
@ -256,7 +233,7 @@ export function AudioGenerationComposer({
|
||||
onChange={(e) => patch({ lyrics: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
{contract?.supportsGender !== false && (!contract?.genderRequiresLyrics || draft.lyrics?.trim()) && <label>
|
||||
<label>
|
||||
演唱声音
|
||||
<select
|
||||
className={input}
|
||||
@ -267,18 +244,18 @@ export function AudioGenerationComposer({
|
||||
<option value="female">女声</option>
|
||||
<option value="male">男声</option>
|
||||
</select>
|
||||
</label>}
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
{!options.length ? (
|
||||
<p className="text-sm text-amber-200">
|
||||
当前没有可用的音乐模型,请在模型设置中启用。
|
||||
Fun-Music 需要阿里云邀测权限,开通并启用模型后即可生成。
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
)}
|
||||
<div className="flex items-end gap-3">
|
||||
{draft.mode !== "asr" && <label>
|
||||
<label>
|
||||
格式
|
||||
<select
|
||||
aria-label="音频格式"
|
||||
@ -292,14 +269,14 @@ export function AudioGenerationComposer({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>}
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!model || loading}
|
||||
className="rounded-lg bg-white px-4 py-2 text-black disabled:opacity-40"
|
||||
onClick={() => void run()}
|
||||
>
|
||||
{busy || sending ? "处理中…" : draft.mode === "asr" ? "识别文字" : "生成音频"}
|
||||
{busy || sending ? "处理中…" : "生成音频"}
|
||||
</button>
|
||||
<label className="cursor-pointer rounded-lg border border-white/20 px-3 py-2">
|
||||
上传音频
|
||||
|
||||
@ -2,13 +2,9 @@
|
||||
|
||||
import { advancePastAtomicRanges, scanMarkdownImageStreaming } from "@/lib/canvas/markdown-image-streaming";
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import { useStickToBottom } from "use-stick-to-bottom";
|
||||
import { DefaultChatTransport } from "ai";
|
||||
import { shouldUseCanvasAgentRuntime } from "@/lib/ai/canvas-agent-runtime/routing";
|
||||
import { CanvasAgentProgressMessage } from "@/components/canvas/chat-panel/canvas-agent-progress";
|
||||
import { useCanvasRemoteOperation, useCanvasRemoteSnapshot } from "@/components/canvas/CanvasRemoteOperationContext";
|
||||
import { readCanvasComposerDraft, writeCanvasComposerDraft, clearCanvasComposerDraft } from "@/lib/client/canvas-draft";
|
||||
import { BEFORE_PAGE_REFRESH, type PageRefreshRequest } from "@/lib/client/page-refresh";
|
||||
import { canvasHistoryForChat } from "@/lib/client/canvas-history-response";
|
||||
import { useCanvasAgentRun } from "@/components/canvas/chat-panel/use-canvas-agent-run";
|
||||
import { canvasAgentProgress, type CanvasAgentProgress } from "@/lib/ai/canvas-agent-runtime/progress";
|
||||
@ -70,15 +66,13 @@ import {
|
||||
import { toast } from "sonner";
|
||||
import { useCanvasStore } from "@/store/canvas";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getGatewayErrorPageMessage } from "@/lib/request-error";
|
||||
import { findImageGenerationFailure } from "@/lib/canvas/image-generation-status";
|
||||
import { fetcher, fetchWithErrorHandlers, generateUUID } from "@/lib/utils";
|
||||
import {
|
||||
fetchUploadWithRetry,
|
||||
type UploadProgress,
|
||||
} from "@/lib/client/upload-with-retry";
|
||||
import {
|
||||
downloadOriginalImage,
|
||||
downloadCanvasImageAsPng,
|
||||
getCanvasImageDownloadErrorMessage,
|
||||
type CanvasImageDownloadProgress,
|
||||
} from "@/lib/client/canvas-image-download";
|
||||
@ -86,8 +80,7 @@ import { canvasService } from "@/services/canvas";
|
||||
import {
|
||||
inferOriginalImageUrl,
|
||||
} from "@/lib/image-url";
|
||||
import { buildImageFallbackUrl, buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { ProgressiveImagePreview, type LoadedImagePreview } from "@/components/progressive-image-preview";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import {
|
||||
isImageGenerationModelDescriptor,
|
||||
isVideoModelDescriptor,
|
||||
@ -380,9 +373,7 @@ function MarkdownResponseFallback({
|
||||
}: Pick<ResponseProps, "children" | "className">) {
|
||||
return (
|
||||
<div className={cn("whitespace-pre-wrap break-words [overflow-wrap:anywhere]", className)}>
|
||||
{typeof children === "string"
|
||||
? getGatewayErrorPageMessage(children) || children
|
||||
: children}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1462,7 +1453,7 @@ function normalizeComposerPreviewTail(text: string, fixedPrefix: string) {
|
||||
}
|
||||
|
||||
// 获取图片尺寸(保留原图分辨率 + 画布显示尺寸)
|
||||
function getImageDimensions(source: string | File): Promise<{
|
||||
function getImageDimensions(url: string): Promise<{
|
||||
width: number;
|
||||
height: number;
|
||||
originalWidth: number;
|
||||
@ -1470,7 +1461,6 @@ function getImageDimensions(source: string | File): Promise<{
|
||||
}> {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
const objectUrl = typeof source === "string" ? null : URL.createObjectURL(source);
|
||||
let settled = false;
|
||||
const resolveOnce = (dimensions: {
|
||||
width: number;
|
||||
@ -1483,11 +1473,9 @@ function getImageDimensions(source: string | File): Promise<{
|
||||
window.clearTimeout(timeout);
|
||||
img.onload = null;
|
||||
img.onerror = null;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
resolve(dimensions);
|
||||
};
|
||||
const timeout = window.setTimeout(() => {
|
||||
img.removeAttribute("src");
|
||||
resolveOnce(DEFAULT_CANVAS_IMAGE_DIMENSIONS);
|
||||
}, CANVAS_IMAGE_DIMENSION_TIMEOUT_MS);
|
||||
|
||||
@ -1520,7 +1508,7 @@ function getImageDimensions(source: string | File): Promise<{
|
||||
// 加载失败时使用默认尺寸
|
||||
resolveOnce(DEFAULT_CANVAS_IMAGE_DIMENSIONS);
|
||||
};
|
||||
img.src = objectUrl ?? String(source);
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
@ -3250,8 +3238,6 @@ export function CanvasChatPanel({
|
||||
onRequireLogin,
|
||||
onBeforeAgentRequest,
|
||||
}: CanvasChatPanelProps) {
|
||||
const runCanvasRemoteOperation = useCanvasRemoteOperation();
|
||||
const applyCanvasRemoteSnapshot = useCanvasRemoteSnapshot();
|
||||
const isWorkspacePresentation = presentation === "workspace";
|
||||
const isVideoWorkspace = workspaceVariant === "video";
|
||||
const propCanvasToolbarConfig = useMemo(
|
||||
@ -3350,7 +3336,6 @@ export function CanvasChatPanel({
|
||||
const activeChatIdRef = useRef<string>(requestedChatSessionId || chatId);
|
||||
const activeMessagesRef = useRef<ChatMessage[]>([]);
|
||||
const inFlightChatIdRef = useRef<string | null>(null);
|
||||
const imageGenerationUserMessageIdsRef = useRef<Record<string, string>>({});
|
||||
const inFlightRawChatIdRef = useRef<string | null>(null);
|
||||
const [chatSessions, setChatSessions] = useState<CanvasChatSession[]>([]);
|
||||
const [isSessionMenuOpen, setIsSessionMenuOpen] = useState(false);
|
||||
@ -3372,15 +3357,15 @@ export function CanvasChatPanel({
|
||||
const latestCanvasSkillTagsRef = useRef<CanvasSkillTag[]>([]);
|
||||
const pendingCanvasSkillTagOrderSaveRef = useRef<string[] | null>(null);
|
||||
const suppressSkillTagClickRef = useRef(false);
|
||||
const { scrollRef: messagesScrollRef, contentRef: messagesContentRef, scrollToBottom: scrollMessagesToBottom, isAtBottom: isMessageListAtBottom } = useStickToBottom({ initial: false, resize: "instant" });
|
||||
const initialScrollChatRef = useRef<string | null>(null);
|
||||
const [messageViewportKey, setMessageViewportKey] = useState(0);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const clawdFolderInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const videoSlotInputRefs = useRef<Array<HTMLInputElement | null>>([]);
|
||||
const agentSlotInputRefs = useRef<Array<HTMLInputElement | null>>([]);
|
||||
const detailSlotInputRefs = useRef<Array<HTMLInputElement | null>>([]);
|
||||
const [clawdTableFiles, setClawdTableFiles] = useState<File[]>([]);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const detailModeSwitchRef = useRef(false);
|
||||
const hiddenPromptRef = useRef<string | null>(null);
|
||||
const autoContextRef = useRef<string | null>(null);
|
||||
@ -3409,6 +3394,7 @@ export function CanvasChatPanel({
|
||||
const hasInitializedVideoWorkspaceRef = useRef(false);
|
||||
const sessionMenuRef = useRef<HTMLDivElement>(null);
|
||||
const clawdHistoryMenuRef = useRef<HTMLDivElement>(null);
|
||||
const historyScrollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const forceHistoryHydrationRef = useRef<string | null>(null);
|
||||
const copiedUserMessageRef = useRef<CopiedUserMessagePayload | null>(null);
|
||||
const composerUserEditedAtRef = useRef(0);
|
||||
@ -3445,7 +3431,6 @@ export function CanvasChatPanel({
|
||||
const [fullscreenPreview, setFullscreenPreview] = useState<{
|
||||
url: string;
|
||||
alt?: string;
|
||||
preview: LoadedImagePreview;
|
||||
} | null>(null);
|
||||
const [downloadProgress, setDownloadProgress] =
|
||||
useState<CanvasImageDownloadProgress | null>(null);
|
||||
@ -3483,6 +3468,16 @@ export function CanvasChatPanel({
|
||||
const [downloadingOriginalUrl, setDownloadingOriginalUrl] = useState("");
|
||||
const [addingClawdImageUrl, setAddingClawdImageUrl] = useState("");
|
||||
const downloadAbortControllerRef = useRef<AbortController | null>(null);
|
||||
const fullscreenPreviewSrc = useMemo(() => {
|
||||
if (!fullscreenPreview?.url) return "";
|
||||
const originalUrl = inferOriginalImageUrl(fullscreenPreview.url);
|
||||
return buildImageProxyUrl(originalUrl || fullscreenPreview.url, {
|
||||
delivery: "proxy",
|
||||
width: 2400,
|
||||
quality: 90,
|
||||
format: "webp",
|
||||
});
|
||||
}, [fullscreenPreview]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (composerUploadClearTimeoutRef.current) {
|
||||
@ -3652,20 +3647,17 @@ export function CanvasChatPanel({
|
||||
|
||||
const setStreamImageGenerationStateForChat = useCallback(
|
||||
(chatSessionId: string, next: ImageGenerationStatusStreamPayload | null) => {
|
||||
const userMessageId = imageGenerationUserMessageIdsRef.current[chatSessionId];
|
||||
if (next?.userMessageId && userMessageId && next.userMessageId !== userMessageId) return;
|
||||
setStreamImageGenerationStateByChatId((prev) => ({
|
||||
...prev,
|
||||
[chatSessionId]: next ? { ...next, userMessageId: next.userMessageId || userMessageId } : null,
|
||||
[chatSessionId]: next,
|
||||
}));
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const clearStreamImageGenerationStateForChat = useCallback((chatSessionId: string, preserveFailure = false) => {
|
||||
const clearStreamImageGenerationStateForChat = useCallback((chatSessionId: string) => {
|
||||
setStreamImageGenerationStateByChatId((prev) => {
|
||||
if (!(chatSessionId in prev)) return prev;
|
||||
if (preserveFailure && prev[chatSessionId]?.phase === "failed") return prev;
|
||||
const next = { ...prev };
|
||||
delete next[chatSessionId];
|
||||
return next;
|
||||
@ -4467,15 +4459,17 @@ export function CanvasChatPanel({
|
||||
setDownloadProgress({
|
||||
phase: "preparing",
|
||||
message: "正在准备原图...",
|
||||
percent: 5,
|
||||
});
|
||||
|
||||
try {
|
||||
await downloadOriginalImage({
|
||||
await downloadCanvasImageAsPng({
|
||||
url: originalUrl,
|
||||
candidates: [raw, buildImageProxyUrl(originalUrl, { delivery: "proxy" })],
|
||||
signal: controller.signal,
|
||||
onProgress: setDownloadProgress,
|
||||
});
|
||||
toast.success("已开始下载");
|
||||
toast.success("原图已开始下载");
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
toast.message("已取消下载");
|
||||
@ -5036,15 +5030,6 @@ export function CanvasChatPanel({
|
||||
console.log('[CanvasChat] 已插入图片标签:', url.substring(0, 50));
|
||||
}, []);
|
||||
|
||||
const setComposerEditorRef = useCallback((editor: HTMLDivElement | null) => {
|
||||
textareaRef.current = editor as unknown as HTMLTextAreaElement;
|
||||
if (!editor) return;
|
||||
const draft = readCanvasComposerDraft<PickedObjectAttachment>(activeChatId);
|
||||
const text = activeChatIdRef.current === activeChatId ? inputRef.current || draft?.text : draft?.text;
|
||||
if (text) editor.textContent = text;
|
||||
draft?.attachments.forEach((attachment, index) => insertImageTagInEditor(attachment.url, attachment.name || "参考图片", index));
|
||||
}, [activeChatId, insertImageTagInEditor]);
|
||||
|
||||
const handleCopyUserMessage = useCallback(async (message: ChatMessage) => {
|
||||
const payload = getUserMessageCopyPayload(message);
|
||||
if (!payload.text && payload.attachments.length === 0) {
|
||||
@ -6109,7 +6094,7 @@ export function CanvasChatPanel({
|
||||
const activeComposerMode = unifiedImageAgent && (rawComposerMode === "image" || rawComposerMode === "video")
|
||||
? "agent" : rawComposerMode;
|
||||
const isImageAgentComposer = unifiedImageAgent && activeComposerMode === "agent";
|
||||
const [imageAgentEnabled, setImageAgentEnabled] = useState(true);
|
||||
const [imageAgentEnabled, setImageAgentEnabled] = useState(false);
|
||||
const imageAgentEnabledRef = useRef(imageAgentEnabled);
|
||||
imageAgentEnabledRef.current = imageAgentEnabled;
|
||||
const isVideoToolbarDark = isVideoWorkspace || activeComposerMode === "video";
|
||||
@ -7807,6 +7792,7 @@ export function CanvasChatPanel({
|
||||
existingMessageImageKeys.add(messageImageKey);
|
||||
}
|
||||
|
||||
const dimensions = await getImageDimensions(url);
|
||||
if (useCanvasStore.getState().projectId !== canvasId || activeChatIdRef.current !== activeChatId) return;
|
||||
const compareSourceUrlRaw =
|
||||
sourceImageUrls[Math.min(index, Math.max(0, sourceImageUrls.length - 1))] ||
|
||||
@ -7839,7 +7825,7 @@ export function CanvasChatPanel({
|
||||
const placeholderNode = reservedPlaceholderNode
|
||||
? currentNodes.find((node) => node.id === reservedPlaceholderNode.id) || null
|
||||
: null;
|
||||
const size = placeholderNode?.size || anchorNode?.size || { width: 300, height: 300 };
|
||||
const size = { width: dimensions.width, height: dimensions.height };
|
||||
const position = placeholderNode
|
||||
? getCenteredReplacementPosition(placeholderNode, size)
|
||||
: getAnchoredGenerationPosition({
|
||||
@ -7857,6 +7843,8 @@ export function CanvasChatPanel({
|
||||
prompt: generationPrompt,
|
||||
originalSrc: canUseCompareSource ? compareSourceUrl : undefined,
|
||||
metadata: {
|
||||
originalWidth: dimensions.originalWidth,
|
||||
originalHeight: dimensions.originalHeight,
|
||||
generationPrompt,
|
||||
sourceMessageId: messageId || undefined,
|
||||
sourceImageKey,
|
||||
@ -7989,12 +7977,8 @@ export function CanvasChatPanel({
|
||||
|
||||
const store = useCanvasStore.getState();
|
||||
store.markAgentOperationRefresh();
|
||||
if (applyCanvasRemoteSnapshot) {
|
||||
if (!applyCanvasRemoteSnapshot({ projectId: targetProjectId, canvasData: result.data.canvasData, updatedAt: String(result.data.updatedAt || "") })) return false;
|
||||
} else {
|
||||
store.loadCanvas(result.data.canvasData);
|
||||
store.setCanvasRevision(String(result.data.updatedAt || ""), String(result.data.updatedAt || ""));
|
||||
}
|
||||
store.loadCanvas(result.data.canvasData);
|
||||
store.setCanvasRevision(String(result.data.updatedAt || ""), String(result.data.updatedAt || ""));
|
||||
if (createdNodeIds.length > 0) {
|
||||
const refreshedStore = useCanvasStore.getState();
|
||||
refreshedStore.selectNodes(createdNodeIds);
|
||||
@ -8022,7 +8006,7 @@ export function CanvasChatPanel({
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[applyCanvasRemoteSnapshot, applyCanvasViewOperation, canvasId, focusCanvasOnNode, mutate]
|
||||
[applyCanvasViewOperation, canvasId, focusCanvasOnNode, mutate]
|
||||
);
|
||||
|
||||
const {
|
||||
@ -8039,8 +8023,6 @@ export function CanvasChatPanel({
|
||||
api: "/api/chat",
|
||||
fetch: fetchWithErrorHandlers,
|
||||
async prepareSendMessagesRequest(request) {
|
||||
const userMessageId = request.messages.findLast((item) => item.role === "user")?.id;
|
||||
if (userMessageId) imageGenerationUserMessageIdsRef.current[request.id] = userMessageId;
|
||||
// 从 canvas-{uuid} 格式中提取纯 UUID,后端 schema 要求纯 UUID
|
||||
const rawId = request.id.startsWith('canvas-')
|
||||
? request.id.replace('canvas-', '')
|
||||
@ -8153,27 +8135,20 @@ export function CanvasChatPanel({
|
||||
const payload: ImageGenerationStatusStreamPayload =
|
||||
typeof dataPart.data === "string" ? JSON.parse(dataPart.data) : dataPart.data;
|
||||
if (!payload || typeof payload !== "object") return;
|
||||
const userMessageId = imageGenerationUserMessageIdsRef.current[eventChatId];
|
||||
if (payload.userMessageId && userMessageId && payload.userMessageId !== userMessageId) return;
|
||||
if (payload.phase === "completed") {
|
||||
setStreamImageGenerationStateForChat(eventChatId, {
|
||||
phase: "finalizing",
|
||||
userMessageId: payload.userMessageId,
|
||||
providerType: payload.providerType,
|
||||
modelName: getAgentSafeModelName(payload.modelName),
|
||||
imageCount: Number(payload.imageCount || 0) || undefined,
|
||||
});
|
||||
window.setTimeout(() => {
|
||||
if (payload.userMessageId && imageGenerationUserMessageIdsRef.current[eventChatId] !== payload.userMessageId) return;
|
||||
clearStreamImageGenerationStateForChat(eventChatId);
|
||||
}, 30_000);
|
||||
return;
|
||||
}
|
||||
setStreamImageGenerationStateForChat(eventChatId, {
|
||||
phase: payload.phase || "processing",
|
||||
userMessageId: payload.userMessageId,
|
||||
requestId: payload.requestId,
|
||||
failure: payload.failure,
|
||||
providerType: payload.providerType,
|
||||
modelName: getAgentSafeModelName(payload.modelName),
|
||||
imageCount: Number(payload.imageCount || 0) || undefined,
|
||||
@ -8441,11 +8416,6 @@ export function CanvasChatPanel({
|
||||
)
|
||||
: false;
|
||||
const normalizedParts = Array.isArray(messageData.parts) ? messageData.parts : [];
|
||||
const failureStatus = findImageGenerationFailure(
|
||||
[{ role: messageData.role, parts: normalizedParts }],
|
||||
imageGenerationUserMessageIdsRef.current[eventChatId],
|
||||
);
|
||||
if (failureStatus) setStreamImageGenerationStateForChat(eventChatId, failureStatus);
|
||||
const normalizedAttachments = Array.isArray(messageData.attachments)
|
||||
? messageData.attachments
|
||||
: [];
|
||||
@ -8514,7 +8484,7 @@ export function CanvasChatPanel({
|
||||
(hasImageGenEndMarker || incomingImageUrls.length > 0 || incomingVideoUrls.length > 0) &&
|
||||
!shouldDeferClearForActiveMedia
|
||||
) {
|
||||
clearStreamImageGenerationStateForChat(eventChatId, true);
|
||||
clearStreamImageGenerationStateForChat(eventChatId);
|
||||
}
|
||||
|
||||
if (!isEventForActiveChat) {
|
||||
@ -8840,6 +8810,12 @@ export function CanvasChatPanel({
|
||||
hasHydratedHistoryRef.current = true;
|
||||
|
||||
setMessages(sortCanvasMessagesByCreatedAt(dbMessages));
|
||||
|
||||
if (dbMessages.length > 0) {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "auto", block: "end" });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const reloadMessagesOnce = async () => {
|
||||
@ -8952,7 +8928,7 @@ export function CanvasChatPanel({
|
||||
onRunChange: (run) => {
|
||||
// The live stream owns its message; polling only recovers disconnected replies.
|
||||
if (status === "submitted" || status === "streaming") return;
|
||||
if (!run?.assistantMessageId || !run.assistantText || run.chatId !== toRawCanvasChatId(activeChatIdRef.current)) return;
|
||||
if (!run?.assistantMessageId || !run.assistantText || run.chatId !== activeChatIdRef.current) return;
|
||||
// Recover the same assistant reply after a stream disconnect or refresh.
|
||||
setMessages(current => {
|
||||
const index = current.findIndex(message => message.id === run.assistantMessageId);
|
||||
@ -8967,33 +8943,6 @@ export function CanvasChatPanel({
|
||||
});
|
||||
const activeCanvasAgentRun = canvasAgentTask.run;
|
||||
const isCanvasAgentRunning = activeCanvasAgentRun?.status === "running";
|
||||
useEffect(() => {
|
||||
const beforeRefresh = (event: Event) => {
|
||||
const request = (event as CustomEvent<PageRefreshRequest>).detail;
|
||||
if (composerUploadProgress) {
|
||||
request.block("素材仍在上传,请等待上传完成后再刷新。当前页面和输入已保留。");
|
||||
return;
|
||||
}
|
||||
if (isCanvasAgentRunning || isClawdSubmitting || isDetailGenerating || status === "streaming" || status === "submitted" || Object.values(sendGuardRef.current).some(guard => guard.inFlight)) {
|
||||
request.block("当前对话任务仍在处理中,请等待结果返回后再刷新。原任务会继续执行,无需重新提交。");
|
||||
return;
|
||||
}
|
||||
request.save(async () => {
|
||||
if ((input.trim() || attachments.length) && !writeCanvasComposerDraft(activeChatId, { text: input, attachments }))
|
||||
throw new Error("浏览器无法保存当前输入,请保留此页并检查浏览器存储空间后重试。");
|
||||
});
|
||||
};
|
||||
const beforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = "true";
|
||||
};
|
||||
window.addEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
if (composerUploadProgress) window.addEventListener("beforeunload", beforeUnload);
|
||||
return () => {
|
||||
window.removeEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
};
|
||||
}, [activeChatId, input, attachments, composerUploadProgress, isCanvasAgentRunning, isClawdSubmitting, isDetailGenerating, status]);
|
||||
|
||||
const restorePendingClawdRequestToComposer = useCallback(
|
||||
(snapshot: PendingClawdRequestRestoreSnapshot) => {
|
||||
@ -9137,7 +9086,6 @@ export function CanvasChatPanel({
|
||||
},
|
||||
} as ChatMessage;
|
||||
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
sendMessage(launchUserMessage as any);
|
||||
setMessages((previousMessages) =>
|
||||
sortCanvasMessagesByCreatedAt([
|
||||
@ -9157,7 +9105,7 @@ export function CanvasChatPanel({
|
||||
if (editableDiv) {
|
||||
editableDiv.innerHTML = "";
|
||||
}
|
||||
}, [activeChatId, rawChatId, selectedModelId, status, sendMessage, setMessages, clearSelection, launchAutoSendTick, activeComposerMode, scrollMessagesToBottom]);
|
||||
}, [activeChatId, rawChatId, selectedModelId, status, sendMessage, setMessages, clearSelection, launchAutoSendTick, activeComposerMode]);
|
||||
|
||||
// 当历史消息加载完成后,更新消息列表(支持同一会话的增量刷新)
|
||||
const loadedHistorySignatureRef = useRef<string>("");
|
||||
@ -9177,6 +9125,7 @@ export function CanvasChatPanel({
|
||||
hiddenPromptRef.current = null;
|
||||
autoContextRef.current = null;
|
||||
pendingLaunchRef.current = null;
|
||||
setMessageViewportKey((prev) => prev + 1);
|
||||
setMessages([]);
|
||||
setInput("");
|
||||
setAttachments([]);
|
||||
@ -9191,20 +9140,11 @@ export function CanvasChatPanel({
|
||||
}, [activeChatId, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
const draft = readCanvasComposerDraft<PickedObjectAttachment>(activeChatId);
|
||||
if (!draft || (input && input !== draft.text)) return;
|
||||
if (!input) setInput(draft.text);
|
||||
setAttachments(draft.attachments);
|
||||
const frame = requestAnimationFrame(() => {
|
||||
const editor = textareaRef.current as HTMLDivElement | null;
|
||||
if (!editor || getComposerPlainTextFromElement(editor).trim()) return;
|
||||
editor.textContent = draft.text;
|
||||
draft.attachments.forEach((attachment, index) => insertImageTagInEditor(attachment.url, attachment.name || "参考图片", index));
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [activeChatId, activeComposerMode, input, insertImageTagInEditor]);
|
||||
if (historyScrollTimerRef.current) {
|
||||
clearTimeout(historyScrollTimerRef.current);
|
||||
historyScrollTimerRef.current = null;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!historyData || !rawChatId) return;
|
||||
const historyMessages = historyData.messages || [];
|
||||
const isClawdHistory = isClawdMode || historyMessages.some(isClawdChatMessage);
|
||||
@ -9245,14 +9185,29 @@ export function CanvasChatPanel({
|
||||
missingPendingMessage ? [...historyMessages, pendingMessage] : historyMessages
|
||||
);
|
||||
});
|
||||
setMessageViewportKey((prev) => prev + 1);
|
||||
console.log("[CanvasChat] 已同步历史消息:", historyMessages.length, signature);
|
||||
|
||||
|
||||
if (historyMessages.length > 0) {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "auto", block: "end" });
|
||||
});
|
||||
historyScrollTimerRef.current = setTimeout(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "auto", block: "end" });
|
||||
historyScrollTimerRef.current = null;
|
||||
}, 160);
|
||||
return () => {
|
||||
if (historyScrollTimerRef.current) {
|
||||
clearTimeout(historyScrollTimerRef.current);
|
||||
historyScrollTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [activeChatId, activeClawdRequestUi?.userMessageId, historyData, isClawdMode, isClawdSubmitting, rawChatId, setMessages, status]);
|
||||
|
||||
useEffect(() => {
|
||||
const streamState = streamImageGenerationStateByChatId[activeChatId];
|
||||
if (!rawChatId || !streamState || (streamState.phase === "failed" && streamState.failure?.outcome !== "unknown")) return;
|
||||
if (!rawChatId || !streamState) return;
|
||||
|
||||
let cancelled = false;
|
||||
const poll = async () => {
|
||||
@ -9276,13 +9231,6 @@ export function CanvasChatPanel({
|
||||
const streamState = streamImageGenerationStateByChatId[activeChatId];
|
||||
if (!streamState || messages.length === 0) return;
|
||||
|
||||
const failure = findImageGenerationFailure(messages, streamState.userMessageId || "");
|
||||
if (failure && streamState.phase !== "failed") {
|
||||
setStreamImageGenerationStateForChat(activeChatId, failure);
|
||||
return;
|
||||
}
|
||||
if (streamState.phase === "failed" && streamState.failure?.outcome !== "unknown") return;
|
||||
|
||||
const lastUserIndex = [...messages]
|
||||
.map((message) => message.role)
|
||||
.lastIndexOf("user");
|
||||
@ -9299,7 +9247,8 @@ export function CanvasChatPanel({
|
||||
.join("\n");
|
||||
return (
|
||||
extractAssistantImageUrls(textContent).length > 0 ||
|
||||
extractVideoUrls(textContent).length > 0
|
||||
extractVideoUrls(textContent).length > 0 ||
|
||||
/失败|超时|重试|error|failed/i.test(textContent)
|
||||
);
|
||||
});
|
||||
|
||||
@ -9320,7 +9269,6 @@ export function CanvasChatPanel({
|
||||
messages,
|
||||
streamImageGenerationStateByChatId,
|
||||
clearStreamImageGenerationStateForChat,
|
||||
setStreamImageGenerationStateForChat,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@ -9581,6 +9529,7 @@ export function CanvasChatPanel({
|
||||
continue;
|
||||
}
|
||||
|
||||
const dimensions = await getImageDimensions(url);
|
||||
if (cancelled) return;
|
||||
const compareSourceUrlRaw =
|
||||
nearestUserImageUrls[Math.min(index, Math.max(0, nearestUserImageUrls.length - 1))] ||
|
||||
@ -9613,7 +9562,20 @@ export function CanvasChatPanel({
|
||||
const placeholderNode = reservedPlaceholderNode
|
||||
? currentNodes.find((node) => node.id === reservedPlaceholderNode.id) || null
|
||||
: null;
|
||||
const size = placeholderNode?.size || anchorNode?.size || { width: 300, height: 300 };
|
||||
const size = placeholderNode
|
||||
? { width: dimensions.width, height: dimensions.height }
|
||||
: anchorNode
|
||||
? {
|
||||
width: Math.max(
|
||||
1,
|
||||
Math.round(Number(anchorNode.size?.width || dimensions.width))
|
||||
),
|
||||
height: Math.max(
|
||||
1,
|
||||
Math.round(Number(anchorNode.size?.height || dimensions.height))
|
||||
),
|
||||
}
|
||||
: { width: dimensions.width, height: dimensions.height };
|
||||
const position = placeholderNode
|
||||
? getCenteredReplacementPosition(placeholderNode, size)
|
||||
: getAnchoredGenerationPosition({
|
||||
@ -9632,6 +9594,8 @@ export function CanvasChatPanel({
|
||||
prompt: generationPrompt || "对话生成",
|
||||
originalSrc: canUseCompareSource ? compareSourceUrl : undefined,
|
||||
metadata: {
|
||||
originalWidth: dimensions.originalWidth,
|
||||
originalHeight: dimensions.originalHeight,
|
||||
generationPrompt: generationPrompt || undefined,
|
||||
sourceMessageId: message.id,
|
||||
sourceImageKey: imageEntry.sourceImageKey,
|
||||
@ -9811,13 +9775,11 @@ export function CanvasChatPanel({
|
||||
});
|
||||
}, [activeChatSessionMode, messages, nodes, updateNode]);
|
||||
|
||||
// Open each conversation at its latest message; later updates respect manual scrolling.
|
||||
// 滚动到底部
|
||||
useEffect(() => {
|
||||
if (messages.length === 0 && !isClawdSubmitting) return;
|
||||
if (initialScrollChatRef.current === activeChatId) return;
|
||||
initialScrollChatRef.current = activeChatId;
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
}, [activeChatId, isClawdSubmitting, messages.length, scrollMessagesToBottom]);
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [isClawdSubmitting, messages]);
|
||||
|
||||
// 标记是否已经为当前画布设置过标题(避免重复调用)
|
||||
const hasSetCanvasTitle = useRef(false);
|
||||
@ -10358,7 +10320,7 @@ export function CanvasChatPanel({
|
||||
buildCanvasUploadedImageAttachment({ file, imageUrl, assetId })
|
||||
);
|
||||
|
||||
const dimensions = await getImageDimensions(file);
|
||||
const dimensions = await getImageDimensions(imageUrl);
|
||||
const nodeIndex = nodes.length + slotIndex;
|
||||
const spacing = 20;
|
||||
const x = 100 + (nodeIndex % 3) * (dimensions.width + spacing);
|
||||
@ -10436,7 +10398,7 @@ export function CanvasChatPanel({
|
||||
buildCanvasUploadedImageAttachment({ file, imageUrl, assetId })
|
||||
);
|
||||
|
||||
const dimensions = await getImageDimensions(file);
|
||||
const dimensions = await getImageDimensions(imageUrl);
|
||||
const nodeIndex = nodes.length + slotIndex;
|
||||
const spacing = 20;
|
||||
const x = 100 + (nodeIndex % 3) * (dimensions.width + spacing);
|
||||
@ -12586,7 +12548,6 @@ export function CanvasChatPanel({
|
||||
const supplement = typeof overrideInput === "string" ? overrideInput.trim() : input.trim();
|
||||
if (isCanvasAgentRunning && !isClawdMode && imageAgentEnabled) {
|
||||
if (supplement && await canvasAgentTask.control("steer", supplement)) {
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
setInput("");
|
||||
const editor = textareaRef.current as HTMLDivElement | null;
|
||||
if (editor) editor.innerHTML = "";
|
||||
@ -12884,7 +12845,6 @@ export function CanvasChatPanel({
|
||||
requestChatId,
|
||||
clawdRequestRestoreSnapshot
|
||||
);
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
startClawdRequestUi(requestChatId, userMessageId, nextProcessingHint);
|
||||
setMessages((previousMessages) =>
|
||||
sortCanvasMessagesByCreatedAt([
|
||||
@ -13373,26 +13333,6 @@ export function CanvasChatPanel({
|
||||
});
|
||||
inFlightChatIdRef.current = activeChatId;
|
||||
inFlightRawChatIdRef.current = rawChatId;
|
||||
imageGenerationUserMessageIdsRef.current[activeChatId] = userMessageId;
|
||||
if (shouldUseCanvasAgentRuntime({
|
||||
composerMode: effectiveComposerMode,
|
||||
agentPresetId: effectiveAgentEntryMode === "preset" ? selectedAgentPreset?.id : undefined,
|
||||
workspaceVariant: isVideoWorkspace ? "video" : "canvas",
|
||||
contextPayload: contextPayloadRef.current || undefined,
|
||||
}) && onBeforeAgentRequest) {
|
||||
try {
|
||||
if (!(await onBeforeAgentRequest())) throw new Error("画布自动同步失败,本次任务未提交。输入内容已保留,请检查网络后再次发送。");
|
||||
} catch (error) {
|
||||
releaseSendGuard(activeChatId);
|
||||
inFlightChatIdRef.current = null;
|
||||
inFlightRawChatIdRef.current = null;
|
||||
contextPayloadRef.current = null;
|
||||
writeCanvasComposerDraft(activeChatId, { text: composerInput, attachments: effectiveAttachments });
|
||||
toast.error(error instanceof Error ? error.message : "画布自动同步失败,本次任务未提交,输入内容已保留。");
|
||||
return;
|
||||
}
|
||||
}
|
||||
clearCanvasComposerDraft(activeChatId);
|
||||
clearStreamImageGenerationStateForChat(activeChatId);
|
||||
clearAgentProgressStateForChat(activeChatId);
|
||||
if (shouldShowOptimisticImageGeneration) {
|
||||
@ -13417,7 +13357,6 @@ export function CanvasChatPanel({
|
||||
|
||||
// 使用与 multimodal-input 相同的格式发送消息
|
||||
try {
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
sendMessage(optimisticUserMessage as any);
|
||||
setMessages((previousMessages) =>
|
||||
sortCanvasMessagesByCreatedAt([
|
||||
@ -13456,9 +13395,6 @@ export function CanvasChatPanel({
|
||||
}
|
||||
}, [
|
||||
isCanvasAgentRunning,
|
||||
scrollMessagesToBottom,
|
||||
onBeforeAgentRequest,
|
||||
isVideoWorkspace,
|
||||
canvasAgentTask.control,
|
||||
activeChatId,
|
||||
activeComposerMode,
|
||||
@ -13596,19 +13532,23 @@ export function CanvasChatPanel({
|
||||
|
||||
console.log('[CanvasChat] 更新画布:', rawId);
|
||||
|
||||
if (!runCanvasRemoteOperation) return;
|
||||
await runCanvasRemoteOperation(async () => {
|
||||
if (useCanvasStore.getState().projectId !== rawId) return;
|
||||
const result = await canvasService.updateProject(rawId, { title, thumbnail: firstImageUrl });
|
||||
if (!result.success) throw new Error(result.error || "画布名称同步失败");
|
||||
const updateResponse = await fetch(`/api/canvas/${rawId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title,
|
||||
thumbnail: firstImageUrl,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log('[CanvasChat] 画布更新响应:', updateResponse.status);
|
||||
} else {
|
||||
console.error('[CanvasChat] auto-title API 请求失败:', response.status);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[CanvasChat] 自动命名失败:', error);
|
||||
}
|
||||
}, [chatId, runCanvasRemoteOperation]);
|
||||
}, [chatId]);
|
||||
|
||||
const addUploadedImageAttachmentToComposer = useCallback(
|
||||
(uploaded: ComposerUploadedImage) => {
|
||||
@ -13722,7 +13662,7 @@ export function CanvasChatPanel({
|
||||
};
|
||||
onUploaded?.(uploadedBase);
|
||||
clearComposerUploadProgress(250);
|
||||
const dimensions = await getImageDimensions(file);
|
||||
const dimensions = await getImageDimensions(imageUrl);
|
||||
const spacing = 20;
|
||||
const x = 100 + (nodeIndex % 3) * (dimensions.width + spacing);
|
||||
const y = 100 + Math.floor(nodeIndex / 3) * (dimensions.height + spacing);
|
||||
@ -14911,7 +14851,7 @@ export function CanvasChatPanel({
|
||||
firstImageUrl = imageUrl;
|
||||
}
|
||||
|
||||
const dimensions = await getImageDimensions(file);
|
||||
const dimensions = await getImageDimensions(imageUrl);
|
||||
updateUploadedImageAttachmentDimensions(imageUrl, dimensions);
|
||||
|
||||
// 获取图片原始尺寸后添加到画布
|
||||
@ -15162,7 +15102,7 @@ export function CanvasChatPanel({
|
||||
!hasGenerationEnd &&
|
||||
Boolean(currentModel || activeComposerMode === "agent"));
|
||||
const hasActiveTypewriter = Object.keys(activeTypingSections).length > 0;
|
||||
const shouldRenderImageLoading = shouldShowImageLoading && streamImageGenerationState?.phase !== "failed" && !hasActiveTypewriter;
|
||||
const shouldRenderImageLoading = shouldShowImageLoading && !hasActiveTypewriter;
|
||||
const loadingImageCount = streamImageGenerationState?.imageCount || imageParams.imageCount || 1;
|
||||
const loadingProviderType =
|
||||
streamImageGenerationState?.providerType ||
|
||||
@ -15225,9 +15165,9 @@ export function CanvasChatPanel({
|
||||
phase === "queued"
|
||||
? "等待开始生成"
|
||||
: phase === "finalizing"
|
||||
? "正在保存生成结果"
|
||||
? "正在润饰细节"
|
||||
: phase === "failed"
|
||||
? streamState.failure?.message || "生成失败"
|
||||
? "生成失败"
|
||||
: "正在创建图片";
|
||||
const status = phase === "failed" ? "failed" : "generating";
|
||||
const currentNodes = useCanvasStore.getState().nodes;
|
||||
@ -15283,10 +15223,14 @@ export function CanvasChatPanel({
|
||||
canvasGenerationPlaceholder: true,
|
||||
chatId: activeChatId,
|
||||
detailProgressLabel: label,
|
||||
generationProgress: undefined,
|
||||
generationFailure: streamState.failure,
|
||||
generationRequestId: streamState.requestId,
|
||||
generationUserMessageId: streamState.userMessageId,
|
||||
generationProgress:
|
||||
phase === "queued"
|
||||
? 12
|
||||
: phase === "finalizing"
|
||||
? 96
|
||||
: phase === "failed"
|
||||
? 100
|
||||
: undefined,
|
||||
modelName: streamState.modelName || currentModel?.displayName || undefined,
|
||||
providerType: streamState.providerType || currentModel?.providerType || undefined,
|
||||
placementMode: "anchored-generation",
|
||||
@ -15380,7 +15324,6 @@ export function CanvasChatPanel({
|
||||
|
||||
if (
|
||||
message.role === "assistant" &&
|
||||
!rawParts.some((part: any) => part.type === "data-imageGenerationStatus" && part.data?.failure) &&
|
||||
isInternalCanvasImageGenerationFailureText(cleanedParts)
|
||||
) {
|
||||
return acc;
|
||||
@ -15690,7 +15633,7 @@ export function CanvasChatPanel({
|
||||
processedMessageIds.current.clear();
|
||||
hasHydratedHistoryRef.current = true;
|
||||
setMessages(sortCanvasMessagesByCreatedAt(fresh.messages));
|
||||
void scrollMessagesToBottom({ animation: "instant" });
|
||||
setMessageViewportKey((previous) => previous + 1);
|
||||
}).catch((error) => {
|
||||
console.error("[CanvasChat] Failed to reopen current conversation:", error);
|
||||
toast.error("聊天记录暂时读取失败,请重试");
|
||||
@ -15704,7 +15647,7 @@ export function CanvasChatPanel({
|
||||
replaceChatSessionQuery(sessionId);
|
||||
setIsSessionMenuOpen(false);
|
||||
toast.success("已切换聊天窗口");
|
||||
}, [activeChatId, isClawdSubmitting, mutateHistoryData, releaseSendGuard, replaceChatSessionQuery, scrollMessagesToBottom, setMessages, status]);
|
||||
}, [activeChatId, isClawdSubmitting, mutateHistoryData, releaseSendGuard, replaceChatSessionQuery, setMessages, status]);
|
||||
|
||||
const switchToClawdHistorySession = useCallback(
|
||||
(historyItem: ClawdHistoryItem) => {
|
||||
@ -15866,8 +15809,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(activeClawdSkillTag.iconUrl)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(activeClawdSkillTag.iconUrl);
|
||||
if (event.currentTarget.src !== activeClawdSkillTag.iconUrl) {
|
||||
event.currentTarget.src = activeClawdSkillTag.iconUrl || "";
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -16121,17 +16064,11 @@ export function CanvasChatPanel({
|
||||
{isDetailEmptyState ? (
|
||||
<div className="flex-1 min-h-0" />
|
||||
) : (
|
||||
<div key={activeChatId} className="relative flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
ref={messagesScrollRef}
|
||||
data-testid="canvas-chat-messages"
|
||||
role="region"
|
||||
aria-label="对话消息"
|
||||
// biome-ignore lint/a11y/noNoninteractiveTabindex: The scroll region needs PageUp/PageDown keyboard input.
|
||||
tabIndex={0}
|
||||
key={`${activeChatId}-${messageViewportKey}`}
|
||||
className={cn(
|
||||
"flex-1 min-h-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
|
||||
isPlainCanvasEmptyState ? "overflow-hidden" : "overflow-auto",
|
||||
"flex-1 min-h-0 overflow-x-hidden",
|
||||
isPlainCanvasEmptyState ? "overflow-hidden" : "overflow-y-auto",
|
||||
isWorkspacePresentation ? "p-5" : "p-3",
|
||||
isPlainCanvasEmptyState
|
||||
? "pt-0"
|
||||
@ -16140,7 +16077,7 @@ export function CanvasChatPanel({
|
||||
: "pt-3"
|
||||
)}
|
||||
>
|
||||
<div ref={messagesContentRef} className={cn(
|
||||
<div className={cn(
|
||||
"space-y-5 overflow-x-hidden pr-1",
|
||||
isPlainCanvasEmptyState ? "h-full pb-0" : "pb-24"
|
||||
)}>
|
||||
@ -16191,8 +16128,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(attachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(attachment.url);
|
||||
if (event.currentTarget.src !== attachment.url) {
|
||||
event.currentTarget.src = attachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -16268,8 +16205,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(attachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(attachment.url);
|
||||
if (event.currentTarget.src !== attachment.url) {
|
||||
event.currentTarget.src = attachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -16454,8 +16391,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(tag.iconUrl)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(tag.iconUrl);
|
||||
if (event.currentTarget.src !== tag.iconUrl) {
|
||||
event.currentTarget.src = tag.iconUrl || "";
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -16755,8 +16692,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(attachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(attachment.url);
|
||||
if (event.currentTarget.src !== attachment.url) {
|
||||
event.currentTarget.src = attachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -17092,23 +17029,15 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(url);
|
||||
if (event.currentTarget.src !== url) {
|
||||
event.currentTarget.src = url;
|
||||
}
|
||||
}}
|
||||
onClick={(event) => setFullscreenPreview({ url, preview: {
|
||||
src: event.currentTarget.currentSrc || event.currentTarget.src,
|
||||
width: event.currentTarget.naturalWidth,
|
||||
height: event.currentTarget.naturalHeight,
|
||||
} })}
|
||||
onClick={() => setFullscreenPreview({ url })}
|
||||
onDoubleClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setFullscreenPreview({ url, preview: {
|
||||
src: e.currentTarget.currentSrc || e.currentTarget.src,
|
||||
width: e.currentTarget.naturalWidth,
|
||||
height: e.currentTarget.naturalHeight,
|
||||
} });
|
||||
setFullscreenPreview({ url });
|
||||
}}
|
||||
/>
|
||||
<div className="absolute bottom-2 right-2 flex items-center gap-1.5">
|
||||
@ -17343,22 +17272,9 @@ export function CanvasChatPanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
{!isMessageListAtBottom && renderableVisibleMessages.length > 0 ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
aria-label="回到最新消息"
|
||||
title="回到最新消息"
|
||||
className="absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-full shadow-sm"
|
||||
onClick={() => void scrollMessagesToBottom({ animation: "instant" })}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fullscreenPreview && createPortal(
|
||||
@ -17367,7 +17283,7 @@ export function CanvasChatPanel({
|
||||
onClick={() => setFullscreenPreview(null)}
|
||||
>
|
||||
<button
|
||||
className="absolute top-4 right-4 z-10 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
|
||||
className="absolute top-4 right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
|
||||
onClick={() => setFullscreenPreview(null)}
|
||||
aria-label="关闭预览"
|
||||
>
|
||||
@ -17376,7 +17292,7 @@ export function CanvasChatPanel({
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="absolute top-4 right-16 z-10 inline-flex items-center gap-1 rounded-full bg-white/10 px-3 py-2 text-sm text-white transition-colors hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-65"
|
||||
className="absolute top-4 right-16 inline-flex items-center gap-1 rounded-full bg-white/10 px-3 py-2 text-sm text-white transition-colors hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-65"
|
||||
disabled={isDownloadingOriginalImage}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
@ -17393,11 +17309,13 @@ export function CanvasChatPanel({
|
||||
{isDownloadingOriginalImage ? "下载中" : "下载原图"}
|
||||
</button>
|
||||
|
||||
<ProgressiveImagePreview
|
||||
src={inferOriginalImageUrl(fullscreenPreview.url) || fullscreenPreview.url}
|
||||
preview={fullscreenPreview.preview}
|
||||
<img
|
||||
src={fullscreenPreviewSrc}
|
||||
alt={fullscreenPreview.alt || "图片预览"}
|
||||
className="max-w-[95vw] max-h-[95vh] object-contain"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
|
||||
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-white/60 text-sm">
|
||||
@ -17964,8 +17882,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(slotAttachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(slotAttachment.url);
|
||||
if (event.currentTarget.src !== slotAttachment.url) {
|
||||
event.currentTarget.src = slotAttachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -18289,8 +18207,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(activeClawdSkillTag.iconUrl)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(activeClawdSkillTag.iconUrl);
|
||||
if (event.currentTarget.src !== activeClawdSkillTag.iconUrl) {
|
||||
event.currentTarget.src = activeClawdSkillTag.iconUrl || "";
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -18549,8 +18467,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(item.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(item.url);
|
||||
if (event.currentTarget.src !== item.url) {
|
||||
event.currentTarget.src = item.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -18605,7 +18523,7 @@ export function CanvasChatPanel({
|
||||
)}
|
||||
>
|
||||
<div
|
||||
ref={setComposerEditorRef}
|
||||
ref={textareaRef as any}
|
||||
contentEditable={!isSubmitting || (isCanvasAgentRunning && !canvasAgentTask.stopPending)}
|
||||
role="textbox"
|
||||
tabIndex={isSubmitting ? -1 : 0}
|
||||
@ -18639,7 +18557,6 @@ export function CanvasChatPanel({
|
||||
setTagPreview(null);
|
||||
}}
|
||||
onInput={(e) => {
|
||||
clearCanvasComposerDraft(activeChatId);
|
||||
// 从 contenteditable 中提取纯文本(排除附件标签文本)
|
||||
const target = e.target as HTMLDivElement;
|
||||
const clone = target.cloneNode(true) as HTMLDivElement;
|
||||
@ -18735,8 +18652,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(slotAttachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(slotAttachment.url);
|
||||
if (event.currentTarget.src !== slotAttachment.url) {
|
||||
event.currentTarget.src = slotAttachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -18803,8 +18720,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(slotAttachment.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(slotAttachment.url);
|
||||
if (event.currentTarget.src !== slotAttachment.url) {
|
||||
event.currentTarget.src = slotAttachment.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -19503,8 +19420,8 @@ export function CanvasChatPanel({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(tagPreview.url)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(tagPreview.url);
|
||||
if (event.currentTarget.src !== tagPreview.url) {
|
||||
event.currentTarget.src = tagPreview.url;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@ -19,7 +19,6 @@ const PROJECT_LIST_PAGE_SIZE = 24;
|
||||
interface CanvasFileListPanelProps {
|
||||
currentId: string;
|
||||
onClose: () => void;
|
||||
onNavigate?: (url: string) => void;
|
||||
workspaceType?: CanvasWorkspaceType;
|
||||
workspaceLabel?: string;
|
||||
createUrl?: string;
|
||||
@ -29,7 +28,6 @@ interface CanvasFileListPanelProps {
|
||||
export function CanvasFileListPanel({
|
||||
currentId,
|
||||
onClose,
|
||||
onNavigate,
|
||||
workspaceType = "canvas",
|
||||
workspaceLabel = "画布",
|
||||
createUrl = "/canvas?new=1",
|
||||
@ -90,10 +88,6 @@ export function CanvasFileListPanel({
|
||||
|
||||
// 创建新画布
|
||||
const handleCreateNew = async () => {
|
||||
if (onNavigate) {
|
||||
onNavigate(createUrl);
|
||||
return;
|
||||
}
|
||||
router.push(createUrl);
|
||||
};
|
||||
|
||||
@ -106,10 +100,6 @@ export function CanvasFileListPanel({
|
||||
}
|
||||
const targetUrl = buildProjectUrl(id);
|
||||
onClose(); // 关闭文件列表面板
|
||||
if (onNavigate) {
|
||||
onNavigate(targetUrl);
|
||||
return;
|
||||
}
|
||||
// 强制整页跳转,避免仅更新 URL 不刷新
|
||||
setTimeout(() => {
|
||||
window.location.assign(targetUrl);
|
||||
|
||||
@ -28,7 +28,6 @@ export function CanvasImageDownloadProgressDialog({
|
||||
: null;
|
||||
const loadedLabel = formatBytes(progress.loadedBytes);
|
||||
const totalLabel = formatBytes(progress.totalBytes);
|
||||
const converting = progress.phase === "converting";
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
@ -42,12 +41,12 @@ export function CanvasImageDownloadProgressDialog({
|
||||
{progress.phase === "saving" ? (
|
||||
<Download className="h-4 w-4" />
|
||||
) : (
|
||||
<Loader2 className="h-4 w-4 motion-safe:animate-spin" />
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
)}
|
||||
</span>
|
||||
<div>
|
||||
<div className="text-[14px] font-semibold">下载原图</div>
|
||||
<div className="mt-0.5 text-[12px] text-white/58" role="status">{progress.message}</div>
|
||||
<div className="mt-0.5 text-[12px] text-white/58">{progress.message}</div>
|
||||
</div>
|
||||
</div>
|
||||
{onCancel ? (
|
||||
@ -64,19 +63,14 @@ export function CanvasImageDownloadProgressDialog({
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="mb-2 flex items-center justify-between text-[12px] text-white/55">
|
||||
<span>{loadedLabel && totalLabel ? `${loadedLabel} / ${totalLabel}` : converting ? "格式转换中" : "正在处理文件"}</span>
|
||||
<span>{loadedLabel && totalLabel ? `${loadedLabel} / ${totalLabel}` : "正在处理文件"}</span>
|
||||
<span>{percent !== null ? `${percent}%` : "..."}</span>
|
||||
</div>
|
||||
<div
|
||||
className="relative h-2 overflow-hidden rounded-full bg-white/10"
|
||||
role="progressbar"
|
||||
aria-label={converting ? "图片格式转换" : "图片下载"}
|
||||
aria-valuenow={percent ?? undefined}
|
||||
>
|
||||
<div className="relative h-2 overflow-hidden rounded-full bg-white/10">
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-y-0 left-0 rounded-full bg-gradient-to-r from-cyan-300 via-sky-400 to-emerald-300",
|
||||
percent === null && "w-1/3 motion-safe:animate-[download-indeterminate_1.15s_ease-in-out_infinite]"
|
||||
percent === null && "w-1/3 animate-[download-indeterminate_1.15s_ease-in-out_infinite]"
|
||||
)}
|
||||
style={percent !== null ? { width: `${percent}%` } : undefined}
|
||||
/>
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext } from "react";
|
||||
import type { CanvasState } from "@/types/canvas";
|
||||
|
||||
export type CanvasRemoteOperationResult = {
|
||||
projectId: string;
|
||||
canvasData: CanvasState;
|
||||
updatedAt: string;
|
||||
};
|
||||
export type CanvasRemoteOperation = (() => Promise<void>) | (() => Promise<CanvasRemoteOperationResult | undefined>);
|
||||
|
||||
export const CanvasRemoteOperationContext = createContext<
|
||||
{
|
||||
run: (operation: CanvasRemoteOperation) => Promise<void>;
|
||||
applySnapshot: (result: CanvasRemoteOperationResult) => boolean;
|
||||
} | null
|
||||
>(null);
|
||||
|
||||
export function useCanvasRemoteOperation() {
|
||||
return useContext(CanvasRemoteOperationContext)?.run || null;
|
||||
}
|
||||
|
||||
export function useCanvasRemoteSnapshot() {
|
||||
return useContext(CanvasRemoteOperationContext)?.applySnapshot || null;
|
||||
}
|
||||
@ -2,10 +2,14 @@
|
||||
|
||||
import { ReferenceIcon } from "@/components/lovart/reference-icon";
|
||||
|
||||
import { Loader2, Save } from "lucide-react";
|
||||
|
||||
type CanvasSurfaceHeaderProps = {
|
||||
isSaving: boolean;
|
||||
onAddImage: () => void;
|
||||
onHome: () => void;
|
||||
onOpenFiles: () => void;
|
||||
onSave: () => void;
|
||||
projectTitle: string;
|
||||
rightInset: number;
|
||||
};
|
||||
@ -14,9 +18,11 @@ const iconButtonClass =
|
||||
"inline-flex h-[28px] w-[28px] items-center justify-center rounded-[8px] p-0 text-[#858585] transition-colors hover:bg-black/5 focus-visible:outline-2 focus-visible:outline-offset-2 dark:hover:bg-white/10";
|
||||
|
||||
export function CanvasSurfaceHeader({
|
||||
isSaving,
|
||||
onAddImage,
|
||||
onHome,
|
||||
onOpenFiles,
|
||||
onSave,
|
||||
projectTitle,
|
||||
rightInset,
|
||||
}: CanvasSurfaceHeaderProps) {
|
||||
@ -71,6 +77,19 @@ export function CanvasSurfaceHeader({
|
||||
<ReferenceIcon name="plus" size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-[8px] border border-[#e5e5e5] px-3 text-[12px] text-[#333333] transition-colors hover:bg-black/5 disabled:opacity-50 dark:border-white/10 dark:text-white"
|
||||
disabled={isSaving}
|
||||
onClick={onSave}
|
||||
type="button"
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-3.5 w-3.5" />
|
||||
)}
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
"use client";
|
||||
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||
import { useCanvasGroupRuns } from "@/hooks/use-canvas-group-runs";
|
||||
import { hasRecoverableCanvasTask } from "@/lib/video-canvas/task-recovery";
|
||||
import { restoreTextResourceContent } from "@/lib/video-canvas/text-resource";
|
||||
import { GroupStoryboardPreview } from "./GroupStoryboardPreview";
|
||||
import { CanvasGroupToolbar } from "./CanvasGroupToolbar";
|
||||
import { isCanvasGroup, groupMembers, makeCanvasGroup, ungroupCanvasNodes, moveCanvasSelection, layoutCanvasGroup, migrateLegacyGroups, exportCanvasGroup, instantiateCanvasGroup, groupBounds, assignGroupMembers } from "@/lib/video-canvas/groups";
|
||||
@ -4146,7 +4144,7 @@ function normalizeTextResourceNode(node: CloneNode, fallbackIndex: number): Clon
|
||||
draftValues: {
|
||||
...(node.draftValues || {}),
|
||||
action: "TEXT_RESOURCE",
|
||||
content: restoreTextResourceContent(node.draftValues),
|
||||
content: Array.isArray(node.draftValues?.content) ? node.draftValues?.content : [],
|
||||
nodeType: "text",
|
||||
scriptRole: "resource",
|
||||
viewMode: undefined,
|
||||
@ -15106,7 +15104,7 @@ function DirectorNodeComposer({
|
||||
if(file.size>20*1024*1024){setError("参考图需小于 20 MiB");return;}
|
||||
setBusy(true);setError("");try{
|
||||
const form=new FormData();form.append("file",file);form.append("purpose","director-studio");
|
||||
const response=await fetchUploadWithRetry(form,{signal:AbortSignal.timeout(120000)});
|
||||
const response=await fetch("/api/files/upload",{method:"POST",body:form,signal:AbortSignal.timeout(120000)});
|
||||
const result=await response.json();const url=result.url||result.data?.url;
|
||||
if(!response.ok||!url)throw new Error(result.error||"图片上传失败");
|
||||
onDraft({directorReferenceUrl:String(url)});
|
||||
@ -15627,8 +15625,7 @@ function VideoTargetModuleComposer({
|
||||
const ratio = supported.ratios.length && !supported.ratios.includes(normalizeVideoRatioValue(current.ratio)) ? supported.ratios[0] : current.ratio;
|
||||
const executableResolutions = supported.resolutions.filter(value => ["480p", "720p", "1080p"].includes(value.toLowerCase()));
|
||||
const resolution = executableResolutions.length && !executableResolutions.includes(normalizeVideoResolutionValue(current.resolution)) ? executableResolutions[0].toUpperCase() : current.resolution;
|
||||
const durations = getCanvasVideoParameters(target, activeMode, resolution || "720P").durations;
|
||||
const duration = durations.length && !durations.includes(normalizeVideoDurationValue(current.duration)) ? `${durations[0]}s` : current.duration;
|
||||
const duration = supported.durations.length && !supported.durations.includes(normalizeVideoDurationValue(current.duration)) ? `${supported.durations[0]}s` : current.duration;
|
||||
const audio = supported.supportsAudio ? current.audio : "关闭";
|
||||
return ratio === current.ratio && resolution === current.resolution && duration === current.duration && audio === current.audio ? current : {...current, ratio, resolution, duration, audio};
|
||||
});
|
||||
@ -17931,7 +17928,7 @@ function VideoParameterEditor({
|
||||
const candidates = filterCanvasModels(modelOptions, audioRequired ? "audio-video" : "video", mode);
|
||||
const model = candidates.find(item => item.id === settings.model || item.modelId === settings.model) ||
|
||||
(!normalizeModelRef(settings.model) || settings.model === "auto" ? candidates[0] : undefined);
|
||||
const options = getCanvasVideoParameters(model, mode, settings.resolution || "720P");
|
||||
const options = getCanvasVideoParameters(model, mode);
|
||||
const executableResolutions = options.resolutions.filter(value => ["480p", "720p", "1080p"].includes(value.toLowerCase())).map(value => value.toUpperCase());
|
||||
const durationIndex = Math.max(0, options.durations.indexOf(normalizeVideoDurationValue(settings.duration)));
|
||||
return (
|
||||
@ -20841,18 +20838,8 @@ function PresetMediaCanvasNode({
|
||||
</div>
|
||||
) : mediaType === "audio" ? (
|
||||
<div className="relative h-[calc(100%-32px)]">
|
||||
{isGenerating || isGenerationFailed ? (
|
||||
<GenerationPendingPreview
|
||||
errorMessage={getDraftString(node, "generationError")}
|
||||
onCancel={onCancelGeneration}
|
||||
progress={getDraftNumber(node, "generationProgress", 0)}
|
||||
status={generationStatus}
|
||||
statusLabel={getDraftString(node, "pendingLabel") || "生成中"}
|
||||
/>
|
||||
) : (
|
||||
<OfficialAudioCard durationSeconds={getDraftNumber(node, "durationSeconds", 0)} mediaUrl={mediaUrl} selected={selected} />
|
||||
)}
|
||||
{!generated && !isGenerating && !isGenerationFailed ? (
|
||||
<OfficialAudioCard durationSeconds={getDraftNumber(node, "durationSeconds", 3)} mediaUrl={mediaUrl} selected={selected} />
|
||||
{!generated ? (
|
||||
<button
|
||||
aria-label={mediaUrl ? "替换音频" : "上传音频"}
|
||||
className="absolute right-3 top-3 flex h-9 w-9 items-center justify-center rounded-[8px] bg-black/56 text-white/90"
|
||||
@ -21398,14 +21385,12 @@ function GenerationPendingPreview({
|
||||
previewUrl,
|
||||
progress,
|
||||
status,
|
||||
statusLabel,
|
||||
}: {
|
||||
errorMessage?: string;
|
||||
onCancel: () => void;
|
||||
previewUrl?: string;
|
||||
progress: number;
|
||||
status: string;
|
||||
statusLabel?: string;
|
||||
}) {
|
||||
const displayProgress = Math.max(2, Math.min(99, Math.round(progress)));
|
||||
const failed = status === "failed";
|
||||
@ -21451,7 +21436,7 @@ function GenerationPendingPreview({
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{statusLabel || `生成中 ${displayProgress}%...`}</span>
|
||||
<span>生成中 {displayProgress}%...</span>
|
||||
<button
|
||||
className="font-medium text-white/42 transition hover:text-white/80"
|
||||
onClick={(event) => {
|
||||
@ -21479,7 +21464,11 @@ function PureTextResourceCanvasNode({
|
||||
onTextResourceChange: (content: string) => void;
|
||||
selected: boolean;
|
||||
}) {
|
||||
const textContent = restoreTextResourceContent(node.draftValues)[0] || "";
|
||||
const contentValues = node.draftValues?.content;
|
||||
const textContent =
|
||||
Array.isArray(contentValues) && typeof contentValues[0] === "string"
|
||||
? contentValues[0]
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="h-full w-full">
|
||||
|
||||
@ -152,7 +152,16 @@ export function shouldRetryCanvasViewOperationAfterRefresh(
|
||||
);
|
||||
}
|
||||
|
||||
export type { ImageGenerationStatusStreamPayload } from "@/lib/canvas/image-generation-status";
|
||||
export type ImageGenerationStatusStreamPayload = {
|
||||
phase?: "queued" | "processing" | "finalizing" | "failed" | "completed";
|
||||
providerType?: string;
|
||||
modelName?: string;
|
||||
imageCount?: number;
|
||||
queuePosition?: number;
|
||||
sameModelRunningCount?: number;
|
||||
concurrencyLimit?: number;
|
||||
estimatedWaitMs?: number;
|
||||
};
|
||||
|
||||
export type AgentTargetLockRefPreview = {
|
||||
url: string;
|
||||
|
||||
@ -448,7 +448,7 @@ function extractChatMediaUrls(text: string, kind: ChatMediaKind): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
const markdownLinkPattern = /(?<!!)\[([^\]]*)]\((https?:\/\/[^)\s]+)\)/gi;
|
||||
const markdownLinkPattern = /\[([^\]]*)]\((https?:\/\/[^)\s]+)\)/gi;
|
||||
while ((match = markdownLinkPattern.exec(text)) !== null) {
|
||||
const label = String(match[1] || "");
|
||||
const hintedKind = /音频|语音|声音|audio|mp3/i.test(label)
|
||||
@ -491,7 +491,7 @@ export function stripMediaMarkup(text: string): string {
|
||||
.replace(/<audio[\s\S]*?<\/audio>/gi, "")
|
||||
.replace(/<audio\b[^>]*\/?\s*>/gi, "")
|
||||
.replace(/<a[\s\S]*?<\/a>/gi, "")
|
||||
.replace(/(?<!!)\[([^\]]*)]\((https?:\/\/[^)\s]+)\)/gi, (match, label, url) => {
|
||||
.replace(/\[([^\]]*)]\((https?:\/\/[^)\s]+)\)/gi, (match, label, url) => {
|
||||
const hintedMedia = /音频|语音|声音|audio|mp3|视频|影片|播放|video/i.test(
|
||||
String(label || "")
|
||||
);
|
||||
|
||||
@ -6,8 +6,6 @@ import { ArrowUp, MessageSquare, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { CanvasAgentRunPanel } from "./canvas-agent-run-panel";
|
||||
import { BEFORE_PAGE_REFRESH, type PageRefreshRequest } from "@/lib/client/page-refresh";
|
||||
import { readCanvasComposerDraft, writeCanvasComposerDraft, clearCanvasComposerDraft } from "@/lib/client/canvas-draft";
|
||||
import {
|
||||
videoAgentSettingsSchema,
|
||||
type VideoAgentSettings,
|
||||
@ -96,22 +94,6 @@ export function VideoCanvasAgentPanel(props: {
|
||||
};
|
||||
}, [props.projectId, setMessages]);
|
||||
const busy = backgroundRunning || preparing || status === "submitted" || status === "streaming";
|
||||
useEffect(() => {
|
||||
const draft = readCanvasComposerDraft(`video-agent-${props.projectId}`);
|
||||
if (draft) setInput(draft.text);
|
||||
}, [props.projectId]);
|
||||
useEffect(() => {
|
||||
const beforeRefresh = (event: Event) => {
|
||||
const request = (event as CustomEvent<PageRefreshRequest>).detail;
|
||||
if (busy) request.block("当前视频任务仍在处理中,请等待结果返回后再刷新。原任务无需重新提交。");
|
||||
request.save(async () => {
|
||||
if (input.trim() && !writeCanvasComposerDraft(`video-agent-${props.projectId}`, { text: input, attachments: [] }))
|
||||
throw new Error("浏览器无法保存当前输入,请保留此页并检查浏览器存储空间后重试。");
|
||||
});
|
||||
};
|
||||
window.addEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
return () => window.removeEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
}, [busy, input, props.projectId]);
|
||||
const submit = useCallback(
|
||||
async (resumeRunId?: string) => {
|
||||
if (busy || loading) return;
|
||||
@ -123,7 +105,6 @@ export function VideoCanvasAgentPanel(props: {
|
||||
try {
|
||||
await latest.current.props.beforeSend();
|
||||
if (!mounted.current) return;
|
||||
clearCanvasComposerDraft(`video-agent-${props.projectId}`);
|
||||
resumeRef.current = resumeRunId;
|
||||
setInput("");
|
||||
await sendMessage({ text });
|
||||
@ -317,7 +298,7 @@ export function VideoCanvasAgentPanel(props: {
|
||||
<textarea
|
||||
aria-label="视频创作要求"
|
||||
value={input}
|
||||
onChange={(event) => { clearCanvasComposerDraft(`video-agent-${props.projectId}`); setInput(event.target.value); }}
|
||||
onChange={(event) => setInput(event.target.value)}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder="例如:先分析选中素材,写分镜,再生成一条5秒商品展示视频"
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { readDirectorScene, type DirectorScene } from "@/lib/video-canvas/director-scene";
|
||||
@ -65,7 +64,9 @@ export function DirectorReconstructionPanel({
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
form.append("purpose", "director-studio");
|
||||
const response = await fetchUploadWithRetry(form, {
|
||||
const response = await fetch("/api/files/upload", {
|
||||
method: "POST",
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(120000),
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||
import {
|
||||
commitDirectorScene,
|
||||
resolveDirectorCamera,
|
||||
@ -44,13 +43,14 @@ async function upload(file: File) {
|
||||
"purpose",
|
||||
file.type.startsWith("video/") ? "canvas-video-process" : "director-studio",
|
||||
);
|
||||
const response = /\.glb$/i.test(file.name)
|
||||
? await fetch("/api/canvas/director/upload-model", {
|
||||
const response = await fetch(
|
||||
/\.glb$/i.test(file.name) ? "/api/canvas/director/upload-model" : "/api/files/upload",
|
||||
{
|
||||
method: "POST",
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(120000),
|
||||
})
|
||||
: await fetchUploadWithRetry(form, { signal: AbortSignal.timeout(120000) });
|
||||
},
|
||||
);
|
||||
const result = await response.json();
|
||||
const url = result.url || result.data?.url;
|
||||
if (!response.ok || !url) throw new Error(result.error || "上传失败");
|
||||
|
||||
@ -1,7 +1,4 @@
|
||||
"use client";
|
||||
import { CanvasPreviewImage } from "./image-node/canvas-preview-image";
|
||||
import { canvasImagePreviewWidth } from "@/lib/canvas/image-preview-width";
|
||||
import { isRetiredStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
|
||||
import {
|
||||
Box,
|
||||
@ -62,7 +59,6 @@ import { DetailUiDomRenderer } from "@/components/canvas/DetailUiDomRenderer";
|
||||
import { ReferenceImageToolbar } from "@/components/canvas/ReferenceImageToolbar";
|
||||
import { CanvasToolbarIcon } from "@/components/canvas/CanvasToolbarIcon";
|
||||
import { CanvasImageDownloadProgressDialog } from "@/components/canvas/CanvasImageDownloadProgressDialog";
|
||||
import { ProgressiveImagePreview, type LoadedImagePreview } from "@/components/progressive-image-preview";
|
||||
import {
|
||||
areImageAdjustmentsEqual,
|
||||
buildImageAdjustmentFilterStyle,
|
||||
@ -178,7 +174,7 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||
import {
|
||||
downloadOriginalImage,
|
||||
downloadCanvasImageAsPng,
|
||||
getCanvasImageDownloadErrorMessage,
|
||||
type CanvasImageDownloadProgress,
|
||||
} from "@/lib/client/canvas-image-download";
|
||||
@ -189,7 +185,7 @@ import {
|
||||
normalizeDetailUiSubjectAnalysis,
|
||||
} from "@/lib/detail-ui-subject-analysis";
|
||||
import type { DetailUiScreenOverlaySnapshot } from "@/lib/detail-ui-surface-adapter";
|
||||
import { buildImageFallbackUrl, buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import {
|
||||
DEFAULT_PUBLIC_THREED_MODEL_ALIAS_CONFIG,
|
||||
getDefaultThreeDModelAliasId,
|
||||
@ -235,8 +231,6 @@ import {
|
||||
import { normalizeOptionalHexColor } from "@/lib/canvas/text-edit-colors";
|
||||
import { isCanvasImageUploadPending } from "@/lib/canvas/local-upload-state";
|
||||
import { createCanvasCapabilityClientCommand } from "@/lib/canvas/capabilities/client-command";
|
||||
import { executeCanvasToolbarCapability } from "@/lib/client/canvas-toolbar-capability";
|
||||
import { useCanvasRemoteOperation } from "@/components/canvas/CanvasRemoteOperationContext";
|
||||
import { getCanvasCapabilityByClientAction } from "@/lib/canvas/capabilities/registry";
|
||||
import type { CanvasCapabilityClientAction } from "@/lib/canvas/capabilities/types";
|
||||
import { cn, fetcher } from "@/lib/utils";
|
||||
@ -1714,7 +1708,6 @@ export function ImageNode({
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [annotatorOpen, setAnnotatorOpen] = useState(false);
|
||||
const [fullscreenPreviewOpen, setFullscreenPreviewOpen] = useState(false);
|
||||
const [fullscreenPreviewImage, setFullscreenPreviewImage] = useState<LoadedImagePreview | null>(null);
|
||||
const [downloadProgress, setDownloadProgress] =
|
||||
useState<CanvasImageDownloadProgress | null>(null);
|
||||
const downloadAbortControllerRef = useRef<AbortController | null>(null);
|
||||
@ -2084,7 +2077,7 @@ export function ImageNode({
|
||||
const selectNode = useCanvasStore((state) => state.selectNode);
|
||||
const projectId = useCanvasStore((state) => state.projectId);
|
||||
const getCanvasState = useCanvasStore((state) => state.getCanvasState);
|
||||
const runCanvasRemoteOperation = useCanvasRemoteOperation();
|
||||
const loadCanvas = useCanvasStore((state) => state.loadCanvas);
|
||||
const addPendingChatAttachment = useCanvasStore(
|
||||
(state) => state.addPendingChatAttachment
|
||||
);
|
||||
@ -2482,11 +2475,14 @@ export function ImageNode({
|
||||
[compareButtonVisualSize]
|
||||
);
|
||||
const shouldUseHighFidelityDisplayImage =
|
||||
isSelected ||
|
||||
isHovered ||
|
||||
isCompareMode ||
|
||||
boxCutoutMode ||
|
||||
localEditMode ||
|
||||
cropPanelOpen ||
|
||||
imageAdjustPanelOpen ||
|
||||
fullscreenPreviewOpen ||
|
||||
isThisNodePicking;
|
||||
const displayImageWidth = useMemo(() => {
|
||||
const devicePixelRatio =
|
||||
@ -2501,13 +2497,13 @@ export function ImageNode({
|
||||
const densityMultiplier = shouldUseHighFidelityDisplayImage ? 1.35 : 1.05;
|
||||
const minWidth = shouldUseHighFidelityDisplayImage ? 960 : 640;
|
||||
const maxWidth = shouldUseHighFidelityDisplayImage ? 4096 : 2600;
|
||||
return canvasImagePreviewWidth(Math.max(
|
||||
return Math.max(
|
||||
minWidth,
|
||||
Math.min(
|
||||
maxWidth,
|
||||
Math.round((node.size.width || 320) * zoomMultiplier * devicePixelRatio * densityMultiplier)
|
||||
)
|
||||
), maxWidth);
|
||||
);
|
||||
}, [node.size.width, shouldUseHighFidelityDisplayImage, viewportZoom]);
|
||||
const displayImageQuality = shouldUseHighFidelityDisplayImage ? 92 : 88;
|
||||
const displayImageSrc = useMemo(
|
||||
@ -2519,6 +2515,15 @@ export function ImageNode({
|
||||
}),
|
||||
[data.src, displayImageQuality, displayImageWidth]
|
||||
);
|
||||
const fullscreenPreviewSrc = useMemo(() => {
|
||||
const originalUrl = resolveOriginalImageUrl(data.src || "");
|
||||
return buildImageProxyUrl(originalUrl || data.src || "", {
|
||||
delivery: "proxy",
|
||||
width: 4096,
|
||||
quality: 92,
|
||||
format: "webp",
|
||||
});
|
||||
}, [data.src]);
|
||||
const displayCompareSrc = useMemo(
|
||||
() =>
|
||||
buildImageProxyUrl(compareSource, {
|
||||
@ -4673,44 +4678,106 @@ export function ImageNode({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!projectId || !runCanvasRemoteOperation) {
|
||||
toast.error("画布还在加载,请稍后再试");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreatingDetachedResultNode(false);
|
||||
setIsCreatingDetachedResultNode(true);
|
||||
setIsProcessing(true);
|
||||
const actionName = "框选抠图";
|
||||
|
||||
try {
|
||||
const command = createCanvasCapabilityClientCommand({
|
||||
capabilityId: "image.box_cutout",
|
||||
nodeIds: [node.id],
|
||||
projectId,
|
||||
source: "toolbar",
|
||||
args: {
|
||||
...boxCutoutSelection,
|
||||
const newNodeId = addNode({
|
||||
type: "image",
|
||||
position: {
|
||||
x: node.position.x + node.size.width + 20,
|
||||
y: node.position.y,
|
||||
},
|
||||
size: { width: node.size.width, height: node.size.height },
|
||||
data: {
|
||||
src: "",
|
||||
status: "generating",
|
||||
prompt: `${actionName}处理中...`,
|
||||
title: `${displayTitle}-${actionName}`,
|
||||
originalSrc: data.src,
|
||||
metadata: {
|
||||
cropRect: boxCutoutSelection,
|
||||
paddingRatio: BOX_CUTOUT_DEFAULT_PADDING_RATIO,
|
||||
},
|
||||
},
|
||||
connections: [node.id],
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await imageGenerationService.boxCutout({
|
||||
imageUrl: data.src,
|
||||
cropRect: boxCutoutSelection,
|
||||
paddingRatio: BOX_CUTOUT_DEFAULT_PADDING_RATIO,
|
||||
sourceNodeId: node.id,
|
||||
});
|
||||
await runCanvasRemoteOperation(() => executeCanvasToolbarCapability(command));
|
||||
toast.success(`${actionName}完成`);
|
||||
|
||||
if (result.success && result.data?.url) {
|
||||
updateNode(newNodeId, {
|
||||
data: {
|
||||
src: result.data.url,
|
||||
status: "completed",
|
||||
prompt: `${actionName}结果`,
|
||||
title: `${displayTitle}-${actionName}`,
|
||||
originalSrc: data.src,
|
||||
metadata: {
|
||||
cropRect: boxCutoutSelection,
|
||||
cropRectApplied: result.data.cropRectApplied,
|
||||
paddedCropRectApplied: result.data.paddedCropRectApplied,
|
||||
paddingRatio: BOX_CUTOUT_DEFAULT_PADDING_RATIO,
|
||||
editMode: "box-cutout",
|
||||
},
|
||||
},
|
||||
});
|
||||
toast.success(`${actionName}完成`);
|
||||
} else {
|
||||
updateNode(newNodeId, {
|
||||
data: {
|
||||
src: "",
|
||||
status: "failed",
|
||||
prompt: `${actionName}失败`,
|
||||
title: `${displayTitle}-${actionName}-失败`,
|
||||
originalSrc: data.src,
|
||||
metadata: {
|
||||
cropRect: boxCutoutSelection,
|
||||
paddingRatio: BOX_CUTOUT_DEFAULT_PADDING_RATIO,
|
||||
},
|
||||
},
|
||||
});
|
||||
toast.error(result.error || `${actionName}失败`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("框选抠图失败:", error);
|
||||
toast.error(error instanceof Error ? error.message : `${actionName}失败`);
|
||||
updateNode(newNodeId, {
|
||||
data: {
|
||||
src: "",
|
||||
status: "failed",
|
||||
prompt: `${actionName}失败`,
|
||||
title: `${displayTitle}-${actionName}-失败`,
|
||||
originalSrc: data.src,
|
||||
metadata: {
|
||||
cropRect: boxCutoutSelection,
|
||||
paddingRatio: BOX_CUTOUT_DEFAULT_PADDING_RATIO,
|
||||
},
|
||||
},
|
||||
});
|
||||
toast.error(`${actionName}失败,请重试`);
|
||||
} finally {
|
||||
setIsCreatingDetachedResultNode(false);
|
||||
setIsProcessing(false);
|
||||
resetBoxCutoutState();
|
||||
}
|
||||
}, [
|
||||
addNode,
|
||||
boxCutoutSelection,
|
||||
data.src,
|
||||
displayTitle,
|
||||
isProcessing,
|
||||
node.id,
|
||||
projectId,
|
||||
node.position.x,
|
||||
node.position.y,
|
||||
node.size.height,
|
||||
node.size.width,
|
||||
resetBoxCutoutState,
|
||||
runCanvasRemoteOperation,
|
||||
updateNode,
|
||||
]);
|
||||
|
||||
const animateAddToChat = useCallback(async (previewUrl?: string) => {
|
||||
@ -6640,7 +6707,7 @@ export function ImageNode({
|
||||
const executeSharedToolbarCapability = async (
|
||||
action: "rmbg" | "watermark" | "enhance" | "extend" | "layer-split"
|
||||
) => {
|
||||
if (!projectId || !runCanvasRemoteOperation) {
|
||||
if (!projectId) {
|
||||
toast.error("画布还在加载,请稍后再试");
|
||||
return;
|
||||
}
|
||||
@ -6659,7 +6726,21 @@ export function ImageNode({
|
||||
projectId,
|
||||
source: "toolbar",
|
||||
});
|
||||
await runCanvasRemoteOperation(() => executeCanvasToolbarCapability(command));
|
||||
const response = await fetch(`/api/canvas/${projectId}/capabilities`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(command),
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || payload?.success !== true) {
|
||||
throw new Error(payload?.error || `${capability.title}失败`);
|
||||
}
|
||||
|
||||
const projectResult = await canvasService.getProject(projectId);
|
||||
if (!projectResult.success || !projectResult.data?.canvasData) {
|
||||
throw new Error(projectResult.error || "结果已生成,但画布同步失败");
|
||||
}
|
||||
loadCanvas(projectResult.data.canvasData);
|
||||
toast.success(`${capability.title}完成`);
|
||||
} catch (error) {
|
||||
const message =
|
||||
@ -8223,6 +8304,7 @@ export function ImageNode({
|
||||
}
|
||||
};
|
||||
|
||||
// 下载图片 - 服务端统一转为 Photoshop 兼容 PNG,避免后缀和真实格式错配。
|
||||
const isDownloadingOriginalImage = Boolean(downloadProgress);
|
||||
const handleDownload = async () => {
|
||||
if (!data.src) return;
|
||||
@ -8236,16 +8318,24 @@ export function ImageNode({
|
||||
setDownloadProgress({
|
||||
phase: "preparing",
|
||||
message: "正在准备原图...",
|
||||
percent: 5,
|
||||
});
|
||||
|
||||
try {
|
||||
await downloadOriginalImage({
|
||||
url: resolveOriginalImageUrl(data.src) || data.src,
|
||||
await downloadCanvasImageAsPng({
|
||||
url: data.src,
|
||||
name: displayTitle,
|
||||
candidates: [
|
||||
displayImageSrc,
|
||||
fullscreenPreviewSrc,
|
||||
buildImageProxyUrl(resolveOriginalImageUrl(data.src) || data.src, {
|
||||
delivery: "proxy",
|
||||
}),
|
||||
],
|
||||
signal: controller.signal,
|
||||
onProgress: setDownloadProgress,
|
||||
});
|
||||
toast.success("已开始下载");
|
||||
toast.success("原图已开始下载");
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) {
|
||||
toast.message("已取消下载");
|
||||
@ -8349,11 +8439,7 @@ export function ImageNode({
|
||||
{/* 图片内容 - 使用 object-contain 保持原始比例 */}
|
||||
{data.src ? (
|
||||
<div className="relative h-full w-full">
|
||||
{isRetiredStorageUrl(data.src) ? (
|
||||
<div role="status" className="flex h-full w-full items-center justify-center bg-muted p-4 text-center text-sm text-muted-foreground">
|
||||
{RETIRED_STORAGE_MESSAGE}
|
||||
</div>
|
||||
) : !shouldRequestDisplayImage ? (
|
||||
{!shouldRequestDisplayImage ? (
|
||||
<ImageNodeDeferredLoadState />
|
||||
) : isCompareMode && hasCompareSource ? (
|
||||
<div
|
||||
@ -8380,16 +8466,15 @@ export function ImageNode({
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0 bg-slate-50 dark:bg-zinc-900" />
|
||||
<CanvasPreviewImage
|
||||
sourceKey={data.src}
|
||||
<img
|
||||
alt={displayTitle}
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
loading="eager"
|
||||
loading="lazy"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(data.src)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(data.src);
|
||||
if (event.currentTarget.src !== data.src) {
|
||||
event.currentTarget.src = data.src;
|
||||
}
|
||||
}}
|
||||
onLoad={handleDisplayImageLoad}
|
||||
@ -8410,16 +8495,15 @@ export function ImageNode({
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0 bg-slate-50 dark:bg-zinc-900" />
|
||||
<CanvasPreviewImage
|
||||
sourceKey={compareSource}
|
||||
<img
|
||||
alt={`${displayTitle}-原图`}
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
loading="eager"
|
||||
loading="lazy"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(compareSource)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(compareSource);
|
||||
if (event.currentTarget.src !== compareSource) {
|
||||
event.currentTarget.src = compareSource;
|
||||
}
|
||||
}}
|
||||
src={displayCompareSrc}
|
||||
@ -8461,8 +8545,7 @@ export function ImageNode({
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<CanvasPreviewImage
|
||||
sourceKey={data.src}
|
||||
<img
|
||||
alt={displayTitle}
|
||||
className={cn(
|
||||
"h-full w-full bg-slate-50 object-contain dark:bg-zinc-900",
|
||||
@ -8474,7 +8557,7 @@ export function ImageNode({
|
||||
)}
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
loading="eager"
|
||||
loading="lazy"
|
||||
onClick={
|
||||
isThisNodePicking && !boxCutoutMode
|
||||
? handlePickerClick
|
||||
@ -8483,17 +8566,12 @@ export function ImageNode({
|
||||
onDoubleClick={(e) => {
|
||||
if (!isThisNodePicking && !boxCutoutMode && !localEditMode) {
|
||||
e.stopPropagation();
|
||||
setFullscreenPreviewImage({
|
||||
src: e.currentTarget.currentSrc || e.currentTarget.src,
|
||||
width: e.currentTarget.naturalWidth,
|
||||
height: e.currentTarget.naturalHeight,
|
||||
});
|
||||
setFullscreenPreviewOpen(true);
|
||||
}
|
||||
}}
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(data.src)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(data.src);
|
||||
if (event.currentTarget.src !== data.src) {
|
||||
event.currentTarget.src = data.src;
|
||||
}
|
||||
}}
|
||||
onLoad={handleDisplayImageLoad}
|
||||
@ -9404,8 +9482,6 @@ export function ImageNode({
|
||||
) : (
|
||||
<ImageNodeEmptyState
|
||||
detailProgressLabel={detailProgressLabel}
|
||||
failure={data.metadata?.generationFailure}
|
||||
requestId={data.metadata?.generationRequestId}
|
||||
fileInputRef={fileInputRef}
|
||||
generationProgress={generationProgress}
|
||||
onImageUpload={handleImageUpload}
|
||||
@ -11895,7 +11971,6 @@ export function ImageNode({
|
||||
{/* 双击放大预览弹窗 */}
|
||||
{fullscreenPreviewOpen &&
|
||||
data.src &&
|
||||
fullscreenPreviewImage &&
|
||||
createPortal(
|
||||
<div
|
||||
className="fixed inset-0 z-[9999] flex cursor-zoom-out items-center justify-center bg-black/90"
|
||||
@ -11903,7 +11978,7 @@ export function ImageNode({
|
||||
>
|
||||
{/* 关闭按钮 */}
|
||||
<button
|
||||
className="absolute top-4 right-4 z-10 rounded-full bg-slate-950 p-2 transition-colors hover:bg-black"
|
||||
className="absolute top-4 right-4 rounded-full bg-slate-950 p-2 transition-colors hover:bg-black"
|
||||
onClick={() => setFullscreenPreviewOpen(false)}
|
||||
>
|
||||
<svg
|
||||
@ -11921,7 +11996,7 @@ export function ImageNode({
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="absolute top-4 right-16 z-10 inline-flex items-center gap-1.5 rounded-full bg-slate-950 px-3 py-2 text-sm text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:opacity-60"
|
||||
className="absolute top-4 right-16 inline-flex items-center gap-1.5 rounded-full bg-slate-950 px-3 py-2 text-sm text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:opacity-60"
|
||||
disabled={isDownloadingOriginalImage}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
@ -11940,11 +12015,13 @@ export function ImageNode({
|
||||
</button>
|
||||
|
||||
{/* 图片 */}
|
||||
<ProgressiveImagePreview
|
||||
<img
|
||||
alt={data.prompt || "图片预览"}
|
||||
className="max-h-[95vh] max-w-[95vw] object-contain"
|
||||
src={resolveOriginalImageUrl(data.src) || data.src}
|
||||
preview={fullscreenPreviewImage}
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
src={fullscreenPreviewSrc}
|
||||
style={activeImageAdjustmentsStyle}
|
||||
/>
|
||||
|
||||
|
||||
@ -1,32 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { forwardRef, type ImgHTMLAttributes, useState } from "react";
|
||||
|
||||
type Props = Omit<ImgHTMLAttributes<HTMLImageElement>, "src"> & { src: string; sourceKey: string };
|
||||
|
||||
export const CanvasPreviewImage = forwardRef<HTMLImageElement, Props>(function CanvasPreviewImage(
|
||||
{ src, sourceKey, onLoad, style, ...props }, ref,
|
||||
) {
|
||||
const [displayed, setDisplayed] = useState({ sourceKey, src });
|
||||
const visibleSrc = displayed.sourceKey === sourceKey ? displayed.src : src;
|
||||
const sources = visibleSrc === src ? [src] : [visibleSrc, src];
|
||||
return <>{sources.map(candidate => {
|
||||
const visible = candidate === visibleSrc;
|
||||
return <img
|
||||
{...props}
|
||||
key={candidate}
|
||||
ref={visible ? ref : undefined}
|
||||
src={candidate}
|
||||
alt={visible ? props.alt : ""}
|
||||
aria-hidden={visible ? props["aria-hidden"] : true}
|
||||
style={visible ? style : { ...style, position: "absolute", inset: 0, opacity: 0, pointerEvents: "none" }}
|
||||
onLoad={event => {
|
||||
const image = event.currentTarget;
|
||||
onLoad?.(event);
|
||||
void image.decode().then(() => {
|
||||
if (image.isConnected && candidate === src) setDisplayed({ sourceKey, src: candidate });
|
||||
}).catch(() => undefined);
|
||||
}}
|
||||
/>;
|
||||
})}</>;
|
||||
});
|
||||
@ -3,14 +3,11 @@
|
||||
import { AlertCircle, ImagePlus, Loader2 } from "lucide-react";
|
||||
import type React from "react";
|
||||
import { GenerationDotPlaceholder } from "@/components/generation-dot-placeholder";
|
||||
import type { RequestFailureDetails } from "@/lib/request-error";
|
||||
|
||||
interface ImageNodeEmptyStateProps {
|
||||
detailProgressLabel?: string;
|
||||
fileInputRef: React.Ref<HTMLInputElement>;
|
||||
generationProgress?: number | null;
|
||||
failure?: RequestFailureDetails;
|
||||
requestId?: string;
|
||||
onImageUpload: (event: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
onSelectFile: (event: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
status?: string;
|
||||
@ -55,8 +52,6 @@ export function ImageNodeEmptyState({
|
||||
detailProgressLabel,
|
||||
fileInputRef,
|
||||
generationProgress,
|
||||
failure,
|
||||
requestId,
|
||||
onImageUpload,
|
||||
onSelectFile,
|
||||
status,
|
||||
@ -94,7 +89,7 @@ export function ImageNodeEmptyState({
|
||||
if (status === "failed") {
|
||||
const failedTitle = detailProgressLabel || "生成失败";
|
||||
return (
|
||||
<div role="alert" className="flex h-full w-full flex-col items-center justify-center overflow-auto bg-[#fff7f8] px-6 text-center dark:bg-red-950/40">
|
||||
<div className="flex h-full w-full select-none flex-col items-center justify-center bg-[#fff7f8] px-6 text-center dark:bg-red-950/40">
|
||||
<span className="mb-3 flex h-12 w-12 items-center justify-center rounded-[18px] border border-[#f2d7dd] bg-white text-[#d24f63] shadow-[0_0_0_1px_rgba(242,215,221,0.22)]">
|
||||
<AlertCircle className="h-5 w-5" />
|
||||
</span>
|
||||
@ -102,9 +97,8 @@ export function ImageNodeEmptyState({
|
||||
{failedTitle}
|
||||
</span>
|
||||
<span className="mt-1 text-xs text-[#b77480]">
|
||||
{failure?.recommendation || (failedTitle.includes("上传") ? "请重新选择文件" : "请查看对话中的错误原因和处理建议")}
|
||||
{failedTitle.includes("上传") ? "请重新选择文件" : "请重新上传或再试一次"}
|
||||
</span>
|
||||
{requestId ? <span className="mt-2 select-text break-all text-xs text-[#b77480]">请求编号:{requestId}</span> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -15,10 +15,9 @@ import {
|
||||
splitOpenClawChartBlocks,
|
||||
} from "@/components/elements/openclaw-chart-card";
|
||||
import { ResponsePdfDownloadButton } from "@/components/elements/response-pdf-download";
|
||||
import { buildImageFallbackUrl, buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { splitMarkdownImages } from "@/lib/canvas/markdown-image-segments";
|
||||
import { stableStreamingMarkdown } from "@/lib/canvas/markdown-image-streaming";
|
||||
import { getGatewayErrorPageMessage } from "@/lib/request-error";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
@ -442,8 +441,8 @@ function MarkdownTableImagePreview({
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(src)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(src);
|
||||
if (event.currentTarget.src !== src) {
|
||||
event.currentTarget.src = src;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -473,8 +472,8 @@ function MarkdownTableImagePreview({
|
||||
decoding="async"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onError={(event) => {
|
||||
if (event.currentTarget.src !== buildImageFallbackUrl(originalSrc)) {
|
||||
event.currentTarget.src = buildImageFallbackUrl(originalSrc);
|
||||
if (event.currentTarget.src !== originalSrc) {
|
||||
event.currentTarget.src = originalSrc;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@ -1029,10 +1028,7 @@ export const Response = ({
|
||||
|
||||
const rawText =
|
||||
typeof props.children === "string"
|
||||
? normalizeMarkdownContent(stableStreamingMarkdown(
|
||||
getGatewayErrorPageMessage(props.children) || props.children,
|
||||
isMarkdownStreaming
|
||||
))
|
||||
? normalizeMarkdownContent(stableStreamingMarkdown(props.children, isMarkdownStreaming))
|
||||
: null;
|
||||
const shouldShowPdfDownload =
|
||||
Boolean(enablePdfDownload && rawText && hasDownloadableReportContent(rawText));
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BloubAvatar } from "@/components/bloub-avatar";
|
||||
import type { StateId } from "@/lib/bloub-official/states";
|
||||
import { cn } from "@/lib/utils";
|
||||
@ -25,17 +26,193 @@ interface GenerationDotPlaceholderProps {
|
||||
const PHASE_TITLES: Record<GenerationPhase, string> = {
|
||||
idle: "正在创建图片",
|
||||
queued: "等待开始生成",
|
||||
processing: "等待模型返回图片",
|
||||
finalizing: "正在保存生成结果",
|
||||
processing: "生成初稿中",
|
||||
finalizing: "正在润饰细节",
|
||||
failed: "生成失败",
|
||||
completed: "生成完成",
|
||||
};
|
||||
|
||||
const GENERATION_STATUS_TITLES = [
|
||||
"正在理解画面关系",
|
||||
"正在读取参考图片",
|
||||
"正在分析主体轮廓",
|
||||
"正在识别关键元素",
|
||||
"正在整理构图线索",
|
||||
"正在确认画面比例",
|
||||
"正在匹配视觉风格",
|
||||
"正在提取材质细节",
|
||||
"正在梳理光影方向",
|
||||
"正在构建初始画面",
|
||||
"正在生成第一版构图",
|
||||
"正在安排主体位置",
|
||||
"正在校准画面重心",
|
||||
"正在补全背景层次",
|
||||
"正在保持主体一致",
|
||||
"正在优化边缘结构",
|
||||
"正在调整透视关系",
|
||||
"正在细化空间层次",
|
||||
"正在增强画面清晰度",
|
||||
"正在统一色彩倾向",
|
||||
"正在检查参考一致性",
|
||||
"正在处理局部细节",
|
||||
"正在补充纹理信息",
|
||||
"正在修正不自然区域",
|
||||
"正在平衡明暗对比",
|
||||
"正在优化产品质感",
|
||||
"正在调整阴影落点",
|
||||
"正在整理背景干扰",
|
||||
"正在增强真实感",
|
||||
"正在重绘细小结构",
|
||||
"正在合成高清结果",
|
||||
"正在检查主体完整性",
|
||||
"正在优化画面边缘",
|
||||
"正在处理反光细节",
|
||||
"正在提升材质表现",
|
||||
"正在微调构图节奏",
|
||||
"正在清理多余噪点",
|
||||
"正在强化视觉焦点",
|
||||
"正在校正颜色偏差",
|
||||
"正在保留参考特征",
|
||||
"正在生成高分辨率版本",
|
||||
"正在压实画面层次",
|
||||
"正在修饰局部瑕疵",
|
||||
"正在检查文字与图形",
|
||||
"正在稳定画面结构",
|
||||
"正在优化细节密度",
|
||||
"正在完善背景过渡",
|
||||
"正在增强主体质感",
|
||||
"正在统一整体光感",
|
||||
"正在检查比例关系",
|
||||
"正在修正边缘锯齿",
|
||||
"正在提升清晰观感",
|
||||
"正在处理最后细节",
|
||||
"正在准备预览结果",
|
||||
"正在同步生成进度",
|
||||
"正在确认输出尺寸",
|
||||
"正在整理结果文件",
|
||||
"正在校验图片可用性",
|
||||
"正在生成最终预览",
|
||||
"正在完成高清渲染",
|
||||
"正在保存生成结果",
|
||||
"正在写入画布节点",
|
||||
"正在同步到对话框",
|
||||
"正在检查结果完整性",
|
||||
"正在收尾生成任务",
|
||||
"正在等待服务商返回",
|
||||
"正在保持连接状态",
|
||||
"正在确认生成结果",
|
||||
"正在拉取图片地址",
|
||||
"正在准备展示图片",
|
||||
"正在完成最后处理",
|
||||
"正在刷新画布内容",
|
||||
"正在整理图片信息",
|
||||
"正在完成本次生成",
|
||||
"正在即将展示结果",
|
||||
];
|
||||
|
||||
const LONG_WAIT_TITLE_THRESHOLD_MS = 5 * 60 * 1000;
|
||||
const LONG_WAIT_STATUS_TITLES = [
|
||||
"服务繁忙,排队处理中",
|
||||
"高峰期生成较慢,请耐心等候",
|
||||
"仍在保持连接,等待模型返回",
|
||||
"结果返回后会自动展示",
|
||||
];
|
||||
const STATUS_TITLE_DURATIONS_MS = GENERATION_STATUS_TITLES.map((_, index) => {
|
||||
const rhythm = [3600, 5200, 4100, 6100, 3300, 4700, 5700, 3900, 6800, 4400];
|
||||
return rhythm[index % rhythm.length];
|
||||
});
|
||||
const TYPEWRITER_START_DELAY_MS = 120;
|
||||
const TYPEWRITER_BASE_STEP_MS = 46;
|
||||
|
||||
function clampProgress(value: number) {
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(0, Math.min(100, Math.round(value)));
|
||||
}
|
||||
|
||||
function estimateProgress(phase: GenerationPhase, elapsedMs: number) {
|
||||
if (phase === "completed" || phase === "failed") return 100;
|
||||
if (phase === "finalizing") return 96;
|
||||
if (phase === "queued") {
|
||||
return clampProgress(6 + Math.min(12, elapsedMs / 3500));
|
||||
}
|
||||
if (phase === "processing") {
|
||||
const eased = 1 - Math.exp(-elapsedMs / 85_000);
|
||||
return clampProgress(18 + eased * 78);
|
||||
}
|
||||
return clampProgress(Math.min(8, elapsedMs / 1000));
|
||||
}
|
||||
|
||||
function getStatusTitleState(elapsedMs: number, initialTitle?: string) {
|
||||
const titles = initialTitle
|
||||
? [
|
||||
initialTitle,
|
||||
...GENERATION_STATUS_TITLES.filter((item) => item !== initialTitle),
|
||||
]
|
||||
: GENERATION_STATUS_TITLES;
|
||||
const durations = initialTitle
|
||||
? [4200, ...STATUS_TITLE_DURATIONS_MS]
|
||||
: STATUS_TITLE_DURATIONS_MS;
|
||||
|
||||
let cursor = Math.max(0, elapsedMs);
|
||||
for (let index = 0; index < titles.length; index += 1) {
|
||||
const duration = durations[index] || 4600;
|
||||
if (cursor < duration) {
|
||||
return {
|
||||
elapsedInTitle: cursor,
|
||||
index,
|
||||
title:
|
||||
titles[index] ||
|
||||
titles[titles.length - 1] ||
|
||||
PHASE_TITLES.processing,
|
||||
};
|
||||
}
|
||||
cursor -= duration;
|
||||
}
|
||||
|
||||
return {
|
||||
elapsedInTitle: durations[durations.length - 1] || 4600,
|
||||
index: titles.length - 1,
|
||||
title: titles[titles.length - 1] || PHASE_TITLES.processing,
|
||||
};
|
||||
}
|
||||
|
||||
function getLongWaitTitleState(elapsedMs: number, initialTitle?: string) {
|
||||
const titles = initialTitle
|
||||
? [
|
||||
initialTitle,
|
||||
...LONG_WAIT_STATUS_TITLES.filter((item) => item !== initialTitle),
|
||||
]
|
||||
: LONG_WAIT_STATUS_TITLES;
|
||||
const elapsedAfterThreshold = Math.max(
|
||||
0,
|
||||
elapsedMs - LONG_WAIT_TITLE_THRESHOLD_MS
|
||||
);
|
||||
const duration = 7600;
|
||||
const index = Math.floor(elapsedAfterThreshold / duration) % titles.length;
|
||||
|
||||
return {
|
||||
elapsedInTitle: elapsedAfterThreshold % duration,
|
||||
index,
|
||||
title: titles[index] || titles[0] || PHASE_TITLES.processing,
|
||||
};
|
||||
}
|
||||
|
||||
function getTypewriterText(text: string, elapsedInTitle: number, index: number) {
|
||||
const chars = Array.from(text);
|
||||
if (chars.length === 0) return "";
|
||||
const step = TYPEWRITER_BASE_STEP_MS + (index % 5) * 8;
|
||||
const visibleCount = Math.max(
|
||||
1,
|
||||
Math.min(
|
||||
chars.length,
|
||||
Math.floor(
|
||||
Math.max(0, elapsedInTitle - TYPEWRITER_START_DELAY_MS) / step
|
||||
) + 1
|
||||
)
|
||||
);
|
||||
return chars.slice(0, visibleCount).join("");
|
||||
}
|
||||
|
||||
function getBloubState(phase: GenerationPhase): StateId {
|
||||
if (phase === "failed") return "alert";
|
||||
if (phase === "completed") return "wink";
|
||||
@ -51,10 +228,39 @@ export function GenerationDotPlaceholder({
|
||||
showProgress = true,
|
||||
title,
|
||||
}: GenerationDotPlaceholderProps) {
|
||||
const resolvedProgress = typeof progress === "number" && Number.isFinite(progress)
|
||||
? clampProgress(progress) : null;
|
||||
const resolvedTitle = title || PHASE_TITLES[phase];
|
||||
const [elapsedMs, setElapsedMs] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const startedAt = Date.now();
|
||||
const timer = window.setInterval(() => {
|
||||
setElapsedMs(Date.now() - startedAt);
|
||||
}, 90);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [phase]);
|
||||
|
||||
const resolvedProgress = clampProgress(
|
||||
typeof progress === "number" ? progress : estimateProgress(phase, elapsedMs)
|
||||
);
|
||||
const isLongWaitTitle =
|
||||
(phase === "processing" || phase === "finalizing") &&
|
||||
elapsedMs >= LONG_WAIT_TITLE_THRESHOLD_MS;
|
||||
const statusTitleState = isLongWaitTitle
|
||||
? getLongWaitTitleState(elapsedMs, title)
|
||||
: getStatusTitleState(elapsedMs, title);
|
||||
const rotatingTitle = getTypewriterText(
|
||||
statusTitleState.title,
|
||||
statusTitleState.elapsedInTitle,
|
||||
statusTitleState.index
|
||||
);
|
||||
const resolvedTitle =
|
||||
phase === "processing" || phase === "finalizing"
|
||||
? rotatingTitle
|
||||
: title || PHASE_TITLES[phase];
|
||||
const playSequence = phase === "processing" || phase === "finalizing";
|
||||
const progressStyle = useMemo(
|
||||
() => ({ width: `${resolvedProgress}%` }),
|
||||
[resolvedProgress]
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
@ -75,6 +281,10 @@ export function GenerationDotPlaceholder({
|
||||
)}
|
||||
>
|
||||
{resolvedTitle}
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="ml-1 inline-block h-[1em] w-[0.08em] translate-y-[0.15em] animate-[generationCursorBlink_1s_steps(1,end)_infinite] bg-current"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 items-center justify-center py-3">
|
||||
@ -87,13 +297,13 @@ export function GenerationDotPlaceholder({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showProgress && phase !== "completed" ? (
|
||||
{showProgress ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between text-[12px] font-medium text-[#7d838b] dark:text-zinc-400">
|
||||
<span>{phase === "failed" ? "已停止" : resolvedProgress === null ? "等待结果,返回后自动展示" : "生成进度"}</span>
|
||||
{resolvedProgress !== null ? <span>{resolvedProgress}%</span> : null}
|
||||
<span>{phase === "failed" ? "已停止" : "生成进度"}</span>
|
||||
<span>{resolvedProgress}%</span>
|
||||
</div>
|
||||
{resolvedProgress !== null ? <div role="progressbar" aria-valuenow={resolvedProgress} aria-valuemin={0} aria-valuemax={100} className="h-1.5 overflow-hidden rounded-full bg-white/80 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.035)] dark:bg-white/10 dark:shadow-none">
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/80 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.035)] dark:bg-white/10 dark:shadow-none">
|
||||
<div
|
||||
className={cn(
|
||||
"h-full rounded-full transition-[width] duration-700 ease-out",
|
||||
@ -101,12 +311,25 @@ export function GenerationDotPlaceholder({
|
||||
? "bg-[#c7ccd3] dark:bg-zinc-600"
|
||||
: "bg-[#0a0a0c] dark:bg-[#3ecf8e]"
|
||||
)}
|
||||
style={{ width: `${resolvedProgress}%` }}
|
||||
style={progressStyle}
|
||||
/>
|
||||
</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<style jsx>{`
|
||||
@keyframes generationCursorBlink {
|
||||
0%,
|
||||
48% {
|
||||
opacity: 1;
|
||||
}
|
||||
49%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,68 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { isRetiredStorageUrl } from "@/lib/storage/retired-storage";
|
||||
|
||||
type HomeImageProps = {
|
||||
sources: Array<string | null | undefined>;
|
||||
alt: string;
|
||||
className?: string;
|
||||
imageClassName?: string;
|
||||
fallback?: ReactNode;
|
||||
loading?: "lazy" | "eager";
|
||||
onUnavailable?: () => void;
|
||||
};
|
||||
|
||||
function imageCandidates(source: string) {
|
||||
// These two domains are documented aliases for the same gongxiangpan store.
|
||||
// Do not rewrite other buckets, providers, signed URLs or user-supplied hosts.
|
||||
try {
|
||||
const url = new URL(source);
|
||||
if (url.origin === "https://s3.yydd.ai" &&
|
||||
url.pathname.startsWith("/gongxiangpan/") && !url.search && !url.hash) {
|
||||
return [`https://s3.jiansun.vip${url.pathname}`, source];
|
||||
}
|
||||
} catch { /* Relative site assets need no host rewrite. */ }
|
||||
return [source];
|
||||
}
|
||||
|
||||
/** Keep failed image elements out of view, trying each distinct source once. */
|
||||
export function HomeImage(props: HomeImageProps) {
|
||||
const sources = [...new Set(props.sources
|
||||
.filter((url): url is string => Boolean(url?.trim()) && !isRetiredStorageUrl(url))
|
||||
.flatMap(imageCandidates))];
|
||||
return <HomeImageAttempt key={JSON.stringify(sources)} {...props} sources={sources} />;
|
||||
}
|
||||
|
||||
function HomeImageAttempt({
|
||||
sources, alt, className, imageClassName, fallback, loading = "lazy", onUnavailable,
|
||||
}: Omit<HomeImageProps, "sources"> & { sources: string[] }) {
|
||||
const [index, setIndex] = useState(0);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const source = sources[index];
|
||||
return (
|
||||
<span className={`relative block overflow-hidden ${className || ""}`}>
|
||||
{!loaded && (
|
||||
<span className={fallback ? "block" : "block aspect-[4/5] rounded-[12px] bg-[#e8e8e8] dark:bg-[#1b1c20]"}>
|
||||
{fallback}
|
||||
</span>
|
||||
)}
|
||||
{source ? (
|
||||
<img
|
||||
key={source}
|
||||
src={source}
|
||||
alt={alt}
|
||||
loading={loading}
|
||||
decoding="async"
|
||||
className={`${imageClassName || ""} ${loaded ? "" : "absolute inset-0 opacity-0"}`}
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => {
|
||||
setLoaded(false);
|
||||
setIndex(index + 1);
|
||||
if (index + 1 >= sources.length) onUnavailable?.();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@ -1,7 +1,6 @@
|
||||
import { ReferenceIcon } from "@/components/lovart/reference-icon";
|
||||
import { Gem, Heart, Loader2, PlayCircle } from "lucide-react";
|
||||
import { useState, type Ref } from "react";
|
||||
import { HomeImage } from "./home-image";
|
||||
import type { Ref } from "react";
|
||||
import type { FeaturedImage } from "./types";
|
||||
|
||||
type LovartFeaturedGalleryProps = {
|
||||
@ -31,10 +30,6 @@ function getFeaturedPreviewUrl(item: FeaturedImage) {
|
||||
return `${source}?imageView2/2/w/900/q/78`;
|
||||
}
|
||||
|
||||
function imageIdentity(item: FeaturedImage) {
|
||||
return JSON.stringify([item.id, item.thumbnailUrl, item.originalUrl]);
|
||||
}
|
||||
|
||||
export function LovartFeaturedGallery({
|
||||
onOpenProjects,
|
||||
onOpenMaterials,
|
||||
@ -47,13 +42,6 @@ export function LovartFeaturedGallery({
|
||||
isLoadingMoreFeatured,
|
||||
setActiveCategory,
|
||||
}: LovartFeaturedGalleryProps) {
|
||||
const [unavailable, setUnavailable] = useState<Set<string>>(() => new Set());
|
||||
const [retryVersion, setRetryVersion] = useState(0);
|
||||
const uniqueItems = [...new Map(featuredItems.map((item) => [item.id, item])).values()];
|
||||
const visibleItems = uniqueItems.filter((item) =>
|
||||
Boolean(item.thumbnailUrl || item.originalUrl),
|
||||
);
|
||||
const unavailableCount = uniqueItems.filter(item => unavailable.has(imageIdentity(item))).length;
|
||||
return (
|
||||
<section
|
||||
ref={featuredSectionRef}
|
||||
@ -100,48 +88,44 @@ export function LovartFeaturedGallery({
|
||||
))}
|
||||
</div>
|
||||
|
||||
{unavailableCount > 0 && (
|
||||
<div role="status" className="mt-4 flex items-center gap-3 text-xs text-black/50 dark:text-white/50">
|
||||
<span>{unavailableCount} 张灵感图片加载失败,请重试。</span>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 underline underline-offset-4 hover:text-black dark:hover:text-white"
|
||||
onClick={() => {
|
||||
setUnavailable(new Set());
|
||||
setRetryVersion((version) => version + 1);
|
||||
}}
|
||||
>
|
||||
重试加载
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{visibleItems.length === 0 ? (
|
||||
{featuredItems.length === 0 ? (
|
||||
<div className="mt-[22px] rounded-[10px] border border-dashed border-black/15 bg-[#f7f7f7] p-10 text-center text-[14px] text-black/35 dark:border-white/12 dark:bg-[#141416] dark:text-white/35">
|
||||
{isLoadingFeatured
|
||||
? "灵感内容加载中..."
|
||||
: unavailableCount > 0 ? "图片暂时无法加载,请稍后重试。" : "当前没有可展示的灵感数据。"}
|
||||
: "当前没有可展示的灵感数据。"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-6 columns-1 gap-4 sm:columns-2 lg:columns-4">
|
||||
{visibleItems.map((item) => (
|
||||
{featuredItems.map((item, index) => (
|
||||
<button
|
||||
key={`${imageIdentity(item)}:${retryVersion}`}
|
||||
key={item.id}
|
||||
type="button"
|
||||
disabled={unavailable.has(imageIdentity(item))}
|
||||
onClick={() =>
|
||||
window.open(item.originalUrl || item.thumbnailUrl, "_blank")
|
||||
}
|
||||
className="group mb-[24px] block w-full cursor-pointer break-inside-avoid text-left"
|
||||
>
|
||||
{unavailable.has(imageIdentity(item)) ? (
|
||||
<div className="flex aspect-[4/5] items-center justify-center rounded-[12px] bg-muted p-4 text-sm text-muted-foreground">图片加载失败</div>
|
||||
) : <HomeImage
|
||||
sources={[getFeaturedPreviewUrl(item), item.thumbnailUrl, item.originalUrl]}
|
||||
<img
|
||||
src={getFeaturedPreviewUrl(item)}
|
||||
alt={item.prompt || "灵感图"}
|
||||
loading="lazy"
|
||||
onUnavailable={() => setUnavailable((previous) => new Set(previous).add(imageIdentity(item)))}
|
||||
imageClassName="block h-auto w-full rounded-[12px] bg-[#e8e8e8] object-cover transition-transform duration-150 ease-out will-change-transform group-hover:scale-[1.008] dark:bg-[#1b1c20]"
|
||||
/>}
|
||||
decoding="async"
|
||||
onError={(event) => {
|
||||
const image = event.currentTarget;
|
||||
const fallbackUrl = item.originalUrl || item.thumbnailUrl;
|
||||
|
||||
if (
|
||||
!fallbackUrl ||
|
||||
image.dataset.fallbackApplied === "true"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
image.dataset.fallbackApplied = "true";
|
||||
image.src = fallbackUrl;
|
||||
}}
|
||||
className="block h-auto w-full rounded-[12px] bg-[#e8e8e8] object-cover transition-transform duration-150 ease-out will-change-transform group-hover:scale-[1.008] dark:bg-[#1b1c20]"
|
||||
/>
|
||||
<div className="mt-[8px] flex h-[22px] items-center justify-between text-[11px] font-normal leading-none text-[#b8b8b8] dark:text-white/45">
|
||||
<div className="flex min-w-0 items-center gap-[6px] pr-2">
|
||||
<span className="flex h-[16px] w-[16px] shrink-0 items-center justify-center overflow-hidden rounded-full bg-[#d8d8d8] text-[8px] font-medium text-white">
|
||||
@ -154,11 +138,11 @@ export function LovartFeaturedGallery({
|
||||
<div className="inline-flex shrink-0 items-center gap-[7px] text-[11px] leading-none">
|
||||
<span className="inline-flex items-center gap-[4px]">
|
||||
<PlayCircle className="h-[11px] w-[11px]" strokeWidth={2} />
|
||||
{(1200 + featuredItems.indexOf(item) * 37).toLocaleString()}
|
||||
{(1200 + index * 37).toLocaleString()}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-[4px]">
|
||||
<Heart className="h-[11px] w-[11px]" strokeWidth={2} />
|
||||
{(20 + (featuredItems.indexOf(item) % 9) * 11).toLocaleString()}
|
||||
{(20 + (index % 9) * 11).toLocaleString()}
|
||||
</span>
|
||||
<Gem className="h-[11px] w-[11px]" strokeWidth={2} />
|
||||
</div>
|
||||
|
||||
@ -13,7 +13,6 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import type { LovartHomeSidebarItemKey } from "@/lib/home/lovart-sidebar-config";
|
||||
import type { NavLink, TutorialVideo } from "./types";
|
||||
import { HomeImage } from "./home-image";
|
||||
|
||||
type SidebarItem = {
|
||||
iconUrl?: string | null;
|
||||
@ -184,18 +183,17 @@ export function LovartSidebar({
|
||||
onClick={onHome}
|
||||
title={siteName}
|
||||
>
|
||||
<HomeImage
|
||||
sources={[siteLogo]}
|
||||
{siteLogo ? (
|
||||
<img
|
||||
src={siteLogo}
|
||||
alt={siteName}
|
||||
loading="eager"
|
||||
className="h-7 w-7 rounded-full object-cover"
|
||||
imageClassName="h-7 w-7 rounded-full object-cover"
|
||||
fallback={
|
||||
<span aria-hidden="true" className="flex h-7 w-7 items-center justify-center rounded-full bg-black text-[12px] font-semibold text-white dark:bg-white dark:text-black">
|
||||
{siteName.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<span className="flex h-7 w-7 items-center justify-center rounded-full bg-black text-[12px] font-semibold text-white dark:bg-white dark:text-black">
|
||||
{siteName.slice(0, 1).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">{siteName}</TooltipContent>
|
||||
|
||||
@ -918,9 +918,9 @@ export function ImageAnnotator({
|
||||
|
||||
setIsRemovingBg(true);
|
||||
try {
|
||||
const input = /^https?:\/\//i.test(originalImageUrl)
|
||||
? { imageUrl: originalImageUrl }
|
||||
: { image_base64: await imageUrlToBase64(originalImageUrl) };
|
||||
// 使用原图URL获取原图数据,而不是canvas的预览图
|
||||
const base64Data = await imageUrlToBase64(originalImageUrl);
|
||||
logger.debug("rmbg_source_prepared", { base64Length: base64Data.length });
|
||||
|
||||
// 调用抠图API
|
||||
const response = await fetch("/api/rmbg", {
|
||||
@ -929,7 +929,7 @@ export function ImageAnnotator({
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...input,
|
||||
image_base64: base64Data,
|
||||
prompt: "画图标注-抠图处理", // 可选:添加提示词
|
||||
}),
|
||||
});
|
||||
|
||||
@ -41,11 +41,45 @@ const PHASE_HINT: Record<NonNullable<ImageGenerationLoadingProps["phase"]>, stri
|
||||
idle: "任务已创建,正在初始化生成参数。",
|
||||
queued: "任务已进入队列,请稍候。",
|
||||
processing: "模型正在生成图片,请稍候。",
|
||||
finalizing: "图片已返回,正在保存并同步到对话。",
|
||||
failed: "本次处理已停止,请查看对话中的原因和建议。",
|
||||
finalizing: "图片已生成完成,正在同步到对话。",
|
||||
failed: "生成失败,请重试。",
|
||||
};
|
||||
|
||||
const LONG_PROCESSING_HINTS = [
|
||||
"正在读取参考图与文字需求。",
|
||||
"正在分析主体、场景和构图关系。",
|
||||
"正在提取画面中的关键视觉特征。",
|
||||
"正在确认图片比例和输出尺寸。",
|
||||
"正在匹配当前模型的最佳生成参数。",
|
||||
"正在把参考图信息提交给模型。",
|
||||
"正在等待模型完成第一阶段推理。",
|
||||
"正在生成初始画面结构。",
|
||||
"正在保持主体特征和参考一致。",
|
||||
"正在补全画面中的空间层次。",
|
||||
"正在调整光影方向和明暗关系。",
|
||||
"正在优化主体边缘与背景融合。",
|
||||
"正在细化材质、纹理和局部细节。",
|
||||
"正在减少画面噪点和不自然区域。",
|
||||
"正在提升清晰度与整体质感。",
|
||||
"正在检查生成结果的完整性。",
|
||||
"正在处理高分辨率输出。",
|
||||
"正在等待服务商返回最终图片。",
|
||||
"正在保存图片并同步到对话。",
|
||||
"正在准备把结果显示到画布。",
|
||||
];
|
||||
const LONG_WAIT_SECONDS = 5 * 60;
|
||||
const LONG_WAIT_HINT =
|
||||
"服务繁忙,模型可能正在排队或自动尝试备用通道,请耐心等候,结果返回后会自动同步到画布。";
|
||||
|
||||
function getLongProcessingHint(phase: NonNullable<ImageGenerationLoadingProps["phase"]>, elapsedSeconds: number) {
|
||||
if (phase !== "processing" && phase !== "finalizing") return PHASE_HINT[phase];
|
||||
if (elapsedSeconds >= LONG_WAIT_SECONDS) return LONG_WAIT_HINT;
|
||||
const index = Math.min(
|
||||
LONG_PROCESSING_HINTS.length - 1,
|
||||
Math.floor(Math.max(0, elapsedSeconds) / 15)
|
||||
);
|
||||
return LONG_PROCESSING_HINTS[index];
|
||||
}
|
||||
|
||||
function formatImageQueueWaitLabel(estimatedWaitMs?: number) {
|
||||
const numeric = Number(estimatedWaitMs || 0);
|
||||
@ -104,8 +138,16 @@ export const ImageGenerationLoading = memo(
|
||||
const isLongWait =
|
||||
resolvedElapsedSeconds >= LONG_WAIT_SECONDS &&
|
||||
(phase === "processing" || phase === "finalizing");
|
||||
const elapsedLabel = resolvedElapsedSeconds > 0 ? `已等待 ${resolvedElapsedSeconds}s` : "";
|
||||
const phaseHint = PHASE_HINT[phase];
|
||||
const estimateRangeLabel = isLongWait
|
||||
? "单次最长约10分钟"
|
||||
: providerType === "grsai-gpt-image"
|
||||
? "2~5分钟"
|
||||
: "60~120秒";
|
||||
const elapsedLabel =
|
||||
resolvedElapsedSeconds > 0
|
||||
? `已等待 ${resolvedElapsedSeconds}s`
|
||||
: `预计 ${estimateRangeLabel}`;
|
||||
const phaseHint = getLongProcessingHint(phase, resolvedElapsedSeconds);
|
||||
const queueLine =
|
||||
phase === "queued" && Number.isFinite(queuePosition)
|
||||
? Math.max(0, Number(queuePosition || 0)) > 0
|
||||
@ -147,12 +189,12 @@ export const ImageGenerationLoading = memo(
|
||||
}
|
||||
compact={count > 1}
|
||||
phase={phase}
|
||||
title={isLongWait && phase === "processing" ? "模型尚未返回结果,请勿重复提交" : undefined}
|
||||
title={isLongWait ? "服务繁忙,排队处理中" : undefined}
|
||||
/>
|
||||
|
||||
<div className="space-y-0.5 text-[#9aa3b2]">
|
||||
<div className="text-[13px] font-medium">
|
||||
使用 {resolvedModelName} 生成图片
|
||||
使用 {resolvedModelName} 生成图片,预计 {estimateRangeLabel}
|
||||
</div>
|
||||
{queueLine ? <div className="text-[13px]">{queueLine}</div> : null}
|
||||
{queueDetailLine ? <div className="text-[13px]">{queueDetailLine}</div> : null}
|
||||
|
||||
@ -5,7 +5,7 @@ import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ChevronDown, ChevronUp, Link2, Scan, SlidersHorizontal, Sparkles } from "lucide-react";
|
||||
import { getGrsaiGptImageOutputSize } from "@/lib/ai/grsai-gpt-image-sizes";
|
||||
import { getVip98kQualityOptions, resolveVip98kImageTaskSize, type Vip98kTaskInvocation } from "@/lib/ai/vip98k-task-invocation";
|
||||
import { resolveVip98kImageTaskSize } from "@/lib/ai/vip98k-task-invocation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
@ -207,7 +207,7 @@ export function ImageParamsBar({
|
||||
normalizeImageSizeValue(size, "")
|
||||
)
|
||||
: []
|
||||
).filter((size) => providerType !== "alibaba-image" || size === "1K" || size === "2K");
|
||||
);
|
||||
|
||||
const buildImageSizeOptions = () => {
|
||||
if (imageGenConfig?.supportsSize === false) {
|
||||
@ -220,7 +220,6 @@ export function ImageParamsBar({
|
||||
|
||||
return DEFAULT_IMAGE_SIZE_OPTIONS.filter((option) => {
|
||||
if (option.disabled) return false;
|
||||
if (providerType === "alibaba-image" && option.value === "4K") return false;
|
||||
if (!imageGenConfig) return true;
|
||||
if (option.value === "1K") return imageGenConfig.supports1K !== false;
|
||||
if (option.value === "2K") return imageGenConfig.supports2K !== false;
|
||||
@ -268,17 +267,6 @@ export function ImageParamsBar({
|
||||
availableAspectRatioOptions[0]?.value ||
|
||||
"1:1";
|
||||
|
||||
const declaredQualityOptions = providerType === "vip98k"
|
||||
? getVip98kQualityOptions((imageGenConfig?.vip98k?.invocation as Vip98kTaskInvocation | undefined)?.inputSchema)
|
||||
: undefined;
|
||||
const qualityOptions = ([
|
||||
{ label: "自动", value: "auto" },
|
||||
{ label: "高", value: "high" },
|
||||
{ label: "中", value: "medium" },
|
||||
{ label: "低", value: "low" },
|
||||
] as const).filter(option => declaredQualityOptions === undefined ||
|
||||
(declaredQualityOptions.length ? declaredQualityOptions.includes(option.value) : option.value === "auto"));
|
||||
|
||||
const clampParamsByProvider = (raw: ImageGenerationParams): ImageGenerationParams => {
|
||||
const options = getImageCountOptions();
|
||||
const fallbackCount = options[0] ?? 1;
|
||||
@ -297,7 +285,6 @@ export function ImageParamsBar({
|
||||
aspectRatio,
|
||||
imageSize,
|
||||
imageCount,
|
||||
quality: qualityOptions.some(option => option.value === raw.quality) ? raw.quality : qualityOptions[0]?.value || "auto",
|
||||
};
|
||||
};
|
||||
|
||||
@ -334,6 +321,12 @@ export function ImageParamsBar({
|
||||
...buildBaseParams(initialParams),
|
||||
});
|
||||
const [minimalParamsOpen, setMinimalParamsOpen] = useState(false);
|
||||
const qualityOptions = [
|
||||
{ label: "自动", value: "auto" },
|
||||
{ label: "高", value: "high" },
|
||||
{ label: "中", value: "medium" },
|
||||
{ label: "低", value: "low" },
|
||||
] as const;
|
||||
const qualityLabel =
|
||||
qualityOptions.find((option) => option.value === params.quality)?.label || "中";
|
||||
|
||||
|
||||
@ -1,12 +1,10 @@
|
||||
"use client";
|
||||
import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { X, Download, Edit, Target, Paintbrush, Sparkles, Scissors, Expand, Maximize2, Move3D, Droplet } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
import { buildImageProxyUrl, getImageDownloadExtension } from "@/lib/image-delivery";
|
||||
|
||||
const ImageAnnotator = dynamic(
|
||||
() => import("./image-annotator").then((module) => module.ImageAnnotator),
|
||||
@ -24,6 +22,25 @@ const AngleEditDialog = dynamic(
|
||||
}
|
||||
);
|
||||
|
||||
function triggerBrowserDownload(
|
||||
url: string,
|
||||
filename?: string,
|
||||
options?: { openInNewTab?: boolean }
|
||||
) {
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
if (filename) {
|
||||
link.download = filename;
|
||||
}
|
||||
if (options?.openInNewTab) {
|
||||
link.target = "_blank";
|
||||
}
|
||||
link.rel = "noopener noreferrer";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
export function ImagePreview({
|
||||
src,
|
||||
alt,
|
||||
@ -220,12 +237,24 @@ export function ImagePreview({
|
||||
toast.error("下载失败,请重试");
|
||||
return;
|
||||
}
|
||||
const filenameBase = `generated-image-${Date.now()}`;
|
||||
try {
|
||||
await downloadOriginalImage({ url: safeOriginalUrl });
|
||||
toast.success("原图已开始下载");
|
||||
const response = await fetch(
|
||||
buildImageProxyUrl(safeOriginalUrl, { delivery: "original" })
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`下载失败(${response.status})`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const extension = getImageDownloadExtension(blob.type);
|
||||
const filename = extension ? `${filenameBase}.${extension}` : filenameBase;
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
triggerBrowserDownload(url, filename);
|
||||
window.URL.revokeObjectURL(url);
|
||||
toast.success("下载成功");
|
||||
} catch (error) {
|
||||
console.error("下载失败:", error);
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
toast.error(error instanceof Error && error.message.includes("无法确认原图") ? error.message : "原图下载失败,请重试");
|
||||
}
|
||||
};
|
||||
|
||||
@ -277,10 +306,6 @@ export function ImagePreview({
|
||||
}
|
||||
};
|
||||
|
||||
if (isRetiredStorageUrl(src) || isRetiredStorageUrl(original)) {
|
||||
return <div role="status" className="my-2 rounded-lg border bg-muted p-4 text-sm text-muted-foreground">{RETIRED_STORAGE_MESSAGE}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 缩略图(显示压缩后的缩略图)*/}
|
||||
@ -307,18 +332,9 @@ export function ImagePreview({
|
||||
}}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onLoad={(event) => {
|
||||
event.currentTarget.style.aspectRatio = "";
|
||||
event.currentTarget.parentElement?.style.removeProperty("width");
|
||||
event.currentTarget.alt = "Generated Image";
|
||||
}}
|
||||
onError={(event) => {
|
||||
if (!normalizeLegacyAliyunStorageUrl(thumbnail || original) && event.currentTarget.src !== (thumbnail || original)) {
|
||||
if (event.currentTarget.src !== (thumbnail || original)) {
|
||||
event.currentTarget.src = thumbnail || original;
|
||||
} else if (!compactGrid) {
|
||||
event.currentTarget.style.aspectRatio = "1";
|
||||
event.currentTarget.parentElement?.style.setProperty("width", "100%");
|
||||
event.currentTarget.alt = "预览暂不可用,可尝试下载原图";
|
||||
}
|
||||
}}
|
||||
onClick={() => setIsOpen(true)}
|
||||
@ -610,7 +626,7 @@ export function ImagePreview({
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
>
|
||||
<img
|
||||
src={normalizeLegacyAliyunStorageUrl(original) ? buildImageProxyUrl(original) : original}
|
||||
src={original}
|
||||
alt="Generated Image - Original"
|
||||
className={`max-h-[90vh] max-w-full rounded-lg object-contain ${
|
||||
isAnnotationMode ? "cursor-crosshair" : ""
|
||||
|
||||
@ -7,7 +7,6 @@ import type { Vote } from "@/lib/db/schema";
|
||||
import type { ChatMessage } from "@/lib/types";
|
||||
import { cn, sanitizeText } from "@/lib/utils";
|
||||
import { extractImageUrlsFromText } from "@/lib/image-url";
|
||||
import { getGatewayErrorPageMessage } from "@/lib/request-error";
|
||||
import { useDataStream } from "./data-stream-provider";
|
||||
import { DocumentToolResult } from "./document";
|
||||
import { DocumentPreview } from "./document-preview";
|
||||
@ -522,7 +521,7 @@ const PurePreviewMessage = ({
|
||||
const displayModelName = extractedModelName || inferredFallbackModelName;
|
||||
const filteredText =
|
||||
message.role === "assistant"
|
||||
? getGatewayErrorPageMessage(contentWithoutBadge) || appendImageDoneSummary(contentWithoutBadge)
|
||||
? appendImageDoneSummary(contentWithoutBadge)
|
||||
: contentWithoutBadge;
|
||||
const useAssistantTypewriter =
|
||||
message.role === "assistant" &&
|
||||
|
||||
@ -9,7 +9,6 @@ import { Button } from "./ui/button";
|
||||
import { X, Download, Target, Paintbrush } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { ImageAnnotator } from "./image-annotator";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
export const PreviewAttachment = ({
|
||||
attachment,
|
||||
@ -74,11 +73,18 @@ export const PreviewAttachment = ({
|
||||
// 下载图片函数
|
||||
const handleDownload = async () => {
|
||||
try {
|
||||
await downloadOriginalImage({ url, name: name ?? "image" });
|
||||
toast.success("原图已开始下载");
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
const downloadUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = downloadUrl;
|
||||
link.download = name ?? `image-${Date.now()}.jpg`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(downloadUrl);
|
||||
} catch (error) {
|
||||
console.error("下载失败:", error);
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@ -1,74 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, type CSSProperties, type MouseEventHandler } from "react";
|
||||
import { buildImageProxyUrl, getFullscreenPreviewSize } from "@/lib/image-delivery";
|
||||
|
||||
export type LoadedImagePreview = { src: string; width: number; height: number };
|
||||
|
||||
/** Keep the already displayed image visible while its larger preview loads. */
|
||||
export function ProgressiveImagePreview({
|
||||
src,
|
||||
preview,
|
||||
alt,
|
||||
className,
|
||||
style,
|
||||
onClick,
|
||||
}: {
|
||||
src: string;
|
||||
preview: LoadedImagePreview;
|
||||
alt: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onClick?: MouseEventHandler<HTMLImageElement>;
|
||||
}) {
|
||||
const size = getFullscreenPreviewSize({
|
||||
imageWidth: preview.width,
|
||||
imageHeight: preview.height,
|
||||
viewportWidth: typeof window === "undefined" ? 1280 : window.innerWidth,
|
||||
viewportHeight: typeof window === "undefined" ? 900 : window.innerHeight,
|
||||
pixelRatio: typeof window === "undefined" ? 1 : window.devicePixelRatio,
|
||||
});
|
||||
const fullSrc = buildImageProxyUrl(src, {
|
||||
delivery: "proxy",
|
||||
width: size.requestWidth,
|
||||
quality: 86,
|
||||
format: "webp",
|
||||
});
|
||||
const [loadedSrc, setLoadedSrc] = useState("");
|
||||
const [failedSrc, setFailedSrc] = useState("");
|
||||
const ready = fullSrc === preview.src || loadedSrc === fullSrc;
|
||||
const failed = failedSrc === fullSrc;
|
||||
|
||||
useEffect(() => {
|
||||
if (fullSrc === preview.src) return;
|
||||
const image = new Image();
|
||||
image.decoding = "async";
|
||||
image.onload = () => setLoadedSrc(fullSrc);
|
||||
image.onerror = () => setFailedSrc(fullSrc);
|
||||
image.src = fullSrc;
|
||||
return () => {
|
||||
image.onload = null;
|
||||
image.onerror = null;
|
||||
image.removeAttribute("src");
|
||||
};
|
||||
}, [fullSrc, preview.src]);
|
||||
|
||||
return (
|
||||
<div className="relative flex items-center justify-center" onClick={(event) => event.stopPropagation()}>
|
||||
<img
|
||||
alt={alt}
|
||||
className={className}
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onClick={onClick}
|
||||
src={ready ? fullSrc : preview.src}
|
||||
style={{ width: size.displayWidth, ...style }}
|
||||
/>
|
||||
{!ready && (
|
||||
<div role="status" className="pointer-events-none absolute bottom-4 max-w-full rounded-lg bg-black/80 px-3 py-2 text-center text-sm text-white">
|
||||
{failed ? "高清预览加载失败,已保留当前预览;可关闭后重试或下载原图" : "正在加载高清预览…"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,5 +1,4 @@
|
||||
"use client";
|
||||
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||
|
||||
import {
|
||||
ArrowLeft,
|
||||
@ -2074,9 +2073,18 @@ export function SceneFusionView({
|
||||
|
||||
const downloadImage = async (url: string, filename: string) => {
|
||||
try {
|
||||
await downloadOriginalImage({ url, name: filename });
|
||||
} catch (error) {
|
||||
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = blobUrl;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
|
||||
} catch {
|
||||
window.open(url, "_blank");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@ -29,10 +29,10 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content> & { overlayClassName?: string }
|
||||
>(({ className, overlayClassName, ...props }, ref) => (
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay className={overlayClassName} />
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
|
||||
@ -92,16 +92,8 @@ public 先从当前运行版本创建写入时复制副本,保留未纳入 Git
|
||||
|
||||
原生产 checkout 的支线及未提交改动仍保留,不能据其 Git HEAD 判断已发布版本。
|
||||
实际发布证据是:运行 cwd、`.next/BUILD_ID`、该目录 `release.json` 和 `activation.json`。
|
||||
`next.config.ts` 将本流程的发布目录编号写入前后端版本标识;`/api/app-version` 返回该编号且不缓存,发布烟测会核对它与运行目录一致。网页每分钟及切回页面时检查更新,发现版本变化后提示同步并刷新;画布同步失败或当前任务仍在处理时保留页面。首次接入前已经打开的旧网页需先刷新一次,后续发布即可自动收到提示。
|
||||
维护电脑的 `.git/releases/<发布ID>/` 保留提交、构建日志、烟测、传输校验和及操作回执。
|
||||
服务器回滚配置可能含环境元数据,目录权限为 0700、文件为 0600,不放入公开目录或 Git。
|
||||
|
||||
仓库历史全量 lint 仍有已记录的问题,不能声称全部质量门禁通过。
|
||||
每次 PR 须记录本次改动的验证、历史失败和未覆盖项目;当前流程不会自动触发生产发布。
|
||||
|
||||
## ZIP 下载交付
|
||||
|
||||
默认存储为七牛时,完整 ZIP 通过分片上传至七牛,确认下载地址可用后才提供下载。
|
||||
大文件使用三个并发分片,上传进度显示在原打包任务中。传送或链接检查失败会返回具体阶段、
|
||||
下载编号及重试建议,保留已生成的 ZIP;再次点击下载复用原文件,已上传的完整对象不重复上传。
|
||||
后台 ZIP 任务参与发布期间的工作等待。完成或失败的任务及文件保留 24 小时,待处理任务保留 6 小时。
|
||||
|
||||
@ -1,33 +0,0 @@
|
||||
# 旧存储停用与七牛上传核查
|
||||
|
||||
## s3.1080p.hk
|
||||
|
||||
该存储已永久停用,文件不可恢复。它与 2026 年 10 月 14 日迁入七牛的阿里云 OSS 资源不是同一套存储。
|
||||
|
||||
- 首页精选只展示原文件仍在有效存储上的记录,统计和分页按同一条件计算。
|
||||
- 历史生成记录、聊天、画布节点保留。旧图片显示永久失效说明,不再发起下载、归档或上传到旧桶。
|
||||
- 单图下载和代理返回 HTTP 410 / `storage_retired`;批量下载将对应文件记为失败,不重试旧源。
|
||||
- 其他存储的临时加载失败仍展示错误卡片和重试入口。
|
||||
- 黑色 Logo 为 `public/brand/logo-black.png`;白色版使用 SVG 色彩滤镜保留同一 PNG 的透明度和轮廓。两者随应用发布,不依赖对象存储。
|
||||
|
||||
一次性配置整理:在生产运行目录执行 `node scripts/storage/retire-1080p-storage.cjs` 预览,增加 `--apply` 停用旧配置、取消失效图片的精选标记并更新 Logo。执行前将原字段保存至 `/var/lib/ai-chatbot/retired-storage-20261103/`。该操作不删除图片记录或对象文件。
|
||||
|
||||
2026-11-03 核查:旧源生成记录 67,267 条;精选 65 条中 59 条来自旧源;旧源图片归档任务为 0。默认上传存储为七牛 `gongxiangpan-sc`。
|
||||
|
||||
## 2026-10-14 上传峰值
|
||||
|
||||
统计时区 UTC+8,GB 按十进制计算。数据来自七牛只读上传统计、对象清单和生产机迁移记录。
|
||||
|
||||
| 范围 | 对象数 | 字节数 | GB |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 七牛当天上传流量 | — | 825,113,404,030 | 825.11 |
|
||||
| 当天写入且仍存在的 `legacy-oss/demo-sparkai/` | 409,821 | 812,788,883,061 | 812.79 |
|
||||
| 当天写入且仍存在的 `legacy-s3/gongxiangpan/` | 539 | 865,360,590 | 0.87 |
|
||||
| 当天写入且仍存在的其他目录 | 3,382 | 9,735,597,543 | 9.74 |
|
||||
| 上传流量与当天现存对象大小差额 | — | 1,723,562,836 | 1.72 |
|
||||
|
||||
813.65 GB 位于本项目历史迁移目录。主要写入发生在 19:00–21:00。源分别为 `demo-sparkai.oss-cn-shanghai.aliyuncs.com` 和 `s3.jiansun.vip/gongxiangpan`,符合仓库迁移脚本的目标路径。
|
||||
|
||||
生产机 `/var/lib/ai-chatbot/aliyun-qiniu-20261014/verified.jsonl` 有 349,784 个去重后的目标对象、629,920,510,316 字节(629.92 GB)的逐对象验证记录。当前迁移目录比该回执多 60,576 个对象、183.73 GB;目录归属能够确认,现有回执没有覆盖这些对象。
|
||||
|
||||
桶由多个业务共用。其他目录中 `uploads/` 为 7.97 GB,其余包含 `dabi/`、`exports/`、`accio-ghost/` 和 `shared-drive/`,不能全部归为画布新生成资源。上传统计包含传输量,对象清单反映现存对象,不足以单独解释最后 1.72 GB 的差额。本次未删除或改动七牛对象。
|
||||
@ -1,175 +0,0 @@
|
||||
# 生效模型参数核对(2026-11-16)
|
||||
|
||||
核对对象为模型和所属上游同时启用的 76 条配置,包括隐藏但仍可被功能调用的模型。依据生产配置快照、实际请求构建代码、98K 当前账户公布的接口契约以及阿里云、AtlasCloud、Anthropic 官方资料。
|
||||
|
||||
## 修复范围
|
||||
|
||||
| 问题 | 影响与处理 |
|
||||
| --- | --- |
|
||||
| 图片尺寸与比例 | 删除仅允许正方形的错误约束;有独立比例与清晰度字段时按上游契约组合,固定 2K/4K 模型使用对应档位。 |
|
||||
| 请求路线 | 显式选定的标准接口优先于通用任务示例,保留路线与参数约束的对应关系。 |
|
||||
| 参考图数量 | 读取嵌套约束并采用当前实际调用接口的上限,GPT Image 2 的上限由 16 校正为 14。 |
|
||||
| 图片质量与负面提示词 | 质量和负面提示词只写入一个有效位置;固定质量模型不再发送旧的其他档位,页面只提供接口接受的质量选项。 |
|
||||
| 可选生成控制 | 修复水印、提示词扩展、随机种子、尾帧和固定镜头的已支持字段漏传,保留 false 和 0 的原值;上游未声明的字段不发送。 |
|
||||
| 视频时长 | Veo 使用当前接口的 duration 字段;Minimax 的 1080p 时长选项限制在接口允许范围内。 |
|
||||
| 文字输出长度 | AI SDK 调用统一使用 maxOutputTokens,原生厂商接口保留各自标准字段。 |
|
||||
| Claude 采样参数 | 对固定采样协议移除 temperature、top_p、top_k,保留工具调用和输出长度。Haiku 5.5 已实测。 |
|
||||
| 世界生成分类 | world-generation 的类型及任务调用配置按现有世界生成接口校正,避免作为聊天模型使用。 |
|
||||
| 聊天生图备用模型 | 按原请求的清晰度、比例、张数和参考图数量筛选,不把 1K/4K 请求传给固定 2K 模型;额度不足时跳过同一账户的其他模型。 |
|
||||
| 额度错误与请求追踪 | 98K 的英文可用额度不足归类为服务商余额/额度问题,保留上游请求号并关联网页请求号。 |
|
||||
|
||||
## 验证
|
||||
|
||||
- 图片、视频、音频及工具参数组成 12,135 个离线请求用例,采用实际请求构建函数,并核对当前接口约束与字段值。
|
||||
- 阿里云图片另外覆盖 80 个尺寸、数量、参考图、随机种子和开关组合;7 个 AtlasCloud 三维模型按各自 OpenAPI 请求规范核对。
|
||||
- 19 个聊天/文字模型捕获官方 SDK 生成的请求,覆盖输出长度、采样、停止词以及适用的图片和工具调用。13 个 98K 模型同时通过当前路线契约校验;其余 6 个根据接入代码和 SDK 请求核对。
|
||||
- 自动回归 118 项通过,TypeScript 检查通过。
|
||||
- 聊天回退与失败提示另通过 49 项针对性回归,覆盖固定清晰度、比例、张数、参考图上限、同账户额度隔离、未知结果不重提,以及网页提示和历史记录一致。
|
||||
- 独立实测:Nano Banana 2 带参考图生成 16:9 图片,返回 1376×768 PNG;固定 4K 编辑返回 4096×4096 JPEG;Claude Haiku 5.5 返回有效工具调用。两张图片均完成七牛保存和下载验证。每项只有一次提交。
|
||||
|
||||
## 生效模型清单
|
||||
|
||||
| 模型 | 上游 | 本次核对 |
|
||||
| --- | --- | --- |
|
||||
| `grok-4.7` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `gpt-image-2` | 98K | 126 组请求字段与接口约束 |
|
||||
| `gpt-image-2-vip` | 98K | 360 组请求字段与接口约束 |
|
||||
| `nano-banana-2` | 98K | 90 组请求字段与接口约束 |
|
||||
| `nano-banana-pro` | 98K | 90 组请求字段与接口约束 |
|
||||
| `gpt-image-2.5` | 98K | 30 组请求字段与接口约束 |
|
||||
| `gpt-image-2.5-flare` | 98K | 288 组请求字段与接口约束 |
|
||||
| `ocr` | 98K | 3 组请求字段与接口约束 |
|
||||
| `gpt-image-2.5-sunburst` | 98K | 504 组请求字段与接口约束 |
|
||||
| `nano-banana-2-2k-cl` | 98K | 12 组请求字段与接口约束 |
|
||||
| `nano-banana-2-4k-cl` | 98K | 12 组请求字段与接口约束 |
|
||||
| `nano-banana-2-cl` | 98K | 12 组请求字段与接口约束 |
|
||||
| `nano-banana-pro-4k-vip` | 98K | 12 组请求字段与接口约束 |
|
||||
| `nano-banana-pro-cl` | 98K | 12 组请求字段与接口约束 |
|
||||
| `nano-banana-pro-vip` | 98K | 12 组请求字段与接口约束 |
|
||||
| `doubao-seedream-5-0-pro` | 98K | 240 组请求字段与接口约束 |
|
||||
| `flux-2-pro` | 98K | 48 组请求字段与接口约束 |
|
||||
| `gpt-image-2.6` | 98K | 84 组请求字段与接口约束 |
|
||||
| `gpt-image-2.6-flare` | 98K | 360 组请求字段与接口约束 |
|
||||
| `gpt-image-2.6-sunburst` | 98K | 36 组请求字段与接口约束 |
|
||||
| `nano-banana-2-plus` | 98K | 360 组请求字段与接口约束 |
|
||||
| `nano-banana-pro-plus` | 98K | 360 组请求字段与接口约束 |
|
||||
| `qwen-image-3.0` | 98K | 48 组请求字段与接口约束 |
|
||||
| `qwen-image-3.0-pro` | 98K | 48 组请求字段与接口约束 |
|
||||
| `minimax-h3` | 98K | 320 组请求字段与接口约束 |
|
||||
| `veo-3.1-fast` | 98K | 16 组请求字段与接口约束 |
|
||||
| `seedance-2.5` | 98K | 1296 组请求字段与接口约束 |
|
||||
| `seedance-2.5-image-to-video` | 98K | 1458 组请求字段与接口约束 |
|
||||
| `seedance-2.5-reference-to-video` | 98K | 1458 组请求字段与接口约束 |
|
||||
| `seedance-2.5-text-to-video` | 98K | 1134 组请求字段与接口约束 |
|
||||
| `gemini-omni-1.1-flash-preview` | 98K | 8 组请求字段与接口约束 |
|
||||
| `grok-imagine-video` | 98K | 2500 组请求字段与接口约束 |
|
||||
| `grok-imagine-video-1.5` | 98K | 750 组请求字段与接口约束 |
|
||||
| `gemini-3.8-flash` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `gpt-6-astra` | 98K | SDK 请求、输出长度、采样、停止词 |
|
||||
| `gpt-6-sol` | 98K | SDK 请求、输出长度、采样、停止词 |
|
||||
| `gpt-6.1-sol` | 98K | SDK 请求、输出长度、采样、停止词 |
|
||||
| `world-generation` | 98K | 世界生成类型、任务提交与结果查询配置 |
|
||||
| `claude-haiku-5-5` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `claude-sonnet-4-6` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `image-expansion` | 98K | 3 组请求字段与接口约束 |
|
||||
| `gem-3.1-tts` | 98K | 4 组请求字段与接口约束 |
|
||||
| `mimo-v2.5-asr` | 98K | 1 组请求字段与接口约束 |
|
||||
| `mimo-v2.5-tts` | 98K | 1 组请求字段与接口约束 |
|
||||
| `mimo-v2.5-tts-voiceclone` | 98K | 1 组请求字段与接口约束 |
|
||||
| `mimo-v2.5-tts-voicedesign` | 98K | 1 组请求字段与接口约束 |
|
||||
| `music-2.5` | 98K | 3 组请求字段与接口约束 |
|
||||
| `music-2.5+` | 98K | 3 组请求字段与接口约束 |
|
||||
| `speech-2.8-hd` | 98K | 6 组请求字段与接口约束 |
|
||||
| `speech-2.8-turbo` | 98K | 6 组请求字段与接口约束 |
|
||||
| `suno-v4.5` | 98K | 3 组请求字段与接口约束 |
|
||||
| `suno-v6` | 98K | 3 组请求字段与接口约束 |
|
||||
| `suno-v5` | 98K | 3 组请求字段与接口约束 |
|
||||
| `suno-v5-5` | 98K | 3 组请求字段与接口约束 |
|
||||
| `claude-fable-5-1` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `claude-opus-5-5` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `claude-sonnet-5-5` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `gemini-4-argon` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `grok-4.5` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `grok-4.6` | 98K | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `tripo-h3.1/image-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `tripo-h3.1/text-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `tencent/hunyuan3d-pro/text-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `tencent/hunyuan3d-pro/image-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `tencent/hunyuan3d-rapid/text-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `tencent/hunyuan3d-rapid/image-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `bytedance/seed3d-v2.0/image-to-3d` | AtlasCloud | 提示词/参考图、三维输出参数及官方 OpenAPI |
|
||||
| `qwen-image-3.0` | 阿里云图片 | 80 组图片参数及原生请求字段 |
|
||||
| `qwen3-vl-plus` | 阿里云 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `qwen3.8-max` | 阿里云 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `qwen3.8-omni-flash` | 阿里云 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `qwen3-tts-instruct-flash` | 阿里云 | 官方语音请求、音色、语言与指令 |
|
||||
| `qwen3-tts-flash` | 阿里云 | 官方语音请求、音色、语言与指令 |
|
||||
| `deepseek-flash` | 自定义标准接口 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `agnes-1.5-flash` | 自定义标准接口 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
| `agnes-2.0-flash` | 自定义标准接口 | SDK 请求、输出长度、采样、停止词、视觉及工具调用 |
|
||||
|
||||
## 线上核对
|
||||
|
||||
11 月 16 日 15:14–15:23(新加坡时间)98K 只读核查确认账户可用余额不足以预留生成费用,相关拒绝未派发上游;相同的额度错误及备用模型规格不匹配在本轮发布激活前已出现,与网页是否刷新无关。15:43 确认充值到账,“风骚”账号 15:34–15:44 已有 6 笔成功新图片记录,包含 1K 和 4K 请求;历史失败请求未重放。
|
||||
|
||||
32 条模型参数配置已更新并回读核对。聊天回退与额度提示修复已上线,公开入口与正式进程版本一致;切换在旧进程工作归零后完成,未修改历史任务状态。
|
||||
|
||||
场景融合的无效视频首选项已清除,恢复为“不指定首选”,与原先实际采用的图片候选池一致;其余设置保持不变。该配置即时生效,无需重启服务。
|
||||
|
||||
## 当日需求收尾
|
||||
|
||||
| 需求 | 核对结果 |
|
||||
| --- | --- |
|
||||
| 下载慢与图片归档 | 原图七牛直连、准备及转换状态、取消自动转传回生产机的修复已上线。16:21 归档完成数持续增加,队列中的新图片正在保存或更新画布引用,没有新的失败记录。 |
|
||||
| 旧 BananaImage 入口 | 旧供应商与五个旧模型已停用、隐藏;98K 对应入口保留。线上回读与网页列表一致。 |
|
||||
| 后台历史缺图 | 11 月 13 日有 108 张涉及 24 位用户的原图未成功归档;上游文件 404、七牛及本地缓存无副本。Relay 隔离核验三个备份后找回 10 张的原请求号,其余 98 张没有匹配的保留响应,原文件恢复数为 0;未重新生成。 |
|
||||
| 98K 缺失模型接入 | 本次原定的 48 个型号已开放 40 个:对话 5、图片 15、视频 7、语音及音乐 13。剩余 8 个仍受上游型号授权或能力限制。 |
|
||||
| 六款 CL/VIP 参考图编辑 | 六款已完成独立参考图生成、尺寸及七牛保存验证并上线;网页已核对六款均可选择,已移除“仅文生图”标记。 |
|
||||
| “风骚”首次规格错误 | 4K 尺寸映射修复已上线,独立参考图结果为 4096×4096;网页选择固定 4K 型号时自动切换到 4K,参数面板只提供该型号支持的选项。 |
|
||||
| 全部生效模型参数核对 | 已覆盖当时生效的 76 条模型记录,修复与配置调整已上线,包含分辨率、比例、数量、参考图、质量、采样、视频时长等字段。 |
|
||||
| “风骚”再次报错 | 已确认额度不足引发不兼容备用模型回退,非旧网页引起;额度识别、同供应商回退阻止及规格筛选已上线。充值后该账号已有新的成功结果,旧请求未重放。 |
|
||||
|
||||
### 网页操作验收
|
||||
|
||||
- 在独立图片测试画布核对模型列表及固定 4K 参数。测试画布:`97aca1be-6bdb-485e-945e-00cc21691d84`。
|
||||
- 在独立音频测试画布选择 `mimo-v2.5-tts`,提交中文短句一次,19.42 秒完成;WAV 文件保存至七牛,网页显示约 4 秒并播放到结尾。任务记录为成功、尝试一次。测试画布:`8b76a09a-f24f-42ff-9f1e-f3809909dd84`。
|
||||
- 上述测试不等于 40 个新型号的每一种网页流程均完成验收;参考图、视频和其他音频型号的实际调用及存储验证沿用已有独立测试记录。
|
||||
|
||||
17:46 起在 Codex 内置浏览器补充验收,所有操作均在独立测试画布完成:语音识别 6.88 秒返回文字,声音克隆 93.27 秒、声音设计 15.07 秒返回已存入七牛的 WAV,均只提交一次。识别文字存在同音字误差,需要人工校对。
|
||||
|
||||
本轮修复语音识别成功后画布结果为空的问题:新结果采用画布文本结构,已保存的字符串结果也可直接显示和编辑;重复查询不会覆盖人工修改。音频生成节点显示排队、处理中及失败信息,不再以空播放器及默认三秒时长表示未完成任务。相关回归 72 项和 TypeScript 检查通过;内置浏览器独立页面已验证新旧文字显示、中文与尺寸编辑、空格保留及等待/失败状态,修复已上线。
|
||||
|
||||
画布恢复时统一读取字符串和数组格式的文本,保留中文、尺寸及空格;人工编辑和主动清空按画布保存内容显示。恢复与任务相关回归 46 项、TypeScript 检查及内置浏览器的实际恢复组件验收通过。18:53(新加坡时间)在原测试画布完成正式网页验收:旧文字正常读取,中文和 `15mm` 修改保存后刷新仍保留,主动清空保存后刷新保持空白,末尾空格正常保留。
|
||||
|
||||
音乐原任务已成功完成并保存七牛,网页解码时长约 150 秒并可播放。供应商核对确认只受理及扣费一次;本项目工作进程续查一次原任务,没有重新派发。声音克隆与声音设计在内置浏览器均播放到结尾。
|
||||
|
||||
正式运行版本为 `20261116T103955Z-582667dd05a1`,源码提交 `582667dd05a1a629850937aa46b506897998576d`,构建编号 `9nLxMnP463njtm-3FO694`;生产进程目录、构建编号、公开版本接口与发布回执一致。发布等待后台工作结束后再停止旧进程,历史挂起任务记录保持不变。原测试画布仍为五笔成功任务,没有新增生成请求。18:50 复核当日图片归档均已完成,没有等待归档或下载准备积压。
|
||||
|
||||
验收截图:`.qa/production-audio-acceptance.png`。临时本地验收服务已结束,测试画布保留供复核。
|
||||
|
||||
### 剩余上游事项
|
||||
|
||||
| 型号 | 当前阻塞 | 处理方 |
|
||||
| --- | --- | --- |
|
||||
| `gemini-3-pro-image-preview-vip`、`gemini-3.1-flash-image-preview-vip`、`gemini-nano-banana-2.1-vip`、`nano_banana`、`nano_banana_2`、`nano_banana_pro` | 实际账户目录未提供精确型号,原请求返回无执行权限 | ToAPIs 开通对应账户分组型号 |
|
||||
| `gpt-6.1-terra` | 标准工具字段已传递,原响应没有工具调用 | ToAPIs 确认该线路工具调用能力 |
|
||||
| `gem-2.5-tts` | 原异步任务终态服务不可用,已退款并释放预留 | ZZY 恢复该音频服务 |
|
||||
|
||||
以上 8 个仍未开放。Relay 于 16:25 回读确认尚无恢复证据,本轮未新增已知失败的付费探测。
|
||||
|
||||
### 历史原图恢复
|
||||
|
||||
Relay 已只读核验 11 月 13 日 15:13、16:00 以及 11 月 16 日 12:03 的独立备份。10 张可匹配原请求的图片均由 Grsai 同步返回,备份只保留已失效的图片链接,没有原文件或可查询的上游任务号;需要供应商按原型号、受理时间和账号查找原交付记录。其余 98 张没有可匹配的保留响应。此核验未覆盖生产数据、未重新生成图片或产生新的生成扣费。
|
||||
|
||||
## 已知问题与验证边界
|
||||
|
||||
- 生产机可用磁盘约 1.09 GiB,接近发布与批量打包下载的保留线。本轮已回收一个未启用候选副本及一个更早退役版本的构建产物;构建机完整包和源码、当前与最近回滚版本、业务数据均保留。
|
||||
|
||||
- 离线参数核对不等于 76 个模型逐个完成付费生成,也不证明上游持续可用、效果或速度;实际生成验证范围为上述三项。
|
||||
- 自动选模时页面尚未确定最终模型,接入层仍须依据实际选中接口规范化固定参数。模型清单和接口约束会随上游调整,本报告对应本次核对时点。
|
||||
|
||||
## 资料
|
||||
|
||||
- [Anthropic Haiku 5.5 采样参数迁移说明](https://platform.claude.com/docs/en/models/haiku-5-5/migration-guide#remove-sampling-parameters)
|
||||
- [阿里云图片生成及编辑接口](https://www.alibabacloud.com/help/en/model-studio/qwen-image-generation-and-editing-api-reference)
|
||||
- [阿里云语音合成接口](https://www.alibabacloud.com/help/en/model-studio/qwen-tts-api)
|
||||
@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { BEFORE_PAGE_REFRESH, type PageRefreshRequest } from "@/lib/client/page-refresh";
|
||||
import { mergeCanvasSnapshots, type CanvasConflictChoice } from "@/lib/video-canvas/merge-snapshot";
|
||||
import {
|
||||
CanvasRevisionConflict,
|
||||
@ -150,16 +149,6 @@ export function useVideoCanvasPersistence(
|
||||
return !queue.dirty && !queue.failed;
|
||||
}, [ready]);
|
||||
|
||||
useEffect(() => {
|
||||
const beforeRefresh = (event: Event) => {
|
||||
(event as CustomEvent<PageRefreshRequest>).detail.save(async () => {
|
||||
if (!(await saveAndConfirm())) throw new Error("视频画布尚未同步完成,本地草稿已保留,请重试刷新。");
|
||||
});
|
||||
};
|
||||
window.addEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
return () => window.removeEventListener(BEFORE_PAGE_REFRESH, beforeRefresh);
|
||||
}, [saveAndConfirm]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") {
|
||||
|
||||
@ -1,83 +0,0 @@
|
||||
import { sql, type SQL } from "drizzle-orm";
|
||||
|
||||
export function parseMediaQuery(params: URLSearchParams) {
|
||||
const integer = (key: string, fallback: number, max: number) => {
|
||||
const value = Number(params.get(key));
|
||||
return Number.isInteger(value) && value > 0 ? Math.min(value, max) : fallback;
|
||||
};
|
||||
const date = (key: string) => {
|
||||
const value = params.get(key) || "";
|
||||
return /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) ? value : "";
|
||||
};
|
||||
return {
|
||||
page: integer("page", 1, 100000),
|
||||
pageSize: integer("pageSize", 40, 100),
|
||||
search: (params.get("search") || "").trim().slice(0, 128),
|
||||
type: ["image", "video"].includes(params.get("type") || "") ? params.get("type")! : "all",
|
||||
model: params.get("model") || "",
|
||||
featured: params.get("featured") === "true",
|
||||
startDate: date("startDate"),
|
||||
endDate: date("endDate"),
|
||||
};
|
||||
}
|
||||
|
||||
export function mediaRecordsQuery(params: ReturnType<typeof parseMediaQuery>) {
|
||||
const conditions: SQL[] = [sql`true`];
|
||||
if (params.search)
|
||||
conditions.push(
|
||||
sql`exists (select 1 from "User" u where u.id=m."userId" and (u.name ilike ${`%${params.search}%`} or u.email ilike ${`%${params.search}%`}))`,
|
||||
);
|
||||
if (params.startDate) conditions.push(sql`m."createdAt" >= ${params.startDate}::date`);
|
||||
if (params.endDate)
|
||||
conditions.push(sql`m."createdAt" < ${params.endDate}::date + interval '1 day'`);
|
||||
if (params.model) conditions.push(sql`(m."modelId" = ${params.model} or m."modelId" in (select id::text from "AiModel" where "modelId"=${params.model}))`);
|
||||
const where = sql.join(conditions, sql` and `);
|
||||
const videoFilters: SQL[] = [sql`true`];
|
||||
if (params.startDate)
|
||||
videoFilters.push(sql`v."createdAt">=${params.startDate}::date - interval '8 hours'`);
|
||||
if (params.endDate)
|
||||
videoFilters.push(sql`v."createdAt"<${params.endDate}::date+interval '16 hours'`);
|
||||
if (params.model) videoFilters.push(sql`(v."video_metadata"->>'model'=${params.model} or v."video_metadata"->>'model' in (select id::text from "AiModel" where "modelId"=${params.model}))`);
|
||||
if (params.search)
|
||||
videoFilters.push(
|
||||
sql`exists (select 1 from "User" u where u.id=c."userId" and (u.name ilike ${`%${params.search}%`} or u.email ilike ${`%${params.search}%`}))`,
|
||||
);
|
||||
return sql`
|
||||
with video_candidates as materialized (
|
||||
select v.id, v."chatId", v."createdAt" + interval '8 hours' as "createdAt", v."video_metadata", c."userId",
|
||||
coalesce(nullif(v."permanent_video_url", ''), nullif(v."temporary_video_url", ''),
|
||||
(regexp_match(t.body, '<video[^>]+src="([^"]+)"', 'i'))[1],
|
||||
(regexp_match(t.body, '(https?://[^[:space:]"<>]+\\.mp4[^[:space:]"<>)]*)', 'i'))[1]) as url
|
||||
from "Message_v2" v join "Chat" c on c.id=v."chatId"
|
||||
cross join lateral (select case when jsonb_typeof(v.parts::jsonb)='array'
|
||||
then (select string_agg(p->>'text', E'\\n') from jsonb_array_elements(v.parts::jsonb) p)
|
||||
else v.parts::jsonb #>> '{}' end as body) t
|
||||
where ${params.type !== "image" && !params.featured} and v.role='assistant'
|
||||
and ${sql.join(videoFilters, sql` and `)}
|
||||
and (v."permanent_video_url" is not null or v."temporary_video_url" is not null or v.parts::text ilike '%<video%' or v.parts::text ilike '%.mp4%')
|
||||
), media as not materialized (
|
||||
select g.id, 'image'::text as kind, g."createdAt", g."userId", g."modelId", null::text as url
|
||||
from "GeneratedImage" g where ${params.type !== "video"} and (${!params.featured} or g."isFeatured")
|
||||
union all
|
||||
select id, 'video', "createdAt", "userId", "video_metadata"->>'model', url
|
||||
from video_candidates where url is not null
|
||||
), filtered as not materialized (select * from media m where ${where}),
|
||||
totals as (select count(*)::int as total, count(*) filter(where kind='image')::int as images, count(*) filter(where kind='video')::int as videos from filtered),
|
||||
page_rows as (
|
||||
select * from filtered order by "createdAt" desc, kind, id desc
|
||||
limit ${params.pageSize} offset ${(params.page - 1) * params.pageSize}
|
||||
)
|
||||
select t.total, t.images as "totalImages", t.videos as "totalVideos",
|
||||
coalesce((select jsonb_agg(jsonb_build_object(
|
||||
'id', case when p.kind='video' then 'video-'||p.id::text else p.id::text end,
|
||||
'recordType',p.kind,'userId',p."userId",'userName',u.name,'userEmail',u.email,'userDepartment',u.department,
|
||||
'createdAt',p."createdAt",'modelId',p."modelId",'chatId',coalesce(g."chatId",v."chatId"),
|
||||
'thumbnailUrl',coalesce(p.url,g."thumbnailUrl"),'originalUrl',coalesce(p.url,g."originalUrl"),'videoUrl',p.url,
|
||||
'prompt',coalesce(g.prompt,v."video_metadata"->>'prompt'),'imageSize',coalesce(g."imageSize",v."video_metadata"->>'resolution'),
|
||||
'isFeatured',coalesce(g."isFeatured",false),'featuredCategory',g."featuredCategory",'featuredAt',g."featuredAt" + interval '8 hours'
|
||||
) order by p."createdAt" desc,p.kind,p.id desc)
|
||||
from page_rows p left join "User" u on u.id=p."userId"
|
||||
left join "GeneratedImage" g on p.kind='image' and g.id=p.id
|
||||
left join "Message_v2" v on p.kind='video' and v.id=p.id),'[]'::jsonb) as records
|
||||
from totals t`;
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
// One queue for the records screen: visible previews get four network slots.
|
||||
const waiting: Array<() => void> = [];
|
||||
let active = 0;
|
||||
function pump() {
|
||||
while (active < 4 && waiting.length) waiting.shift()?.();
|
||||
}
|
||||
export function queuePreview(start: (release: () => void) => void) {
|
||||
let released = false;
|
||||
let started = false;
|
||||
const release = () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
if (started) active--;
|
||||
else {
|
||||
const index = waiting.indexOf(run);
|
||||
if (index >= 0) waiting.splice(index, 1);
|
||||
}
|
||||
pump();
|
||||
};
|
||||
const run = () => {
|
||||
started = true;
|
||||
active++;
|
||||
start(release);
|
||||
};
|
||||
waiting.push(run);
|
||||
pump();
|
||||
// Active fetches release their slot in finally, after abort has settled.
|
||||
return () => {
|
||||
if (!started) release();
|
||||
};
|
||||
}
|
||||
@ -1,7 +0,0 @@
|
||||
export function formatRecordTime(value: string) {
|
||||
// The admin API normalizes each storage convention to Beijing wall-clock time.
|
||||
return value
|
||||
.replace("T", " ")
|
||||
.replace(/(?:\.\d+)?Z$/, "")
|
||||
.slice(0, 16);
|
||||
}
|
||||
@ -14,8 +14,6 @@ import {
|
||||
sanitizeAgentDetailBrief,
|
||||
} from "@/lib/agents/detail-generation-config";
|
||||
|
||||
export const MAX_DETAIL_REPLACEMENT_REFERENCES = 64;
|
||||
|
||||
export function createEmptyAgentModeWorkspaceState(): AgentModeWorkspaceState {
|
||||
return {
|
||||
detailReplacement: {
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
import { extractImageUrlsFromText } from "@/lib/image-url";
|
||||
import { messageText } from "./replacement-run-recovery";
|
||||
|
||||
type Message = { id: string; role: string; parts?: unknown[] };
|
||||
|
||||
export function getSceneRunResult(messages: Message[], requestMessageId: string) {
|
||||
const index = messages.findIndex((message) => message.id === requestMessageId && message.role === "user");
|
||||
if (index < 0) return null;
|
||||
const replies = messages.slice(index + 1);
|
||||
// A later user turn belongs to another run.
|
||||
if (replies.some((message) => message.role === "user")) return null;
|
||||
const urls = new Set(replies.filter((message) => message.role === "assistant")
|
||||
.flatMap((message) => extractImageUrlsFromText(messageText(message))));
|
||||
return { count: urls.size };
|
||||
}
|
||||
@ -185,7 +185,7 @@ async function optimizeWithConfiguredQwenVisionModel(params: {
|
||||
},
|
||||
],
|
||||
temperature: 0,
|
||||
maxOutputTokens: 320,
|
||||
maxTokens: 320,
|
||||
abortSignal: AbortSignal.timeout(30_000),
|
||||
} as any);
|
||||
|
||||
|
||||
@ -407,32 +407,6 @@ function buildPromptSection(title: string, lines: string[]) {
|
||||
return `【${title}】\n${normalizedLines.join("\n")}`;
|
||||
}
|
||||
|
||||
export function resolveAgentWorkflowComposerSelections(params: {
|
||||
config?: AgentWorkflowUiConfig | null;
|
||||
selections: Partial<Record<AgentWorkflowStepKey, string>>;
|
||||
}): AgentWorkflowComposerContext["selections"] {
|
||||
const config = params.config || defaultAgentWorkflowUiConfig;
|
||||
const steps = flattenVisibleAgentWorkflowSteps(
|
||||
getEnabledAgentWorkflowStepTree(Array.isArray(config.steps) ? config.steps : []),
|
||||
params.selections
|
||||
)
|
||||
.map(({ step }) => step)
|
||||
.filter((step) => Array.isArray(step.options) && step.options.length > 0);
|
||||
return steps.flatMap((step) => {
|
||||
const selectedOptions = getAgentWorkflowSelectedOptionPath({
|
||||
step,
|
||||
selectionValue: params.selections[step.key],
|
||||
});
|
||||
return selectedOptions.map((option) => ({
|
||||
stepKey: step.key,
|
||||
stepTitle: step.title,
|
||||
optionKey: option.key,
|
||||
optionName: option.buttonName,
|
||||
promptFragment: option.promptFragment || option.buttonName,
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
export function buildAgentWorkflowComposerContext(params: {
|
||||
config?: AgentWorkflowUiConfig | null;
|
||||
inputs: AgentWorkflowInputsValue;
|
||||
@ -440,9 +414,30 @@ export function buildAgentWorkflowComposerContext(params: {
|
||||
selectedBrandModel?: AgentWorkflowSelectedBrandModel | null;
|
||||
appearanceRecognitionEnabled?: boolean;
|
||||
selections: Partial<Record<AgentWorkflowStepKey, string>>;
|
||||
resolvedSelections?: AgentWorkflowComposerContext["selections"];
|
||||
}): AgentWorkflowComposerContext | null {
|
||||
const selections = params.resolvedSelections ?? resolveAgentWorkflowComposerSelections(params);
|
||||
const config = params.config || defaultAgentWorkflowUiConfig;
|
||||
const steps = flattenVisibleAgentWorkflowSteps(
|
||||
getEnabledAgentWorkflowStepTree(Array.isArray(config.steps) ? config.steps : []),
|
||||
params.selections
|
||||
)
|
||||
.map(({ step }) => step)
|
||||
.filter((step) => Array.isArray(step.options) && step.options.length > 0);
|
||||
const selections = steps
|
||||
.map((step) => {
|
||||
const selectedOptions = getAgentWorkflowSelectedOptionPath({
|
||||
step,
|
||||
selectionValue: params.selections[step.key],
|
||||
});
|
||||
if (selectedOptions.length === 0) return [];
|
||||
return selectedOptions.map((option) => ({
|
||||
stepKey: step.key,
|
||||
stepTitle: step.title,
|
||||
optionKey: option.key,
|
||||
optionName: option.buttonName,
|
||||
promptFragment: option.promptFragment || option.buttonName,
|
||||
}));
|
||||
})
|
||||
.flat() as AgentWorkflowComposerContext["selections"];
|
||||
const referenceImages = getSelectedWorkflowReferenceImages({
|
||||
inputs: params.inputs,
|
||||
materials: params.materials,
|
||||
|
||||
@ -1,18 +0,0 @@
|
||||
import type { AgentWorkflowOptionUiConfig, AgentWorkflowStepUiConfig } from "@/types/agent";
|
||||
|
||||
export function omitAgentWorkflowPrompts(steps: AgentWorkflowStepUiConfig[]): AgentWorkflowStepUiConfig[] {
|
||||
const omitOptionPrompt = ({ promptFragment: _prompt, children, ...option }: AgentWorkflowOptionUiConfig): AgentWorkflowOptionUiConfig => ({
|
||||
...option,
|
||||
...(children?.length ? { children: children.map(omitOptionPrompt) } : {}),
|
||||
});
|
||||
return steps.map(({ options, children, ...step }) => ({
|
||||
...step,
|
||||
options: options.map(omitOptionPrompt),
|
||||
...(children?.length ? { children: omitAgentWorkflowPrompts(children) } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export function getWorkflowSelectionsRequest(selections: Record<string, string | undefined>) {
|
||||
const entries = Object.entries(selections).filter(([, value]) => value?.trim());
|
||||
return entries.length ? JSON.stringify(Object.fromEntries(entries.sort(([a], [b]) => a.localeCompare(b)))) : "";
|
||||
}
|
||||
@ -124,7 +124,7 @@ async function analyzeWithConfiguredQwenVisionModel(params: {
|
||||
},
|
||||
],
|
||||
temperature: 0,
|
||||
maxOutputTokens: 220,
|
||||
maxTokens: 220,
|
||||
abortSignal: AbortSignal.timeout(25_000),
|
||||
} as any);
|
||||
|
||||
|
||||
@ -1737,7 +1737,7 @@ async function buildExecutionPlanWithAgent(
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
temperature: getCompatibleTextGenerationTemperature(plannerModelConfig, 0.1),
|
||||
maxOutputTokens: 420,
|
||||
maxTokens: 420,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
@ -1858,7 +1858,7 @@ async function generateAgentConversation(
|
||||
},
|
||||
],
|
||||
temperature: getCompatibleTextGenerationTemperature(visionModelConfig, 0.2),
|
||||
maxOutputTokens: 360,
|
||||
maxTokens: 360,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
@ -1920,7 +1920,7 @@ async function generateAgentConversation(
|
||||
system: systemPrompt,
|
||||
prompt,
|
||||
temperature: getCompatibleTextGenerationTemperature(reasoningModelConfig, 0.35),
|
||||
maxOutputTokens: 520,
|
||||
maxTokens: 520,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
@ -2002,7 +2002,7 @@ async function recommendImageParamsWithAgent(
|
||||
- negativePrompt 仅在明显需要避坑时填写。`,
|
||||
prompt: requestText,
|
||||
temperature: getCompatibleTextGenerationTemperature(plannerModelConfig, 0.15),
|
||||
maxOutputTokens: 220,
|
||||
maxTokens: 220,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
@ -2095,7 +2095,7 @@ async function recommendVideoPlanWithAgent(
|
||||
- 避免抽象空话,必须可执行。`,
|
||||
prompt,
|
||||
temperature: getCompatibleTextGenerationTemperature(plannerModelConfig, 0.2),
|
||||
maxOutputTokens: 720,
|
||||
maxTokens: 720,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
@ -2175,7 +2175,7 @@ async function refineRouteWithAgent(
|
||||
候选模型:
|
||||
${candidatesText}`,
|
||||
temperature: getCompatibleTextGenerationTemperature(plannerModelConfig, 0.1),
|
||||
maxOutputTokens: 120,
|
||||
maxTokens: 120,
|
||||
abortSignal: AbortSignal.timeout(AGENT_OPERATION_TIMEOUT_MS),
|
||||
} as any);
|
||||
|
||||
|
||||
@ -4,9 +4,6 @@ import {
|
||||
executeRmbgJob,
|
||||
fetchImageBufferFromUrl,
|
||||
} from "@/lib/ai/rmbg/service";
|
||||
import { createLogger } from "@/lib/observability/logger";
|
||||
|
||||
const logger = createLogger("box-cutout-service");
|
||||
|
||||
export type NormalizedCropRect = {
|
||||
x: number;
|
||||
@ -16,7 +13,6 @@ export type NormalizedCropRect = {
|
||||
};
|
||||
|
||||
export interface ExecuteBoxCutoutJobParams {
|
||||
requestId?: string;
|
||||
userId: string;
|
||||
imageUrl: string;
|
||||
cropRect: Partial<NormalizedCropRect>;
|
||||
@ -147,7 +143,6 @@ function applyPadding(
|
||||
export async function executeBoxCutoutJob(
|
||||
params: ExecuteBoxCutoutJobParams,
|
||||
): Promise<ExecuteBoxCutoutJobResult> {
|
||||
const requestId = params.requestId || crypto.randomUUID();
|
||||
const imageUrl = String(params.imageUrl || "").trim();
|
||||
if (!imageUrl) {
|
||||
throw new BoxCutoutServiceError("缺少 imageUrl 参数", 400);
|
||||
@ -155,7 +150,7 @@ export async function executeBoxCutoutJob(
|
||||
|
||||
const cropRect = sanitizeNormalizedCropRect(params.cropRect);
|
||||
if (!cropRect) {
|
||||
throw new BoxCutoutServiceError("框选范围无效,请重新框选需要抠出的区域后提交。", 400);
|
||||
throw new BoxCutoutServiceError("缺少有效的 cropRect 参数", 400);
|
||||
}
|
||||
|
||||
const paddingRatio = normalizeBoxCutoutPaddingRatio(params.paddingRatio);
|
||||
@ -175,7 +170,7 @@ export async function executeBoxCutoutJob(
|
||||
|
||||
const cropRectPixels = toPixelRect(cropRect, sourceWidth, sourceHeight);
|
||||
if (cropRectPixels.width < MIN_CROP_EDGE_PX || cropRectPixels.height < MIN_CROP_EDGE_PX) {
|
||||
throw new BoxCutoutServiceError("框选区域过小,宽、高均须至少 24 像素,请扩大框选范围后重新提交。", 400);
|
||||
throw new BoxCutoutServiceError("框选区域过小,请重新框选", 400);
|
||||
}
|
||||
|
||||
const paddedCropRect = applyPadding(cropRect, paddingRatio);
|
||||
@ -189,18 +184,7 @@ export async function executeBoxCutoutJob(
|
||||
})
|
||||
.toBuffer();
|
||||
|
||||
logger.info("crop_prepared", {
|
||||
requestId,
|
||||
sourceNodeId: params.sourceNodeId,
|
||||
sourceWidth,
|
||||
sourceHeight,
|
||||
cropRectPixels,
|
||||
paddedCropRectPixels,
|
||||
inputBytes: croppedBuffer.length,
|
||||
});
|
||||
|
||||
const result = await executeRmbgJob({
|
||||
requestId,
|
||||
userId: params.userId,
|
||||
imageBuffer: croppedBuffer,
|
||||
imageBase64: croppedBuffer.toString("base64"),
|
||||
|
||||
@ -9,7 +9,6 @@ import {
|
||||
summarizeAgentCapabilities,
|
||||
} from "./capability-access";
|
||||
import type { CanvasAgentTool } from "./loop";
|
||||
import { AgentToolRejectedError } from "./protocol";
|
||||
import type { CanvasOperationPlan } from "@/types/canvas/agent-protocol";
|
||||
|
||||
export function registerImageCanvasAccessTools(params: {
|
||||
@ -60,10 +59,10 @@ export function registerImageCanvasAccessTools(params: {
|
||||
(item) => item.workspace === "canvas" && item.id === input.featureId,
|
||||
);
|
||||
if (!feature?.authorized || !feature.id.startsWith("canvas.ui."))
|
||||
throw new AgentToolRejectedError("请使用清单中的图片画布界面入口,媒体能力请使用对应专用工具;本次未打开面板或提交处理。");
|
||||
throw new Error("请使用清单中的图片画布界面入口,媒体能力请使用对应专用工具");
|
||||
const { nodes } = await readOwnedCanvas(params.userId, params.projectId);
|
||||
if (input.nodeIds.some((nodeId) => !nodes.some((node) => node.id === nodeId)))
|
||||
throw new AgentToolRejectedError("目标节点不属于当前画布,本次未打开面板或提交处理。");
|
||||
throw new Error("目标节点不属于当前画布");
|
||||
params.emit("data-canvasAgentUiCommand", {
|
||||
projectId: params.projectId,
|
||||
requestId: `${params.runId}:${id}`,
|
||||
|
||||
@ -13,18 +13,13 @@ export type AgentImageParameters = {
|
||||
};
|
||||
export type AgentImagePreferences = { modelId?: string; parameters?: AgentImageParameters };
|
||||
|
||||
export function selectedAgentImageCount(preferences?: AgentImagePreferences) {
|
||||
const count = preferences?.parameters?.imageCount ?? preferences?.parameters?.n;
|
||||
return count === undefined ? undefined : Math.floor(count);
|
||||
}
|
||||
|
||||
export function applyAgentImagePreferences<T extends Record<string, unknown>>(
|
||||
input: T,
|
||||
preferences?: AgentImagePreferences,
|
||||
): T & AgentImageParameters & { modelId?: string } {
|
||||
const parameters = Object.fromEntries(Object.entries(preferences?.parameters || {})
|
||||
.filter(([, value]) => value !== undefined));
|
||||
const count = selectedAgentImageCount(preferences);
|
||||
const count = preferences?.parameters?.imageCount ?? preferences?.parameters?.n;
|
||||
return {
|
||||
...input,
|
||||
...parameters,
|
||||
|
||||
@ -1,14 +1,5 @@
|
||||
import type { AgentCallRecord, AgentRunSnapshot } from "./protocol";
|
||||
|
||||
export function countAgentGeneratedImages(calls: AgentCallRecord[]) {
|
||||
return calls.reduce((count, call) => {
|
||||
const output = call.output;
|
||||
if (call.status !== "succeeded" || !output?.appliedImagePreferences ||
|
||||
!Array.isArray(output.createdNodeIds)) return count;
|
||||
return count + output.createdNodeIds.length;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// A spontaneous download command is not an unfinished image edit. Keep genuine
|
||||
// download requests and all editor panels waiting for their actual interaction.
|
||||
export function isAncillaryDownload(snapshot: AgentRunSnapshot, call: AgentCallRecord) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user