Compare commits
327 Commits
codex/deta
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e4fcfee16b | |||
| 3e567e4b05 | |||
| 4c53f9778b | |||
| bf9f06d907 | |||
| 06593978a5 | |||
| fafff4f7e8 | |||
| e264fd3e30 | |||
| d4c5ceba9b | |||
| 3c8f2174c5 | |||
| 5228cef34e | |||
| 868104ea19 | |||
| 79171a1282 | |||
| 6c7bebe9d3 | |||
| 9334591323 | |||
| f670158409 | |||
| 0d16c27178 | |||
| d79b0b8e49 | |||
| 171e5d6a49 | |||
| c0054cfa7c | |||
| 4fb829a417 | |||
| 6ff8a0c43d | |||
| dfe39a8d20 | |||
| 7fe5ec24a8 | |||
| e64bbfef9c | |||
| a99a63a7bb | |||
| 2b23476d51 | |||
| 4a1e521556 | |||
| 8b2ec847e7 | |||
| a13a6cc180 | |||
| 53b376c739 | |||
| 75997efe2e | |||
| ee1c5bf971 | |||
| 23cf98bf61 | |||
| 18cdbc99c2 | |||
| d96336f568 | |||
| e48b8fd10b | |||
| 3e08783b37 | |||
| a02c203781 | |||
| fc97232b6f | |||
| e3f17cbb5d | |||
| 020637f13d | |||
| 121ca3014b | |||
| 83091c0457 | |||
| 399aa1d761 | |||
| 7094231a55 | |||
| 902ad6fc9c | |||
| bf4dfe0fcb | |||
| 582667dd05 | |||
| 4cfadcea08 | |||
| a7fdff59fc | |||
| 58b4695d17 | |||
| 2123e6208c | |||
| 60c8109d09 | |||
| 9687561b9c | |||
| 82218217ec | |||
| 2d65834dbb | |||
| 0a808a2b83 | |||
| 90492972b3 | |||
| 4d739927f7 | |||
| 903686db36 | |||
| 40fdb41b32 | |||
| f980cfb036 | |||
| 2d0238aca6 | |||
| 5701e95bb4 | |||
| 36ad7900b6 | |||
| c655bbd81e | |||
| dff2e22ffd | |||
| 995820138a | |||
| 4ac5062080 | |||
| ba24efc8e7 | |||
| 1a682343c7 | |||
| f8c97ba7e4 | |||
| 17075e38bd | |||
| ed25603be2 | |||
| 7464108d2f | |||
| 86fd3353f4 | |||
| af54ec2611 | |||
| 9139b33208 | |||
| 2b5455d046 | |||
| 89a9416815 | |||
| 168de1db3c | |||
| 90fe4f2933 | |||
| dc7a1ae0a4 | |||
| a6f79998bd | |||
| d0653c2d51 | |||
| f058012bb8 | |||
| 8aa9ebd061 | |||
| d32258e13b | |||
| 6caf1b5cce | |||
| 78b111130b | |||
| 8fca3b25c5 | |||
| b8799f4804 | |||
| d1f9590d05 | |||
| 74053490cc | |||
| 61b6eba4b4 | |||
| bbecafc826 | |||
| ed3b1b5e8a | |||
| 8f56b5a567 | |||
| fd8d5404c6 | |||
| 09db16f74c | |||
| 70621f4261 | |||
| 5a95e7da49 | |||
| 8cf113b554 | |||
| 5fc3f1bb11 | |||
| 1342bf384c | |||
| 759ee6af58 | |||
| 54eb35e21c | |||
| f157161ad9 | |||
| eb9ee0ce1e | |||
| 2c30c9d7f9 | |||
| 8428886a1d | |||
| 24cf77c9c2 | |||
| 9cbc32bb5d | |||
| 7ddaeb12a0 | |||
| 5f24743bdb | |||
| 03a5613d80 | |||
| 6112892b85 | |||
| 8c50c1ce72 | |||
| b3c4f2763a | |||
| 97d32fd2d3 | |||
| 4dd6885f1c | |||
| 7b776f96c1 | |||
| 17d5f6fec9 | |||
| b3549f25d7 | |||
| 74d9368744 | |||
| e8e8edcefe | |||
| 57e94b797c | |||
| ca6b27624c | |||
| fa3210a367 | |||
| e335821ca8 | |||
| c2e8ff6eac | |||
| d26bec9864 | |||
| 24a3c930c2 | |||
| ebb0d1514b | |||
| 50ffc8d648 | |||
| ff6381d02e | |||
| feaa18ed3b | |||
| 2939ff8a1f | |||
| 5bffeaf94d | |||
| e221027b74 | |||
| 445d756a19 | |||
| 05c3d90708 | |||
| cea4cd01f5 | |||
| ea0351bb2c | |||
| 37406d7d6e | |||
| 0ce9a95a9c | |||
| 8bf8e349ca | |||
| 8039bea86c | |||
| aea18a7fc6 | |||
| e9921cae98 | |||
| 1f5528331d | |||
| 535ea1aee4 | |||
| 8cbc8b1ab8 | |||
| ae9354f747 | |||
| c68bf9a824 | |||
| 21b47751d6 | |||
| c219f5b10b | |||
| 672c1368e0 | |||
| c60585aeca | |||
| 2ee8bd4dea | |||
| 85ff680b65 | |||
| 751cffae05 | |||
| 6e4350fe2b | |||
| 3f52e24076 | |||
| 0b74e71a33 | |||
| 4f8c1a5d5d | |||
| 33662210dd | |||
| 71413c173e | |||
| dbe96db34d | |||
| dfaeb9f09d | |||
| 46abb8259a | |||
| 3b3b5bc78a | |||
| db63f38b9c | |||
| 955ad91ae8 | |||
| 36ac3def8f | |||
| 1d40053c7a | |||
| 07451f5558 | |||
| 13684505a6 | |||
| 65b235e747 | |||
| d1ee6d53d5 | |||
| a484942fb9 | |||
| 084f538e77 | |||
| 5250aed7b7 | |||
| cbec13b285 | |||
| 5fda42495a | |||
| 73eb276e7f | |||
| 8c7ca174bc | |||
| 8fd0dba59f | |||
| ce94241234 | |||
| 198deca47b | |||
| 8908b0d39a | |||
| 34ba1919c4 | |||
| 2fdc4299e0 | |||
| ac2369b657 | |||
| 6642c39198 | |||
| ac7928fe2d | |||
| b06fdbb38b | |||
| 61e2bbe0e4 | |||
| 70f954382a | |||
| 00cef71be7 | |||
| 525e105876 | |||
| 5371ae2617 | |||
| af8189908d | |||
| 6053271352 | |||
| 6b7b24a86e | |||
| c431a574c8 | |||
| 1daf08a964 | |||
| 348cf4cf5d | |||
| a43a51adfc | |||
| 6ba5d9606d | |||
| 02b9575a47 | |||
| 349735601c | |||
| e837788d7a | |||
|
|
dfab95a654 | ||
| c35f5fc5a8 | |||
|
|
e6c6e19e5a | ||
| bb9d02a053 | |||
|
|
d9b06cf0b3 | ||
| 086c58fcc3 | |||
|
|
5a343b6392 | ||
| e6f07ed2ce | |||
|
|
db46983725 | ||
| ae4605d479 | |||
|
|
36efdfae53 | ||
| 10efb4c1e7 | |||
|
|
9da598967a | ||
| 91edc4019e | |||
|
|
7439792d40 | ||
| be642948ec | |||
|
|
9155682238 | ||
|
|
03b8a0deb0 | ||
|
|
439fd56fe1 | ||
|
|
99db635e0a | ||
|
|
14a7668274 | ||
|
|
01485340b5 | ||
|
|
8784bb783e | ||
|
|
82c71b8cd8 | ||
|
|
90c17a61fb | ||
|
|
404d783fa5 | ||
|
|
1705f0ba43 | ||
|
|
b689f8f770 | ||
|
|
7541262f28 | ||
|
|
75e6a28309 | ||
|
|
7925545980 | ||
|
|
59994062c9 | ||
|
|
fb10747828 | ||
|
|
d2d0a1725c | ||
|
|
f38488b546 | ||
|
|
36761e37a4 | ||
|
|
32e8c9cbd6 | ||
|
|
2a2a32c3bd | ||
|
|
d4a6b54078 | ||
|
|
d8aa51185e | ||
|
|
73f9844022 | ||
|
|
1803727d4b | ||
|
|
8848d00107 | ||
|
|
623859f846 | ||
|
|
f55d21968f | ||
|
|
ad25b4e17f | ||
|
|
5dbdc3df46 | ||
|
|
cfb071d0df | ||
|
|
fce14356d9 | ||
|
|
ac2e355a7a | ||
|
|
a8c6a5a026 | ||
|
|
1965ee9cc0 | ||
|
|
0d44ac12c8 | ||
|
|
c7f320074a | ||
|
|
62311d187f | ||
|
|
a4bf68734c | ||
|
|
145f699823 | ||
|
|
8ee12a5b13 | ||
|
|
0a3eef1f4d | ||
|
|
0fd14f18bb | ||
|
|
ac9103906e | ||
|
|
320d52d26f | ||
|
|
2bd2910fae | ||
|
|
54ce53f263 | ||
|
|
f0b6c2765f | ||
|
|
d3b8162faf | ||
|
|
ac54ade6b7 | ||
|
|
1aa61570db | ||
|
|
3504141be5 | ||
|
|
79d10cf1ac | ||
|
|
3a9e392a7f | ||
|
|
07101946ff | ||
|
|
8111ce7708 | ||
|
|
a03ac48f3a | ||
|
|
1dd4487cf0 | ||
|
|
6319a3ceef | ||
|
|
4734d5cb76 | ||
|
|
d33db04ecc | ||
|
|
ab7240b3d4 | ||
|
|
55ad5b21f0 | ||
|
|
562b9a3f1d | ||
|
|
30cfd62669 | ||
|
|
255e9082da | ||
|
|
53e565045a | ||
|
|
a2b65b426c | ||
|
|
d1789f5f93 | ||
|
|
726d66bd19 | ||
|
|
74aa67ce44 | ||
|
|
f83779e65e | ||
|
|
10ef40b734 | ||
|
|
850f664fb1 | ||
|
|
3750e89ed1 | ||
|
|
c0cbc34911 | ||
|
|
dfc1c6d496 | ||
|
|
425d3a4ddf | ||
|
|
1a806b4275 | ||
|
|
47e1009ee0 | ||
|
|
50569ca88a | ||
|
|
c3f5903a86 | ||
|
|
9611fafe0b | ||
|
|
9f98a68049 | ||
|
|
822c4cbfb9 | ||
|
|
a492d082ed | ||
|
|
4ada7eaf38 | ||
|
|
63e2f48192 | ||
|
|
d376f5959f | ||
|
|
2c8f306e74 | ||
|
|
c4a2753a6e | ||
|
|
0d752d6e38 | ||
|
|
96d67955cb | ||
|
|
c45a6a77a0 | ||
|
|
88cf96b998 | ||
|
|
570375b5f1 | ||
|
|
e7be5af3f2 |
10
.env.example
10
.env.example
@ -40,6 +40,11 @@ EMAIL_VERIFICATION_SECRET=
|
|||||||
# Optional scheduled job protection.
|
# Optional scheduled job protection.
|
||||||
CRON_SECRET=
|
CRON_SECRET=
|
||||||
|
|
||||||
|
# Canvas feedback: server-side project credentials for the shared notification center.
|
||||||
|
YYD_NOTIFICATION_CENTER_URL=https://sc.jiansun.vip/notification-center
|
||||||
|
YYD_NOTIFICATION_CENTER_PROJECT_CODE=
|
||||||
|
YYD_NOTIFICATION_CENTER_PROJECT_SECRET=
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Database
|
# Database
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
@ -153,8 +158,9 @@ PRODUCT_PLANNING_DB_SSL=false
|
|||||||
# Home Performance / Queues
|
# Home Performance / Queues
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
|
|
||||||
CANVAS_IMAGE_TASK_CONCURRENCY=3
|
# Legacy image queue fields: 0 = unrestricted; model/user admission caps are disabled.
|
||||||
CANVAS_IMAGE_TASK_BATCH_DISPATCH_INTERVAL_MS=1000
|
CANVAS_IMAGE_TASK_CONCURRENCY=0
|
||||||
|
CANVAS_IMAGE_TASK_BATCH_DISPATCH_INTERVAL_MS=0
|
||||||
EXTERNAL_IMAGE_API_MAX_CONCURRENT=3
|
EXTERNAL_IMAGE_API_MAX_CONCURRENT=3
|
||||||
EXTERNAL_IMAGE_API_MAX_QUEUE=20
|
EXTERNAL_IMAGE_API_MAX_QUEUE=20
|
||||||
EXTERNAL_IMAGE_API_QUEUE_TIMEOUT_MS=120000
|
EXTERNAL_IMAGE_API_QUEUE_TIMEOUT_MS=120000
|
||||||
|
|||||||
20
.gitattributes
vendored
Normal file
20
.gitattributes
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
# Keep source checkouts consistent across Windows and Linux.
|
||||||
|
.gitattributes text eol=lf
|
||||||
|
.gitignore text eol=lf
|
||||||
|
*.ts text eol=lf
|
||||||
|
*.tsx text eol=lf
|
||||||
|
*.js text eol=lf
|
||||||
|
*.jsx text eol=lf
|
||||||
|
*.mjs text eol=lf
|
||||||
|
*.cjs text eol=lf
|
||||||
|
*.json text eol=lf
|
||||||
|
*.jsonc text eol=lf
|
||||||
|
*.yaml text eol=lf
|
||||||
|
*.yml text eol=lf
|
||||||
|
*.css text eol=lf
|
||||||
|
*.html text eol=lf
|
||||||
|
*.md text eol=lf
|
||||||
|
*.sh text eol=lf
|
||||||
|
*.py text eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.cmd text eol=crlf
|
||||||
11
.gitignore
vendored
11
.gitignore
vendored
@ -13,6 +13,7 @@ coverage
|
|||||||
.next/
|
.next/
|
||||||
.next-build/
|
.next-build/
|
||||||
.next-previous/
|
.next-previous/
|
||||||
|
/.next-*/
|
||||||
out/
|
out/
|
||||||
build
|
build
|
||||||
|
|
||||||
@ -67,6 +68,11 @@ migration-backup-complete/
|
|||||||
migration-*.log
|
migration-*.log
|
||||||
migration-*.txt
|
migration-*.txt
|
||||||
|
|
||||||
|
# Local release backups, model credentials and migration scratch data.
|
||||||
|
/.model-config-backups/
|
||||||
|
/backups/
|
||||||
|
/tmp/
|
||||||
|
|
||||||
# 本地抓包/竞品参考产物,不能提交
|
# 本地抓包/竞品参考产物,不能提交
|
||||||
artifacts/liblib-*/
|
artifacts/liblib-*/
|
||||||
analysis/qiaodou-extract/
|
analysis/qiaodou-extract/
|
||||||
@ -120,6 +126,7 @@ services/smart-edit/__pycache__/
|
|||||||
# Local verification artefacts (also excluded from Tailwind's automatic source scan).
|
# Local verification artefacts (also excluded from Tailwind's automatic source scan).
|
||||||
.qa/
|
.qa/
|
||||||
.next-video-*/
|
.next-video-*/
|
||||||
|
.next-tvstar-*/
|
||||||
|
|
||||||
services/video-upscale/dist/
|
services/video-upscale/dist/
|
||||||
services/video-upscale/__pycache__/
|
services/video-upscale/__pycache__/
|
||||||
@ -127,3 +134,7 @@ services/video-upscale/vendor/__pycache__/
|
|||||||
|
|
||||||
/services/audio-processing/dist/
|
/services/audio-processing/dist/
|
||||||
/services/audio-processing/__pycache__/
|
/services/audio-processing/__pycache__/
|
||||||
|
|
||||||
|
# Python release-tool and test bytecode.
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
|||||||
@ -2377,8 +2377,10 @@ export function LocalAiImagePipelineSections({
|
|||||||
items={[
|
items={[
|
||||||
{
|
{
|
||||||
label:
|
label:
|
||||||
extendConfig.provider === "vip98k"
|
extendConfig.provider === "fal"
|
||||||
? "VIP98K 服务商"
|
? "fal · FLUX 2 Pro 扩图"
|
||||||
|
: extendConfig.provider === "vip98k"
|
||||||
|
? `98K · ${extendConfig.modelId || "image-expansion"}`
|
||||||
: "阿里云服务商",
|
: "阿里云服务商",
|
||||||
tone: "enabled",
|
tone: "enabled",
|
||||||
},
|
},
|
||||||
@ -2391,9 +2393,13 @@ export function LocalAiImagePipelineSections({
|
|||||||
}
|
}
|
||||||
title="图像拓展API配置"
|
title="图像拓展API配置"
|
||||||
>
|
>
|
||||||
{extendConfig.provider === "vip98k" ? (
|
{extendConfig.provider === "fal" ? (
|
||||||
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
<div className="rounded-lg border bg-muted/40 p-4 text-sm">
|
||||||
使用 VIP98K 的 image-expansion 模型。API Key 从“AI 模型设置”中的
|
使用 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 服务商读取,仅在这里维护扩展比例。
|
VIP98K 服务商读取,仅在这里维护扩展比例。
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@ -1078,139 +1078,15 @@ export function LocalAiRuntimeSections({
|
|||||||
</Button>
|
</Button>
|
||||||
</LocalAiSectionShell>
|
</LocalAiSectionShell>
|
||||||
|
|
||||||
{/* 全站生图单模型并发 */}
|
|
||||||
<LocalAiSectionShell
|
<LocalAiSectionShell
|
||||||
description={
|
description="生图任务直接发起,图片先显示,后台转存到存储桶。"
|
||||||
<>
|
|
||||||
控制全站生图链路中,同一个模型允许同时运行的任务数,以及排队后下一批任务的发起间隔。配置保存到数据库,异步队列和直调生成都会自动读取,无需重启服务。
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
expanded={isLocalAiSectionExpanded("canvas-image-task-queue")}
|
expanded={isLocalAiSectionExpanded("canvas-image-task-queue")}
|
||||||
id="local-ai-section-canvas-image-task-queue"
|
id="local-ai-section-canvas-image-task-queue"
|
||||||
onToggle={() => toggleLocalAiSection("canvas-image-task-queue")}
|
onToggle={() => toggleLocalAiSection("canvas-image-task-queue")}
|
||||||
summary={
|
summary={<LocalAiSectionSummary items={[{ label: "并发不限", tone: "enabled" }, { label: "即时发起", tone: "enabled" }]} />}
|
||||||
<LocalAiSectionSummary
|
title={<span className="flex items-center gap-2"><ImageIcon className="h-5 w-5" />生图任务执行</span>}
|
||||||
items={[
|
|
||||||
{
|
|
||||||
label: `${canvasImageTaskQueueConfig.concurrency} 并发/模型`,
|
|
||||||
tone: "neutral",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: `${(
|
|
||||||
canvasImageTaskQueueConfig.batchDispatchIntervalMs / 1000
|
|
||||||
).toFixed(1)} 秒补位`,
|
|
||||||
tone: "neutral",
|
|
||||||
},
|
|
||||||
{ label: "全站生图生效", tone: "enabled" },
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
title={
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<ImageIcon className="h-5 w-5" />
|
|
||||||
全站生图单模型并发与批次间隔
|
|
||||||
</span>
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(220px,320px)]">
|
<p className="text-muted-foreground text-sm">已取消模型及单用户并发限制,任务无需等待其他图片生成完成。任务状态、超时处理和失败重试继续保留。</p>
|
||||||
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-amber-900 text-sm">
|
|
||||||
<div className="font-medium">生效范围</div>
|
|
||||||
<div className="mt-2 space-y-1 text-amber-800 text-xs leading-5">
|
|
||||||
<p>
|
|
||||||
•
|
|
||||||
影响画布异步生图、智能体直调生图、视频分镜高清预览等全站生图入口。
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
•
|
|
||||||
多用户共享同一套并发限制,但会按模型分别计数,不同模型之间不再互相阻塞。
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
• 当前配置的是单模型并发,不是全站总并发,也不是单用户并发。
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
•
|
|
||||||
批次间隔只控制排队补位的“下一批”发起节奏,不影响首批任务即时启动。
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
• 数值过高可能触发上游模型 429、超时或 504,建议配合模型 Key
|
|
||||||
池继续细分。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="canvasImageTaskQueueConcurrency">
|
|
||||||
单模型最大同时运行任务数
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="canvasImageTaskQueueConcurrency"
|
|
||||||
max={MAX_CANVAS_IMAGE_TASK_CONCURRENCY}
|
|
||||||
min={MIN_CANVAS_IMAGE_TASK_CONCURRENCY}
|
|
||||||
onChange={(e) =>
|
|
||||||
setCanvasImageTaskQueueConfig(
|
|
||||||
normalizeCanvasImageTaskQueueConfig({
|
|
||||||
...canvasImageTaskQueueConfig,
|
|
||||||
concurrency: e.target.value,
|
|
||||||
})
|
|
||||||
)
|
|
||||||
}
|
|
||||||
type="number"
|
|
||||||
value={canvasImageTaskQueueConfig.concurrency}
|
|
||||||
/>
|
|
||||||
<div className="text-muted-foreground text-xs">
|
|
||||||
可配置范围 {MIN_CANVAS_IMAGE_TASK_CONCURRENCY}-
|
|
||||||
{MAX_CANVAS_IMAGE_TASK_CONCURRENCY},当前为{" "}
|
|
||||||
{canvasImageTaskQueueConfig.concurrency} 并发,默认值为{" "}
|
|
||||||
{DEFAULT_CANVAS_IMAGE_TASK_CONCURRENCY}。
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="canvasImageTaskBatchDispatchIntervalSeconds">
|
|
||||||
下一批排队任务发起间隔(秒)
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="canvasImageTaskBatchDispatchIntervalSeconds"
|
|
||||||
max={MAX_CANVAS_IMAGE_BATCH_DISPATCH_INTERVAL_MS / 1000}
|
|
||||||
min={MIN_CANVAS_IMAGE_BATCH_DISPATCH_INTERVAL_MS / 1000}
|
|
||||||
onChange={(e) =>
|
|
||||||
setCanvasImageTaskQueueConfig(
|
|
||||||
normalizeCanvasImageTaskQueueConfig({
|
|
||||||
...canvasImageTaskQueueConfig,
|
|
||||||
batchDispatchIntervalMs: Math.round(
|
|
||||||
Number.parseFloat(e.target.value || "0") * 1000
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
}
|
|
||||||
step="0.5"
|
|
||||||
type="number"
|
|
||||||
value={String(
|
|
||||||
canvasImageTaskQueueConfig.batchDispatchIntervalMs / 1000
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div className="text-muted-foreground text-xs">
|
|
||||||
可配置范围 {MIN_CANVAS_IMAGE_BATCH_DISPATCH_INTERVAL_MS / 1000}-
|
|
||||||
{MAX_CANVAS_IMAGE_BATCH_DISPATCH_INTERVAL_MS / 1000} 秒,当前为{" "}
|
|
||||||
{(
|
|
||||||
canvasImageTaskQueueConfig.batchDispatchIntervalMs / 1000
|
|
||||||
).toFixed(1)}{" "}
|
|
||||||
秒,默认值为{" "}
|
|
||||||
{(
|
|
||||||
DEFAULT_CANVAS_IMAGE_BATCH_DISPATCH_INTERVAL_MS / 1000
|
|
||||||
).toFixed(1)}{" "}
|
|
||||||
秒。
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end">
|
|
||||||
<Button onClick={handleSaveCanvasImageTaskQueueConfig}>
|
|
||||||
<Save className="mr-2 h-4 w-4" /> 保存并发与间隔
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</LocalAiSectionShell>
|
</LocalAiSectionShell>
|
||||||
|
|
||||||
{/* 批量处理配置 */}
|
{/* 批量处理配置 */}
|
||||||
|
|||||||
@ -274,7 +274,9 @@ export type EnhanceConfig = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type ExtendConfig = {
|
export type ExtendConfig = {
|
||||||
provider: "vip98k" | "dashscope";
|
provider: "vip98k" | "dashscope" | "fal";
|
||||||
|
modelId: string;
|
||||||
|
routeOptionId: string;
|
||||||
xScale: string;
|
xScale: string;
|
||||||
yScale: string;
|
yScale: string;
|
||||||
};
|
};
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -23,6 +23,21 @@ import { AntigravityBackground } from "@/components/antigravity-background";
|
|||||||
import { createClientLogger } from "@/lib/observability/client-logger";
|
import { createClientLogger } from "@/lib/observability/client-logger";
|
||||||
|
|
||||||
const logger = createClientLogger("auth-login");
|
const logger = createClientLogger("auth-login");
|
||||||
|
|
||||||
|
function getSafeLoginCallbackUrl() {
|
||||||
|
const { origin, search } = window.location;
|
||||||
|
const callbackUrl = new URLSearchParams(search).get("callbackUrl");
|
||||||
|
if (!callbackUrl?.startsWith("/")) return "/";
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { origin: targetOrigin, pathname, search, hash } = new URL(callbackUrl, origin);
|
||||||
|
if (targetOrigin !== origin || pathname.startsWith("//")) return "/";
|
||||||
|
return pathname + search + hash;
|
||||||
|
} catch {
|
||||||
|
return "/";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [isSuccessful, setIsSuccessful] = useState(false);
|
const [isSuccessful, setIsSuccessful] = useState(false);
|
||||||
@ -70,7 +85,7 @@ export default function Page() {
|
|||||||
.then((data) => {
|
.then((data) => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
if (data?.valid === true && data?.userType !== "guest") {
|
if (data?.valid === true && data?.userType !== "guest") {
|
||||||
window.location.replace("/");
|
window.location.replace(getSafeLoginCallbackUrl());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setIsCheckingExistingSession(false);
|
setIsCheckingExistingSession(false);
|
||||||
@ -90,6 +105,7 @@ export default function Page() {
|
|||||||
const completeDingTalkLogin = useCallback(async (token: string) => {
|
const completeDingTalkLogin = useCallback(async (token: string) => {
|
||||||
logger.debug("[DingTalk] Completing login with token", { hasToken: Boolean(token) });
|
logger.debug("[DingTalk] Completing login with token", { hasToken: Boolean(token) });
|
||||||
setIsHandlingToken(true);
|
setIsHandlingToken(true);
|
||||||
|
const callbackUrl = getSafeLoginCallbackUrl();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 获取 CSRF token
|
// 获取 CSRF token
|
||||||
@ -102,11 +118,12 @@ export default function Page() {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/x-www-form-urlencoded",
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
"X-Auth-Return-Redirect": "1",
|
||||||
},
|
},
|
||||||
body: new URLSearchParams({
|
body: new URLSearchParams({
|
||||||
csrfToken,
|
csrfToken,
|
||||||
token,
|
token,
|
||||||
callbackUrl: "/",
|
callbackUrl,
|
||||||
}),
|
}),
|
||||||
credentials: "include", // 重要:确保 cookie 被发送和接收
|
credentials: "include", // 重要:确保 cookie 被发送和接收
|
||||||
});
|
});
|
||||||
@ -134,12 +151,12 @@ export default function Page() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (session && session.user) {
|
if (session && session.user) {
|
||||||
logger.debug("[DingTalk] Session validated, redirecting to home...");
|
logger.debug("[DingTalk] Session validated, redirecting...");
|
||||||
setIsSuccessful(true);
|
setIsSuccessful(true);
|
||||||
// 使用 replace 而不是 href,避免在历史记录中留下登录页
|
// 使用 replace 而不是 href,避免在历史记录中留下登录页
|
||||||
// 增加短暂延迟确保 cookie 完全同步
|
// 增加短暂延迟确保 cookie 完全同步
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.location.replace("/");
|
window.location.replace(callbackUrl);
|
||||||
}, 200);
|
}, 200);
|
||||||
} else {
|
} else {
|
||||||
logger.error("[DingTalk] Session not created after login");
|
logger.error("[DingTalk] Session not created after login");
|
||||||
@ -174,7 +191,7 @@ export default function Page() {
|
|||||||
// 使用 replace 而不是 href,避免在历史记录中留下登录页
|
// 使用 replace 而不是 href,避免在历史记录中留下登录页
|
||||||
// 增加短暂延迟确保 cookie 完全同步
|
// 增加短暂延迟确保 cookie 完全同步
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.location.replace(result.url || "/");
|
window.location.replace(callbackUrl);
|
||||||
}, 200);
|
}, 200);
|
||||||
} else {
|
} else {
|
||||||
logger.error("[DingTalk] Session not created");
|
logger.error("[DingTalk] Session not created");
|
||||||
@ -298,7 +315,7 @@ export default function Page() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await signIn("google", { callbackUrl: "/" });
|
await signIn("google", { redirectTo: getSafeLoginCallbackUrl() });
|
||||||
};
|
};
|
||||||
|
|
||||||
// 检查 URL 中是否有钉钉 Token(页面加载时自动登录)
|
// 检查 URL 中是否有钉钉 Token(页面加载时自动登录)
|
||||||
@ -365,13 +382,14 @@ export default function Page() {
|
|||||||
description: "提交的信息校验失败",
|
description: "提交的信息校验失败",
|
||||||
});
|
});
|
||||||
} else if (state.status === "success") {
|
} else if (state.status === "success") {
|
||||||
toast({ type: "success", description: "登录成功,正在进入首页" });
|
const callbackUrl = getSafeLoginCallbackUrl();
|
||||||
|
toast({ type: "success", description: "登录成功,正在跳转" });
|
||||||
setIsSuccessful(true);
|
setIsSuccessful(true);
|
||||||
loginRedirectTimerRef.current = window.setTimeout(() => {
|
loginRedirectTimerRef.current = window.setTimeout(() => {
|
||||||
window.location.replace("/");
|
window.location.replace(callbackUrl);
|
||||||
}, 120);
|
}, 120);
|
||||||
loginRedirectFallbackTimerRef.current = window.setTimeout(() => {
|
loginRedirectFallbackTimerRef.current = window.setTimeout(() => {
|
||||||
window.location.assign("/");
|
window.location.assign(callbackUrl);
|
||||||
}, 1600);
|
}, 1600);
|
||||||
}
|
}
|
||||||
}, [state.status]);
|
}, [state.status]);
|
||||||
@ -393,23 +411,6 @@ export default function Page() {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getSafeLoginCallbackUrl = () => {
|
|
||||||
if (typeof window === "undefined") return "/";
|
|
||||||
|
|
||||||
const callbackUrl = new URLSearchParams(window.location.search).get(
|
|
||||||
"callbackUrl",
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
callbackUrl &&
|
|
||||||
callbackUrl.startsWith("/") &&
|
|
||||||
!callbackUrl.startsWith("//")
|
|
||||||
) {
|
|
||||||
return callbackUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
return "/";
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildDingTalkLoginUrl = (orgName?: string) => {
|
const buildDingTalkLoginUrl = (orgName?: string) => {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (orgName) params.set("org", orgName);
|
if (orgName) params.set("org", orgName);
|
||||||
|
|||||||
@ -4,7 +4,8 @@ import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
|
|||||||
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
||||||
import {
|
import {
|
||||||
DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
||||||
normalizeDetailReplacementImageModelConfig,
|
findConfiguredDetailReplacementImageModel,
|
||||||
|
isDetailReplacementImageModel,
|
||||||
} from "@/lib/ai/detail-replacement-image-model-config";
|
} from "@/lib/ai/detail-replacement-image-model-config";
|
||||||
import {
|
import {
|
||||||
compositeReplacementWithReferenceLocks,
|
compositeReplacementWithReferenceLocks,
|
||||||
@ -29,7 +30,6 @@ import {
|
|||||||
} from "@/lib/db/queries";
|
} from "@/lib/db/queries";
|
||||||
import { uploadFile } from "@/lib/storage/service";
|
import { uploadFile } from "@/lib/storage/service";
|
||||||
import { bufferToArrayBuffer } from "./persistence";
|
import { bufferToArrayBuffer } from "./persistence";
|
||||||
import { isVideoProviderType } from "./video-models";
|
|
||||||
import type { AgentPresetMessageImagePart } from "./agent-scene-workflow";
|
import type { AgentPresetMessageImagePart } from "./agent-scene-workflow";
|
||||||
import type { PostRequestBody } from "../schema";
|
import type { PostRequestBody } from "../schema";
|
||||||
|
|
||||||
@ -623,7 +623,7 @@ async function resolveReplacementProductIdentityProfile(params: {
|
|||||||
system:
|
system:
|
||||||
"你是高精度商品结构分析器。多张图片属于同一商品;请跨视角还原唯一结构身份,并明确每个视角最清楚的构件。",
|
"你是高精度商品结构分析器。多张图片属于同一商品;请跨视角还原唯一结构身份,并明确每个视角最清楚的构件。",
|
||||||
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
||||||
maxTokens: 1800,
|
maxOutputTokens: 1800,
|
||||||
abortSignal: AbortSignal.timeout(
|
abortSignal: AbortSignal.timeout(
|
||||||
params.planningRuntime.kind === "local_moonshot" ? 90_000 : 60_000,
|
params.planningRuntime.kind === "local_moonshot" ? 90_000 : 60_000,
|
||||||
),
|
),
|
||||||
@ -2161,22 +2161,10 @@ export async function resolveDirectReplacementModelRef(params: {
|
|||||||
models?: Awaited<ReturnType<typeof getEnabledAiModelsWithProvider>>;
|
models?: Awaited<ReturnType<typeof getEnabledAiModelsWithProvider>>;
|
||||||
}) {
|
}) {
|
||||||
const models = params.models || (await getEnabledAiModelsWithProvider(false));
|
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({
|
const configuredModelSetting = await getSystemSetting({
|
||||||
key: DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
key: DETAIL_REPLACEMENT_IMAGE_MODEL_CONFIG_KEY,
|
||||||
}).catch(() => null);
|
}).catch(() => null);
|
||||||
const configuredModelId = normalizeDetailReplacementImageModelConfig(
|
const configuredModel = findConfiguredDetailReplacementImageModel(models, configuredModelSetting?.value);
|
||||||
configuredModelSetting?.value,
|
|
||||||
).modelId;
|
|
||||||
const configuredModel = imageModels.find(
|
|
||||||
({ model }) =>
|
|
||||||
model.id === configuredModelId || model.modelId === configuredModelId,
|
|
||||||
);
|
|
||||||
if (configuredModel) {
|
if (configuredModel) {
|
||||||
return configuredModel.model.id;
|
return configuredModel.model.id;
|
||||||
}
|
}
|
||||||
@ -2190,6 +2178,7 @@ export async function resolveDirectReplacementModelRef(params: {
|
|||||||
return routedModel;
|
return routedModel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const imageModels = models.filter(isDetailReplacementImageModel);
|
||||||
const preferred =
|
const preferred =
|
||||||
imageModels.find(({ model }) => model.isDefault) ||
|
imageModels.find(({ model }) => model.isDefault) ||
|
||||||
imageModels.find(({ provider }) => String(provider?.type || "").includes("image")) ||
|
imageModels.find(({ provider }) => String(provider?.type || "").includes("image")) ||
|
||||||
@ -2387,7 +2376,7 @@ export async function analyzeReplacementReferenceImage(params: {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
temperature: 0,
|
temperature: 0,
|
||||||
maxTokens: 160,
|
maxOutputTokens: 160,
|
||||||
abortSignal: AbortSignal.timeout(45_000),
|
abortSignal: AbortSignal.timeout(45_000),
|
||||||
} as any);
|
} as any);
|
||||||
|
|
||||||
@ -2690,7 +2679,7 @@ export async function analyzeReplacementExecutionPlan(params: {
|
|||||||
system:
|
system:
|
||||||
"你是高精度商品详情图场景规划器。你只分析当前参考图本身,负责理解这一屏的场景、机位、主体位置和人物需求,不要臆测或依赖其他输入图片。",
|
"你是高精度商品详情图场景规划器。你只分析当前参考图本身,负责理解这一屏的场景、机位、主体位置和人物需求,不要臆测或依赖其他输入图片。",
|
||||||
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
temperature: params.planningRuntime.kind === "local_moonshot" ? 1 : 0.1,
|
||||||
maxTokens: 1600,
|
maxOutputTokens: 1600,
|
||||||
abortSignal: AbortSignal.timeout(replacementScenePlanningTimeoutMs),
|
abortSignal: AbortSignal.timeout(replacementScenePlanningTimeoutMs),
|
||||||
} as any);
|
} as any);
|
||||||
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@ import { modelLacksReferenceImageInputSupport } from "@/lib/ai/reference-image-c
|
|||||||
import type { ChatMessage } from "@/lib/types";
|
import type { ChatMessage } from "@/lib/types";
|
||||||
import { convertMessagesWithImages } from "./image-media";
|
import { convertMessagesWithImages } from "./image-media";
|
||||||
import { isProviderBalanceError } from "@/lib/request-error";
|
import { isProviderBalanceError } from "@/lib/request-error";
|
||||||
import { isImageFallbackModelBalanceCoolingDown } from "@/lib/ai/runtime/image-fallback-balance-cooldown";
|
import { isImageModelBalanceBlocked } from "@/lib/ai/runtime/image-balance";
|
||||||
|
|
||||||
const chatApiLogger = createLogger("chat.imageFailover");
|
const chatApiLogger = createLogger("chat.imageFailover");
|
||||||
|
|
||||||
@ -264,6 +264,29 @@ export function chatMessagesHaveImageInput(messages: ChatMessage[]) {
|
|||||||
return countChatMessageImageInputs(messages) > 0;
|
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) {
|
export function getImageFailoverConvertProvider(providerType?: string | null) {
|
||||||
switch (providerType) {
|
switch (providerType) {
|
||||||
case "bfl-image":
|
case "bfl-image":
|
||||||
@ -326,7 +349,7 @@ export function buildImageFallbackCandidates(
|
|||||||
if (!sameProvider && !IMAGE_FAILOVER_PROVIDER_ALLOWLIST.has(providerType)) {
|
if (!sameProvider && !IMAGE_FAILOVER_PROVIDER_ALLOWLIST.has(providerType)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (isImageFallbackModelCoolingDown(item.model.id) || isImageFallbackModelBalanceCoolingDown(item.model)) {
|
if (isImageFallbackModelCoolingDown(item.model.id) || isImageModelBalanceBlocked(item.model)) {
|
||||||
const cooldown = imageFailoverModelCooldown.get(item.model.id);
|
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"}`);
|
chatApiLogger.info(`[Chat API] ⏭ Skip configured image fallback on cooldown: ${item.model.displayName} (${providerType}) - ${cooldown?.reason || "provider balance cooldown"}`);
|
||||||
return false;
|
return false;
|
||||||
@ -488,7 +511,7 @@ export function getImageCrossProviderCandidates(
|
|||||||
}
|
}
|
||||||
if (m.model.id === options.currentModelId) return false;
|
if (m.model.id === options.currentModelId) return false;
|
||||||
if (options.currentProviderId && m.provider.id === options.currentProviderId) return false;
|
if (options.currentProviderId && m.provider.id === options.currentProviderId) return false;
|
||||||
if (isImageFallbackModelCoolingDown(m.model.id) || isImageFallbackModelBalanceCoolingDown(m.model)) {
|
if (isImageFallbackModelCoolingDown(m.model.id) || isImageModelBalanceBlocked(m.model)) {
|
||||||
const cooldown = imageFailoverModelCooldown.get(m.model.id);
|
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"}`);
|
chatApiLogger.info(`[Chat API] ⏭ Skip image failover model on cooldown: ${m.model.displayName} (${m.provider.type}) - ${cooldown?.reason || "provider balance cooldown"}`);
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
56
app/(chat)/api/chat/_lib/image-generation-failure.ts
Normal file
56
app/(chat)/api/chat/_lib/image-generation-failure.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
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,6 +208,7 @@ export function writeImageGenerationStatusChunk(
|
|||||||
writer: StreamWriter,
|
writer: StreamWriter,
|
||||||
params: {
|
params: {
|
||||||
phase: "queued" | "processing" | "finalizing" | "failed" | "completed";
|
phase: "queued" | "processing" | "finalizing" | "failed" | "completed";
|
||||||
|
userMessageId?: string;
|
||||||
providerType?: string | null;
|
providerType?: string | null;
|
||||||
modelName?: string | null;
|
modelName?: string | null;
|
||||||
imageCount?: number | null;
|
imageCount?: number | null;
|
||||||
@ -223,6 +224,7 @@ export function writeImageGenerationStatusChunk(
|
|||||||
"data-imageGenerationStatus",
|
"data-imageGenerationStatus",
|
||||||
{
|
{
|
||||||
phase: params.phase,
|
phase: params.phase,
|
||||||
|
userMessageId: params.userMessageId,
|
||||||
providerType: normalizeImageLoadingProviderType(params.providerType),
|
providerType: normalizeImageLoadingProviderType(params.providerType),
|
||||||
modelName: String(params.modelName || "").trim() || undefined,
|
modelName: String(params.modelName || "").trim() || undefined,
|
||||||
imageCount:
|
imageCount:
|
||||||
|
|||||||
@ -1,8 +1,11 @@
|
|||||||
|
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 { createLogger } from "@/lib/observability/logger";
|
||||||
|
import { trackRuntimeWork } from "@/lib/observability/active-work";
|
||||||
import { geolocation } from "@vercel/functions";
|
import { geolocation } from "@vercel/functions";
|
||||||
import {
|
import {
|
||||||
convertToModelMessages,
|
convertToModelMessages,
|
||||||
createUIMessageStream,
|
createUIMessageStream as createAiUIMessageStream,
|
||||||
generateText,
|
generateText,
|
||||||
smoothStream,
|
smoothStream,
|
||||||
stepCountIs,
|
stepCountIs,
|
||||||
@ -194,6 +197,7 @@ import {
|
|||||||
} from "@/lib/ai/runtime/agent-media-markdown";
|
} from "@/lib/ai/runtime/agent-media-markdown";
|
||||||
import { extractImageUrlsFromText } from "@/lib/image-url";
|
import { extractImageUrlsFromText } from "@/lib/image-url";
|
||||||
import { saveGeneratedImages } from "@/lib/ai/runtime/generated-image-persistence";
|
import { saveGeneratedImages } from "@/lib/ai/runtime/generated-image-persistence";
|
||||||
|
import { withAuthenticationFailover } from "@/lib/ai/runtime/authentication-failover";
|
||||||
import {
|
import {
|
||||||
recordAiModelHealthFailure,
|
recordAiModelHealthFailure,
|
||||||
recordAiModelHealthSuccess,
|
recordAiModelHealthSuccess,
|
||||||
@ -333,6 +337,8 @@ import {
|
|||||||
} from "./_lib/image-media";
|
} from "./_lib/image-media";
|
||||||
import {
|
import {
|
||||||
buildImageFallbackCandidates,
|
buildImageFallbackCandidates,
|
||||||
|
canUseImageFallback,
|
||||||
|
countChatMessageImageInputs,
|
||||||
generateImageWithFailoverCandidate,
|
generateImageWithFailoverCandidate,
|
||||||
getImageCrossProviderCandidates,
|
getImageCrossProviderCandidates,
|
||||||
IMAGE_FAILOVER_PROVIDER_ALLOWLIST,
|
IMAGE_FAILOVER_PROVIDER_ALLOWLIST,
|
||||||
@ -341,6 +347,8 @@ import {
|
|||||||
setImageFallbackModelCooldown,
|
setImageFallbackModelCooldown,
|
||||||
shouldCooldownImageFallbackModel,
|
shouldCooldownImageFallbackModel,
|
||||||
} from "./_lib/image-failover";
|
} from "./_lib/image-failover";
|
||||||
|
import { isImageModelBalanceBlocked, resolveConfiguredImageBalanceFallback } from "@/lib/ai/runtime/image-balance";
|
||||||
|
import { isProviderBalanceError } from "@/lib/request-error";
|
||||||
import {
|
import {
|
||||||
buildAgentSceneWorkflowPrompt,
|
buildAgentSceneWorkflowPrompt,
|
||||||
buildAgentSlotPrompt,
|
buildAgentSlotPrompt,
|
||||||
@ -419,7 +427,11 @@ import {
|
|||||||
type VideoModeType,
|
type VideoModeType,
|
||||||
} from "./_lib/video-models";
|
} from "./_lib/video-models";
|
||||||
|
|
||||||
|
import { reportImageGenerationFailure } from "./_lib/image-generation-failure";
|
||||||
|
|
||||||
const chatApiLogger = createLogger("chat.route");
|
const chatApiLogger = createLogger("chat.route");
|
||||||
|
const createUIMessageStream: typeof createAiUIMessageStream = (options) =>
|
||||||
|
createAiUIMessageStream({ ...options, execute: (writer) => trackRuntimeWork(() => options.execute(writer)) });
|
||||||
|
|
||||||
const INTERNAL_IMAGE_GENERATION_FAILURE_PATTERN =
|
const INTERNAL_IMAGE_GENERATION_FAILURE_PATTERN =
|
||||||
/生成图片失败|图片生成失败|未找到图片数据|未解析到图片|模型未返回生成图片|图片数据不可用|未返回可用图片/i;
|
/生成图片失败|图片生成失败|未找到图片数据|未解析到图片|模型未返回生成图片|图片数据不可用|未返回可用图片/i;
|
||||||
@ -437,16 +449,6 @@ function assertGeneratedImageMarkdownHasImage(markdown: string, modelLabel: stri
|
|||||||
throw new Error(`${modelLabel} 未返回可用图片:${reason.slice(0, 160)}`);
|
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(
|
const AGENT_REPLACEMENT_PARALLEL_WORKER_COUNT = Math.max(
|
||||||
1,
|
1,
|
||||||
Math.min(8, Number(process.env.AGENT_REPLACEMENT_PARALLEL_WORKER_COUNT || 6) || 6),
|
Math.min(8, Number(process.env.AGENT_REPLACEMENT_PARALLEL_WORKER_COUNT || 6) || 6),
|
||||||
@ -904,6 +906,15 @@ export async function POST(request: Request) {
|
|||||||
const json = await request.json();
|
const json = await request.json();
|
||||||
chatApiLogger.info("[Chat API] Received request body:", JSON.stringify(json, null, 2));
|
chatApiLogger.info("[Chat API] Received request body:", JSON.stringify(json, null, 2));
|
||||||
requestBody = postRequestBodySchema.parse(json);
|
requestBody = postRequestBodySchema.parse(json);
|
||||||
|
// Agent/Auto Agent has one execution owner: the isolated native ZCode entry.
|
||||||
|
// This also upgrades existing browser tabs without routing Claw here.
|
||||||
|
if (requestBody.composerMode === "agent" && requestBody.contextPayload?.source === "canvas" && requestBody.contextPayload.projectId) {
|
||||||
|
const { POST: nativeAgentPost } = await import("@/app/api/canvas/agent-chat/route");
|
||||||
|
return nativeAgentPost(new Request(new URL("/api/canvas/agent-chat", request.url), {
|
||||||
|
method: "POST", headers: request.headers, body: JSON.stringify(json),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
chatApiLogger.error("[Chat API] Schema validation failed:", error);
|
chatApiLogger.error("[Chat API] Schema validation failed:", error);
|
||||||
return new ChatSDKError("bad_request:api").toResponse();
|
return new ChatSDKError("bad_request:api").toResponse();
|
||||||
@ -1198,6 +1209,14 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (shouldRunAgentConversation && preferredAgentModelId && !shouldKeepSelectedModel) {
|
||||||
|
const preferred = await getAiModelById({ id: preferredAgentModelId }).catch(() => null);
|
||||||
|
if (!preferred?.isEnabled || preferred.healthStatus === "auto_disabled") {
|
||||||
|
preferredAgentModelId = undefined;
|
||||||
|
configuredAgentConversationModelId = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (shouldRunAgentConversation && !preferredAgentModelId) {
|
if (shouldRunAgentConversation && !preferredAgentModelId) {
|
||||||
const configuredAgentModel = await getAgentAiModelWithProvider().catch((agentModelError) => {
|
const configuredAgentModel = await getAgentAiModelWithProvider().catch((agentModelError) => {
|
||||||
chatApiLogger.warn("[Chat API] Failed to load configured agent model:", agentModelError);
|
chatApiLogger.warn("[Chat API] Failed to load configured agent model:", agentModelError);
|
||||||
@ -1318,6 +1337,7 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const allowAgentVideoGeneration =
|
const allowAgentVideoGeneration =
|
||||||
|
(contextPayload?.source === "canvas" && inferVideoTaskRequirements(requestTextContent).expectsVideo) ||
|
||||||
Boolean(requestBody.videoParams) ||
|
Boolean(requestBody.videoParams) ||
|
||||||
isVideoProviderType(requestedModelProviderType, requestedModelConfig || undefined);
|
isVideoProviderType(requestedModelProviderType, requestedModelConfig || undefined);
|
||||||
let smartAutoWorkflowDecision:
|
let smartAutoWorkflowDecision:
|
||||||
@ -5661,6 +5681,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
modelName: resolvedModelRef,
|
modelName: resolvedModelRef,
|
||||||
imageCount: replacementReferences.length,
|
imageCount: replacementReferences.length,
|
||||||
@ -6003,6 +6024,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase:
|
phase:
|
||||||
queueStatus.status === "running"
|
queueStatus.status === "running"
|
||||||
? "processing"
|
? "processing"
|
||||||
@ -6158,6 +6180,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: successCount > 0 ? "completed" : "failed",
|
phase: successCount > 0 ? "completed" : "failed",
|
||||||
modelName: resolvedModelDisplayName,
|
modelName: resolvedModelDisplayName,
|
||||||
imageCount: successCount,
|
imageCount: successCount,
|
||||||
@ -6390,6 +6413,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
modelName:
|
modelName:
|
||||||
selectedAgentPreset.defaultModel?.displayName ||
|
selectedAgentPreset.defaultModel?.displayName ||
|
||||||
@ -6941,6 +6965,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase:
|
phase:
|
||||||
queueStatus.status === "running"
|
queueStatus.status === "running"
|
||||||
? "processing"
|
? "processing"
|
||||||
@ -7266,6 +7291,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase:
|
phase:
|
||||||
queueStatus.status === "running"
|
queueStatus.status === "running"
|
||||||
? "processing"
|
? "processing"
|
||||||
@ -7494,6 +7520,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase:
|
phase:
|
||||||
queueStatus.status === "running"
|
queueStatus.status === "running"
|
||||||
? "processing"
|
? "processing"
|
||||||
@ -7812,6 +7839,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: successCount > 0 ? "completed" : "failed",
|
phase: successCount > 0 ? "completed" : "failed",
|
||||||
modelName:
|
modelName:
|
||||||
selectedAgentPreset.defaultModel?.displayName ||
|
selectedAgentPreset.defaultModel?.displayName ||
|
||||||
@ -8021,6 +8049,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
providerType: requestedModelProviderType,
|
providerType: requestedModelProviderType,
|
||||||
modelName: finalModelId,
|
modelName: finalModelId,
|
||||||
@ -8059,6 +8088,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
...directImageStatusPayload,
|
...directImageStatusPayload,
|
||||||
},
|
},
|
||||||
@ -8151,6 +8181,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: requestedModelProviderType,
|
providerType: requestedModelProviderType,
|
||||||
modelName: directImageResult.model,
|
modelName: directImageResult.model,
|
||||||
@ -8171,42 +8202,16 @@ export async function POST(request: Request) {
|
|||||||
);
|
);
|
||||||
} catch (directToolError) {
|
} catch (directToolError) {
|
||||||
chatApiLogger.error("[Chat API] Direct agent image generation failed:", directToolError);
|
chatApiLogger.error("[Chat API] Direct agent image generation failed:", directToolError);
|
||||||
const errorMessage = getDirectAgentToolErrorMessage(
|
const errorMessage = await reportImageGenerationFailure({
|
||||||
"generate_image",
|
writer, chatId: id, userMessageId: message.id,
|
||||||
directToolError,
|
messageId: assistantMessageId, error: directToolError,
|
||||||
);
|
label: "agent:generate_image:error",
|
||||||
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(
|
writeAgentProgressChunk(
|
||||||
writer,
|
writer,
|
||||||
buildDirectAgentImageGenerateFailedProgress(errorMessage),
|
buildDirectAgentImageGenerateFailedProgress(errorMessage),
|
||||||
"agent:generate_image:progress-failed",
|
"agent:generate_image:progress-failed",
|
||||||
);
|
);
|
||||||
writeAssistantTextChunk(
|
|
||||||
writer,
|
|
||||||
"<!-- IMAGE_GENERATION_END -->",
|
|
||||||
"agent:generate_image:end-error",
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
stopDirectImageKeepalive();
|
stopDirectImageKeepalive();
|
||||||
if (stopDirectImageStatus) {
|
if (stopDirectImageStatus) {
|
||||||
@ -8748,6 +8753,19 @@ 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)
|
// 检查是否是 UUID 格式(数据库中的模型 ID)
|
||||||
const isUUID =
|
const isUUID =
|
||||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||||
@ -8865,7 +8883,7 @@ export async function POST(request: Request) {
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join("\n\n");
|
.join("\n\n");
|
||||||
|
|
||||||
const activeRuntimeModelDescriptor = await resolveAgentModelSlotDescriptor(
|
let activeRuntimeModelDescriptor = await resolveAgentModelSlotDescriptor(
|
||||||
resolvedRuntimeModelLookupId,
|
resolvedRuntimeModelLookupId,
|
||||||
).catch(() => null);
|
).catch(() => null);
|
||||||
if (shouldRunAgentConversation && activeRuntimeModelDescriptor) {
|
if (shouldRunAgentConversation && activeRuntimeModelDescriptor) {
|
||||||
@ -9155,6 +9173,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
providerType: (languageModel as any).provider,
|
providerType: (languageModel as any).provider,
|
||||||
modelName: currentModelConfig?.displayName || actualModelId,
|
modelName: currentModelConfig?.displayName || actualModelId,
|
||||||
@ -9198,8 +9217,11 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
// 🆕 尝试备用模型(支持跨服务商切换)
|
// 🆕 尝试备用模型(支持跨服务商切换)
|
||||||
let fallbackSuccess = false;
|
let fallbackSuccess = false;
|
||||||
|
const balanceBlockedProviders = new Set<string>();
|
||||||
|
if (isProviderBalanceError(primaryError) && currentModelConfig?.providerId) balanceBlockedProviders.add(currentModelConfig.providerId);
|
||||||
const triedFallbackModelIds = new Set<string>();
|
const triedFallbackModelIds = new Set<string>();
|
||||||
for (const candidate of fallbackCandidates) {
|
for (const candidate of fallbackCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, buildMessagesForGemini(), balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||||
chatApiLogger.info(`[Chat API] 🔄 Trying fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔄 Trying fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
@ -9221,6 +9243,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Fallback model ${fallbackResult.displayName} succeeded!`);
|
chatApiLogger.info(`[Chat API] ✅ Fallback model ${fallbackResult.displayName} succeeded!`);
|
||||||
break;
|
break;
|
||||||
} catch (fallbackError) {
|
} catch (fallbackError) {
|
||||||
|
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||||
@ -9242,6 +9265,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.warn("[Chat API] Record Gemini fallback health failure failed:", healthError);
|
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);
|
chatApiLogger.error(`[Chat API] ❌ Fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||||
|
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -9273,6 +9297,7 @@ export async function POST(request: Request) {
|
|||||||
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")));
|
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")));
|
||||||
|
|
||||||
for (const candidate of crossProviderCandidates) {
|
for (const candidate of crossProviderCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, buildMessagesForGemini(), balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||||
chatApiLogger.info(`[Chat API] 🔁 Gemini cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔁 Gemini cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
@ -9295,6 +9320,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Gemini cross-provider fallback model ${fallbackResult.displayName} succeeded!`);
|
chatApiLogger.info(`[Chat API] ✅ Gemini cross-provider fallback model ${fallbackResult.displayName} succeeded!`);
|
||||||
break;
|
break;
|
||||||
} catch (fallbackError) {
|
} catch (fallbackError) {
|
||||||
|
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||||
@ -9316,6 +9342,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.warn("[Chat API] Record Gemini cross-provider health failure failed:", healthError);
|
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);
|
chatApiLogger.error(`[Chat API] ❌ Gemini cross-provider fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||||
|
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -9383,6 +9410,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: (languageModel as any).provider,
|
providerType: (languageModel as any).provider,
|
||||||
modelName: usedModelDisplayName,
|
modelName: usedModelDisplayName,
|
||||||
@ -9447,6 +9475,14 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
chatApiLogger.error("[Chat API] Gemini generation error:", 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...");
|
chatApiLogger.info("[Chat API] Attempting failover to Volcano Vision...");
|
||||||
|
|
||||||
// 故障转移:尝试使用火山引擎模型
|
// 故障转移:尝试使用火山引擎模型
|
||||||
@ -9524,6 +9560,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: "volcano-vision",
|
providerType: "volcano-vision",
|
||||||
modelName: volcanoModel.model.displayName || volcanoModel.model.modelId,
|
modelName: volcanoModel.model.displayName || volcanoModel.model.modelId,
|
||||||
@ -9589,46 +9626,14 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info("[Chat API] No Volcano Vision model available for failover");
|
chatApiLogger.info("[Chat API] No Volcano Vision model available for failover");
|
||||||
} catch (failoverError) {
|
} catch (failoverError) {
|
||||||
chatApiLogger.error("[Chat API] Failover to Volcano Vision also failed:", failoverError);
|
chatApiLogger.error("[Chat API] Failover to Volcano Vision also failed:", failoverError);
|
||||||
|
finalError = failoverError;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果故障转移也失败,返回错误消息
|
// 如果故障转移也失败,返回错误消息
|
||||||
const errorMessageId = generateUUID();
|
await reportImageGenerationFailure({
|
||||||
writeAssistantTextChunk(
|
writer, chatId: id, userMessageId: message.id,
|
||||||
writer,
|
messageId: generateUUID(), error: finalError, label: "gemini:error",
|
||||||
"图片生成失败,请稍后重试",
|
});
|
||||||
"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 {
|
} finally {
|
||||||
stopKeepalive?.();
|
stopKeepalive?.();
|
||||||
}
|
}
|
||||||
@ -9826,6 +9831,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "queued",
|
phase: "queued",
|
||||||
providerType: "fal-image",
|
providerType: "fal-image",
|
||||||
modelName: modelDisplayName,
|
modelName: modelDisplayName,
|
||||||
@ -9906,6 +9912,12 @@ export async function POST(request: Request) {
|
|||||||
imageGenConfig: alibabaModelConfig?.imageGenConfig || null,
|
imageGenConfig: alibabaModelConfig?.imageGenConfig || null,
|
||||||
modelDisplayName, // 🆕 传递模型显示名称
|
modelDisplayName, // 🆕 传递模型显示名称
|
||||||
overrideModelId: isRetry ? modelIdToUse : undefined,
|
overrideModelId: isRetry ? modelIdToUse : undefined,
|
||||||
|
onImageGenerationNotice: (notice: string) =>
|
||||||
|
safeWriteStreamChunk(writer, {
|
||||||
|
type: "data-imageGenerationNotice",
|
||||||
|
data: notice,
|
||||||
|
transient: true,
|
||||||
|
}, "alibaba:image-notice"),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (result?.finishReason === "error") {
|
if (result?.finishReason === "error") {
|
||||||
@ -9932,6 +9944,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
providerType: (languageModel as any).provider,
|
providerType: (languageModel as any).provider,
|
||||||
modelName: alibabaModelConfig?.displayName || actualModelId,
|
modelName: alibabaModelConfig?.displayName || actualModelId,
|
||||||
@ -9981,7 +9994,10 @@ export async function POST(request: Request) {
|
|||||||
|
|
||||||
let fallbackSuccess = false;
|
let fallbackSuccess = false;
|
||||||
const triedFallbackModelIds = new Set<string>();
|
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) {
|
for (const candidate of fallbackCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForAlibaba, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||||
chatApiLogger.info(`[Chat API] 🔄 Alibaba fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔄 Alibaba fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
@ -10004,6 +10020,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Alibaba fallback model ${fallbackResult.displayName} succeeded!`);
|
chatApiLogger.info(`[Chat API] ✅ Alibaba fallback model ${fallbackResult.displayName} succeeded!`);
|
||||||
break;
|
break;
|
||||||
} catch (fallbackError) {
|
} catch (fallbackError) {
|
||||||
|
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||||
@ -10025,6 +10042,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.warn("[Chat API] Record image fallback health failure failed:", healthError);
|
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);
|
chatApiLogger.error(`[Chat API] ❌ Alibaba fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||||
|
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -10052,9 +10070,10 @@ export async function POST(request: Request) {
|
|||||||
currentModelKey: actualModelId,
|
currentModelKey: actualModelId,
|
||||||
currentProviderId: alibabaModelConfig?.providerId,
|
currentProviderId: alibabaModelConfig?.providerId,
|
||||||
providerPriority,
|
providerPriority,
|
||||||
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")));
|
}).filter((candidate) => !triedFallbackModelIds.has(String(candidate.model.id || "")) && !balanceBlockedProviders.has(candidate.provider.id));
|
||||||
|
|
||||||
for (const candidate of crossProviderCandidates) {
|
for (const candidate of crossProviderCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForAlibaba, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
triedFallbackModelIds.add(String(candidate.model.id || ""));
|
||||||
chatApiLogger.info(`[Chat API] 🔁 Cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔁 Cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
@ -10136,6 +10155,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] ✅ Cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
break;
|
break;
|
||||||
} catch (crossError) {
|
} catch (crossError) {
|
||||||
|
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||||
@ -10157,6 +10177,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.warn("[Chat API] Record image cross-provider health failure failed:", healthError);
|
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);
|
chatApiLogger.error(`[Chat API] ❌ Cross-provider failover failed: ${candidate.model.displayName} (${candidate.provider.type})`, crossError);
|
||||||
|
if (!shouldFailoverAiModelError(crossError)) throw crossError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -10224,6 +10245,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: (languageModel as any).provider,
|
providerType: (languageModel as any).provider,
|
||||||
modelName: usedModelDisplayName,
|
modelName: usedModelDisplayName,
|
||||||
@ -10288,43 +10310,10 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.error("[Chat API] Alibaba generation error:", error);
|
chatApiLogger.error("[Chat API] Alibaba generation error:", error);
|
||||||
|
|
||||||
// 返回错误消息
|
// 返回错误消息
|
||||||
const errorMessageId = generateUUID();
|
await reportImageGenerationFailure({
|
||||||
const errorText = getPublicImageGenerationErrorText(error);
|
writer, chatId: id, userMessageId: message.id,
|
||||||
writeAssistantTextChunk(
|
messageId: generateUUID(), error, label: "alibaba:error",
|
||||||
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 {
|
} finally {
|
||||||
stopKeepalive?.();
|
stopKeepalive?.();
|
||||||
}
|
}
|
||||||
@ -10453,6 +10442,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
providerType: "volcano-vision",
|
providerType: "volcano-vision",
|
||||||
modelName: volcanoModelConfig?.displayName || actualModelId,
|
modelName: volcanoModelConfig?.displayName || actualModelId,
|
||||||
@ -10471,7 +10461,10 @@ export async function POST(request: Request) {
|
|||||||
throw primaryError;
|
throw primaryError;
|
||||||
}
|
}
|
||||||
let fallbackSuccess = false;
|
let fallbackSuccess = false;
|
||||||
|
const balanceBlockedProviders = new Set<string>();
|
||||||
|
if (isProviderBalanceError(primaryError) && volcanoModelConfig?.providerId) balanceBlockedProviders.add(volcanoModelConfig.providerId);
|
||||||
for (const candidate of fallbackCandidates) {
|
for (const candidate of fallbackCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForVolcano, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
chatApiLogger.info(`[Chat API] 🔄 Volcano fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔄 Volcano fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
const fallbackResult = await generateImageWithFailoverCandidate({
|
const fallbackResult = await generateImageWithFailoverCandidate({
|
||||||
@ -10493,11 +10486,13 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Volcano fallback model ${fallbackResult.displayName} succeeded!`);
|
chatApiLogger.info(`[Chat API] ✅ Volcano fallback model ${fallbackResult.displayName} succeeded!`);
|
||||||
break;
|
break;
|
||||||
} catch (fallbackError) {
|
} catch (fallbackError) {
|
||||||
|
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||||
}
|
}
|
||||||
chatApiLogger.error(`[Chat API] ❌ Volcano fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
chatApiLogger.error(`[Chat API] ❌ Volcano fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||||
|
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!fallbackSuccess) {
|
if (!fallbackSuccess) {
|
||||||
@ -10527,6 +10522,7 @@ export async function POST(request: Request) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
for (const candidate of crossProviderCandidates) {
|
for (const candidate of crossProviderCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForVolcano, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
chatApiLogger.info(`[Chat API] 🔁 Volcano cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔁 Volcano cross-provider failover attempt: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
if (
|
if (
|
||||||
@ -10607,6 +10603,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ Volcano cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] ✅ Volcano cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
break;
|
break;
|
||||||
} catch (crossError) {
|
} catch (crossError) {
|
||||||
|
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||||
@ -10664,6 +10661,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
writer,
|
writer,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: "volcano-vision",
|
providerType: "volcano-vision",
|
||||||
modelName: usedModelDisplayName,
|
modelName: usedModelDisplayName,
|
||||||
@ -10728,43 +10726,10 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
chatApiLogger.error("[Chat API] Volcano Vision generation error:", error);
|
chatApiLogger.error("[Chat API] Volcano Vision generation error:", error);
|
||||||
const errorMessageId = generateUUID();
|
await reportImageGenerationFailure({
|
||||||
writeAssistantTextChunk(
|
writer, chatId: id, userMessageId: message.id,
|
||||||
writer,
|
messageId: generateUUID(), error, label: "volcano:error",
|
||||||
"图片生成失败,请稍后重试",
|
});
|
||||||
"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 {
|
} finally {
|
||||||
stopKeepalive?.();
|
stopKeepalive?.();
|
||||||
}
|
}
|
||||||
@ -11222,7 +11187,7 @@ export async function POST(request: Request) {
|
|||||||
requestHeaders: request.headers,
|
requestHeaders: request.headers,
|
||||||
requestUrl: request.url,
|
requestUrl: request.url,
|
||||||
defaultModelId: finalModelId,
|
defaultModelId: finalModelId,
|
||||||
destructiveConfirmed: isCanvasOperationConfirmText(requestTextContent),
|
authorizeDestructive: (nodeIds) => isExplicitDestructiveIntent(requestTextContent) && nodeIds.length > 0 && nodeIds.every((nodeId) => selectedCanvasImageNodeIds.includes(nodeId)),
|
||||||
callbacks: {
|
callbacks: {
|
||||||
onClientCommand: (command, capability) => {
|
onClientCommand: (command, capability) => {
|
||||||
writeCanvasCapabilityCommandChunk(
|
writeCanvasCapabilityCommandChunk(
|
||||||
@ -11337,6 +11302,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
dataStream as unknown as StreamWriter,
|
dataStream as unknown as StreamWriter,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "processing",
|
phase: "processing",
|
||||||
providerType: currentModelConfig?.providerId ? resolvedProviderType || providerType : providerType,
|
providerType: currentModelConfig?.providerId ? resolvedProviderType || providerType : providerType,
|
||||||
modelName: currentModelConfig?.displayName || actualModelId,
|
modelName: currentModelConfig?.displayName || actualModelId,
|
||||||
@ -11381,7 +11347,10 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let fallbackSuccess = false;
|
let fallbackSuccess = false;
|
||||||
|
const balanceBlockedProviders = new Set<string>();
|
||||||
|
if (isProviderBalanceError(primaryError) && currentModelConfig?.providerId) balanceBlockedProviders.add(currentModelConfig.providerId);
|
||||||
for (const candidate of fallbackCandidates) {
|
for (const candidate of fallbackCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForCrossProvider, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
chatApiLogger.info(`[Chat API] 🔄 OpenAI-compatible fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔄 OpenAI-compatible fallback model: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
const shouldUseOpenAICompatFallback =
|
const shouldUseOpenAICompatFallback =
|
||||||
@ -11423,11 +11392,13 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible fallback model ${candidate.model.displayName} succeeded!`);
|
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible fallback model ${candidate.model.displayName} succeeded!`);
|
||||||
break;
|
break;
|
||||||
} catch (fallbackError) {
|
} catch (fallbackError) {
|
||||||
|
if (isProviderBalanceError(fallbackError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
const fallbackErrorMessage = normalizeFailoverErrorMessage(fallbackError);
|
||||||
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(fallbackErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, fallbackErrorMessage);
|
||||||
}
|
}
|
||||||
chatApiLogger.error(`[Chat API] ❌ OpenAI-compatible fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
chatApiLogger.error(`[Chat API] ❌ OpenAI-compatible fallback model ${candidate.model.displayName} (${candidate.provider.type}) failed:`, fallbackError);
|
||||||
|
if (!shouldFailoverAiModelError(fallbackError)) throw fallbackError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -11458,6 +11429,7 @@ export async function POST(request: Request) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
for (const candidate of crossProviderCandidates) {
|
for (const candidate of crossProviderCandidates) {
|
||||||
|
if (!canUseImageFallback(candidate, effectiveImageGenerationParams, messagesForCrossProvider, balanceBlockedProviders)) continue;
|
||||||
try {
|
try {
|
||||||
chatApiLogger.info(`[Chat API] 🔁 OpenAI-compatible cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] 🔁 OpenAI-compatible cross-provider failover: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
if (
|
if (
|
||||||
@ -11541,6 +11513,7 @@ export async function POST(request: Request) {
|
|||||||
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
chatApiLogger.info(`[Chat API] ✅ OpenAI-compatible cross-provider failover succeeded: ${candidate.model.displayName} (${candidate.provider.type})`);
|
||||||
break;
|
break;
|
||||||
} catch (crossError) {
|
} catch (crossError) {
|
||||||
|
if (isProviderBalanceError(crossError)) balanceBlockedProviders.add(candidate.provider.id);
|
||||||
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
const crossErrorMessage = normalizeFailoverErrorMessage(crossError);
|
||||||
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
if (shouldCooldownImageFallbackModel(crossErrorMessage)) {
|
||||||
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
setImageFallbackModelCooldown(candidate.model.id, crossErrorMessage);
|
||||||
@ -11599,6 +11572,7 @@ export async function POST(request: Request) {
|
|||||||
writeImageGenerationStatusChunk(
|
writeImageGenerationStatusChunk(
|
||||||
dataStream as unknown as StreamWriter,
|
dataStream as unknown as StreamWriter,
|
||||||
{
|
{
|
||||||
|
userMessageId: message.id,
|
||||||
phase: "completed",
|
phase: "completed",
|
||||||
providerType: resolvedProviderType || providerType,
|
providerType: resolvedProviderType || providerType,
|
||||||
modelName: usedModelDisplayName,
|
modelName: usedModelDisplayName,
|
||||||
@ -11658,54 +11632,10 @@ export async function POST(request: Request) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
chatApiLogger.error("[Chat API] OpenAI-compatible image model generation error:", error);
|
chatApiLogger.error("[Chat API] OpenAI-compatible image model generation error:", error);
|
||||||
|
|
||||||
const errorMessageId = generateUUID();
|
await reportImageGenerationFailure({
|
||||||
const errorText = getPublicImageGenerationErrorText(error);
|
writer: dataStream as unknown as StreamWriter,
|
||||||
|
chatId: id, userMessageId: message.id,
|
||||||
dataStream.write({
|
messageId: generateUUID(), error, label: "openai-compat:error",
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
@ -12251,8 +12181,70 @@ export async function POST(request: Request) {
|
|||||||
const shouldDisableSmoothStream =
|
const shouldDisableSmoothStream =
|
||||||
resolvedModelSupportsImageGen || isVolcanoVideoModel;
|
resolvedModelSupportsImageGen || isVolcanoVideoModel;
|
||||||
|
|
||||||
|
let activeConversationModel = currentModelConfig;
|
||||||
|
let activeConversationProvider = currentProviderConfig;
|
||||||
|
const recordedAuthFailures = new Set<string>();
|
||||||
|
const recordConversationAuthFailure = async (error: unknown) => {
|
||||||
|
const key = activeConversationModel?.id;
|
||||||
|
if (!key || recordedAuthFailures.has(key)) return;
|
||||||
|
recordedAuthFailures.add(key);
|
||||||
|
recordProviderHealthFailure({
|
||||||
|
providerKey: activeConversationProvider?.id,
|
||||||
|
providerType: activeConversationProvider?.type,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
await recordAiModelHealthFailure({
|
||||||
|
model: activeConversationModel,
|
||||||
|
provider: activeConversationProvider,
|
||||||
|
error,
|
||||||
|
context: "canvas_agent_conversation_auth",
|
||||||
|
}).catch((healthError) => chatApiLogger.warn("[Chat API] Could not persist model authentication failure:", healthError));
|
||||||
|
};
|
||||||
|
const needsVisionFallback = convertedMessages.some((item: any) =>
|
||||||
|
Array.isArray(item.content) && item.content.some((part: any) =>
|
||||||
|
part.type === "image" || (part.type === "file" && String(part.mediaType || "").startsWith("image/"))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
const streamModel = shouldRunAgentConversation && !shouldKeepSelectedModel &&
|
||||||
|
currentModelConfig?.excludeFromFailover !== true &&
|
||||||
|
!resolvedModelSupportsImageGen && !isVolcanoVideoModel
|
||||||
|
? withAuthenticationFailover({
|
||||||
|
primary: languageModel as any,
|
||||||
|
onAuthenticationFailure: recordConversationAuthFailure,
|
||||||
|
resolveFallback: async () => {
|
||||||
|
const enabled = await getEnabledAiModelsWithProvider(false);
|
||||||
|
const preferredIds = [currentModelConfig?.fallbackModelId1, currentModelConfig?.fallbackModelId2];
|
||||||
|
const candidates = enabled.filter(({ model, provider }) =>
|
||||||
|
model.id !== activeConversationModel?.id && model.isEnabled && provider.isEnabled &&
|
||||||
|
!model.excludeFromFailover && !model.isSubModel && model.healthStatus !== "auto_disabled" &&
|
||||||
|
!isImageGenerationModelType(provider.type, model) && !isVideoProviderType(provider.type, model) &&
|
||||||
|
(!needsVisionFallback || model.supportsVision) &&
|
||||||
|
(isAiModelAgentAuto(model) || preferredIds.includes(model.id)) &&
|
||||||
|
!shouldAvoidProvider(getProviderHealthSnapshot(provider.id))
|
||||||
|
).sort((a, b) => {
|
||||||
|
const rank = (id: string, isDefault: boolean) => {
|
||||||
|
const index = preferredIds.indexOf(id);
|
||||||
|
return index >= 0 ? index : isDefault ? 2 : 3;
|
||||||
|
};
|
||||||
|
return rank(a.model.id, a.model.isDefault) - rank(b.model.id, b.model.isDefault);
|
||||||
|
});
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const fallback = await getLanguageModelById(candidate.model.id);
|
||||||
|
if (!fallback || typeof fallback === "string") continue;
|
||||||
|
activeConversationModel = candidate.model;
|
||||||
|
activeConversationProvider = candidate.provider;
|
||||||
|
finalModelId = candidate.model.id;
|
||||||
|
actualModelId = candidate.model.modelId;
|
||||||
|
activeRuntimeModelDescriptor = await resolveAgentModelSlotDescriptor(candidate.model.id).catch(() => null);
|
||||||
|
return fallback as any;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: languageModel;
|
||||||
const result = streamText({
|
const result = streamText({
|
||||||
model: languageModel,
|
model: streamModel,
|
||||||
|
maxRetries: shouldRunAgentConversation ? 0 : undefined,
|
||||||
system: effectiveConversationSystemPrompt,
|
system: effectiveConversationSystemPrompt,
|
||||||
messages: convertedMessages,
|
messages: convertedMessages,
|
||||||
stopWhen: stepCountIs(shouldUseCanvasCapabilityToolLoop ? 8 : 5),
|
stopWhen: stepCountIs(shouldUseCanvasCapabilityToolLoop ? 8 : 5),
|
||||||
|
|||||||
@ -10,6 +10,10 @@ import {
|
|||||||
} from "@/lib/db/queries";
|
} from "@/lib/db/queries";
|
||||||
import { getAiModelFrontendAvailability } from "@/lib/ai/model-frontend-availability";
|
import { getAiModelFrontendAvailability } from "@/lib/ai/model-frontend-availability";
|
||||||
import { buildVideoToolCapability } from "@/lib/ai/video-tool-capability";
|
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 {
|
import {
|
||||||
isImageGenerationModelDescriptor,
|
isImageGenerationModelDescriptor,
|
||||||
isVideoModelDescriptor,
|
isVideoModelDescriptor,
|
||||||
@ -157,10 +161,17 @@ export async function GET(request: Request) {
|
|||||||
: await getEnabledAiModelsWithProvider(false, true);
|
: await getEnabledAiModelsWithProvider(false, true);
|
||||||
const agentModelWithProvider = await getAgentAiModelWithProvider();
|
const agentModelWithProvider = await getAgentAiModelWithProvider();
|
||||||
const defaultModel = await getDefaultAiModel();
|
const defaultModel = await getDefaultAiModel();
|
||||||
const [siteSettings, agentWorkflowUiConfigSetting] = await Promise.all([
|
const [siteSettings, agentWorkflowUiConfigSetting, detailReplacementModelSetting] = await Promise.all([
|
||||||
getSiteSettings(),
|
getSiteSettings(),
|
||||||
getSystemSetting({ key: AGENT_WORKFLOW_UI_CONFIG_KEY }).catch(() => null),
|
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];
|
type ModelWithProvider = (typeof modelsWithProvider)[number];
|
||||||
const serializeModel = ({ model, provider }: ModelWithProvider) => ({
|
const serializeModel = ({ model, provider }: ModelWithProvider) => ({
|
||||||
id: model.id,
|
id: model.id,
|
||||||
@ -309,6 +320,7 @@ export async function GET(request: Request) {
|
|||||||
: null,
|
: null,
|
||||||
agentWorkflowDefaultModelId: agentWorkflowDefaultModel?.model.id || null,
|
agentWorkflowDefaultModelId: agentWorkflowDefaultModel?.model.id || null,
|
||||||
agentWorkflowConfiguredModels,
|
agentWorkflowConfiguredModels,
|
||||||
|
detailReplacementModel: detailReplacementModel ? serializeModel(detailReplacementModel) : null,
|
||||||
agentModel: agentModelWithProvider
|
agentModel: agentModelWithProvider
|
||||||
? {
|
? {
|
||||||
id: agentModelWithProvider.model.id,
|
id: agentModelWithProvider.model.id,
|
||||||
|
|||||||
@ -8,6 +8,8 @@ import { ArrowLeft, Download, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsR
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { formatBeijingTime } from "@/lib/utils";
|
import { formatBeijingTime } from "@/lib/utils";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||||
|
|
||||||
type FeaturedImage = {
|
type FeaturedImage = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -74,18 +76,11 @@ export default function FeaturedPage() {
|
|||||||
|
|
||||||
const handleDownload = async (url: string, prompt: string) => {
|
const handleDownload = async (url: string, prompt: string) => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url);
|
await downloadOriginalImage({ url, name: "featured-image" });
|
||||||
const blob = await response.blob();
|
toast.success("原图已开始下载");
|
||||||
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) {
|
} catch (error) {
|
||||||
console.error("Download failed:", error);
|
console.error("Download failed:", error);
|
||||||
|
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -3,10 +3,5 @@ export default function FlowBoardLayout({
|
|||||||
}: {
|
}: {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return <>{children}</>;
|
||||||
<>
|
|
||||||
<link href="/vendor/drawnix.css" rel="stylesheet" />
|
|
||||||
{children}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { isRetiredStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
@ -9,9 +10,10 @@ import { Input } from "@/components/ui/input";
|
|||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { requestLongTaskResult } from "@/lib/client/long-task";
|
import { requestLongTaskResult } from "@/lib/client/long-task";
|
||||||
import { buildImageProxyUrl } from "@/lib/image-delivery";
|
import { buildImageProxyUrl, getImageDownloadExtension } from "@/lib/image-delivery";
|
||||||
import { inferOriginalImageUrl } from "@/lib/image-url";
|
import { inferOriginalImageUrl } from "@/lib/image-url";
|
||||||
import { formatBeijingTime } from "@/lib/utils";
|
import { formatBeijingTime } from "@/lib/utils";
|
||||||
|
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||||
|
|
||||||
type GalleryImage = {
|
type GalleryImage = {
|
||||||
id: string;
|
id: string;
|
||||||
@ -32,7 +34,7 @@ type Pagination = {
|
|||||||
totalPages: number;
|
totalPages: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function buildGalleryDownloadFilename(url: string, alt: string) {
|
function buildGalleryDownloadFilename(url: string, alt: string, contentType: string) {
|
||||||
const rawUrl = String(url || "").trim();
|
const rawUrl = String(url || "").trim();
|
||||||
const rawAlt = String(alt || "").trim();
|
const rawAlt = String(alt || "").trim();
|
||||||
const safeBase =
|
const safeBase =
|
||||||
@ -58,7 +60,7 @@ function buildGalleryDownloadFilename(url: string, alt: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${safeBase}-${Date.now()}.${extension}`;
|
return `${safeBase}.${getImageDownloadExtension(contentType) || extension}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function GalleryPage() {
|
export default function GalleryPage() {
|
||||||
@ -103,7 +105,7 @@ export default function GalleryPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDownload = async (url: string, alt: string) => {
|
const handleDownload = async (url: string, alt: string) => {
|
||||||
const originalUrl = inferOriginalImageUrl(String(url || "").trim());
|
const originalUrl = String(url || "").trim();
|
||||||
if (!originalUrl) {
|
if (!originalUrl) {
|
||||||
toast.error("图片地址无效");
|
toast.error("图片地址无效");
|
||||||
return;
|
return;
|
||||||
@ -112,32 +114,17 @@ export default function GalleryPage() {
|
|||||||
try {
|
try {
|
||||||
toast.info("正在准备下载...");
|
toast.info("正在准备下载...");
|
||||||
|
|
||||||
const response = await fetch(
|
// Validate the supplied URL before any legacy thumbnail inference can
|
||||||
buildImageProxyUrl(originalUrl, { delivery: "proxy" })
|
// remove signed storage transformation parameters.
|
||||||
);
|
buildImageProxyUrl(originalUrl, { delivery: "original" });
|
||||||
if (!response.ok) {
|
const parsed = new URL(originalUrl, window.location.origin);
|
||||||
throw new Error(`download failed: ${response.status}`);
|
const source = parsed.pathname === "/api/image-proxy" ? originalUrl : inferOriginalImageUrl(originalUrl);
|
||||||
}
|
|
||||||
const blob = await response.blob();
|
await downloadOriginalImage({ url: source, name: buildGalleryDownloadFilename(originalUrl, alt, "") });
|
||||||
const blobUrl = window.URL.createObjectURL(blob);
|
|
||||||
const link = document.createElement("a");
|
|
||||||
link.href = blobUrl;
|
|
||||||
link.download = buildGalleryDownloadFilename(originalUrl, alt);
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
document.body.removeChild(link);
|
|
||||||
window.setTimeout(() => window.URL.revokeObjectURL(blobUrl), 1000);
|
|
||||||
toast.success("图片已开始下载");
|
toast.success("图片已开始下载");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Download failed:", error);
|
console.error("Download failed:", error);
|
||||||
const fallbackLink = document.createElement("a");
|
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||||
fallbackLink.href = originalUrl;
|
|
||||||
fallbackLink.target = "_blank";
|
|
||||||
fallbackLink.rel = "noopener noreferrer";
|
|
||||||
document.body.appendChild(fallbackLink);
|
|
||||||
fallbackLink.click();
|
|
||||||
document.body.removeChild(fallbackLink);
|
|
||||||
toast.error("下载失败,已为你打开原图,可直接另存为");
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -156,57 +143,28 @@ export default function GalleryPage() {
|
|||||||
try {
|
try {
|
||||||
toast.info("正在处理抠图,请稍候...");
|
toast.info("正在处理抠图,请稍候...");
|
||||||
|
|
||||||
// 获取原图并转换为Base64
|
const imageUrl = new URL(image.url, window.location.origin).href;
|
||||||
const response = await fetch(image.url);
|
const response = await fetch("/api/rmbg", {
|
||||||
const blob = await response.blob();
|
method: "POST",
|
||||||
const reader = new FileReader();
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
reader.onloadend = async () => {
|
imageUrl,
|
||||||
try {
|
prompt: `抠图处理 - ${image.alt}`,
|
||||||
const base64Data = (reader.result as string).split(",")[1];
|
chatId: image.chatId,
|
||||||
|
messageId: image.messageId,
|
||||||
// 调用抠图API
|
includeBase64: false,
|
||||||
const rmbgResponse = await fetch("/api/rmbg", {
|
}),
|
||||||
method: "POST",
|
});
|
||||||
headers: {
|
const result = await response.json();
|
||||||
"Content-Type": "application/json",
|
if (!response.ok || !result.success) {
|
||||||
},
|
throw new Error(result.error || result.detail || "抠图失败");
|
||||||
body: JSON.stringify({
|
}
|
||||||
image_base64: base64Data,
|
await fetchImages(pagination.page);
|
||||||
prompt: `抠图处理 - ${image.alt}`,
|
toast.success(`抠图完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
|
||||||
chatId: image.chatId,
|
|
||||||
messageId: image.messageId,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!rmbgResponse.ok) {
|
|
||||||
const error = await rmbgResponse.json();
|
|
||||||
throw new Error(error.error || error.detail || "抠图失败");
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await rmbgResponse.json();
|
|
||||||
|
|
||||||
// 刷新相册列表以显示新图片
|
|
||||||
await fetchImages(pagination.page);
|
|
||||||
|
|
||||||
toast.success(`抠图完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[抠图] 错误:", error);
|
|
||||||
toast.error(error instanceof Error ? error.message : "抠图处理失败");
|
|
||||||
} finally {
|
|
||||||
setProcessingImageId(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
reader.onerror = () => {
|
|
||||||
toast.error("图片读取失败");
|
|
||||||
setProcessingImageId(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
reader.readAsDataURL(blob);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[抠图] 错误:", error);
|
console.error("[抠图] 错误:", error);
|
||||||
toast.error(error instanceof Error ? error.message : "抠图处理失败");
|
toast.error(error instanceof Error ? error.message : "抠图处理失败");
|
||||||
|
} finally {
|
||||||
setProcessingImageId(null);
|
setProcessingImageId(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -221,51 +179,23 @@ export default function GalleryPage() {
|
|||||||
try {
|
try {
|
||||||
toast.info("正在处理图片变清晰,请稍候...");
|
toast.info("正在处理图片变清晰,请稍候...");
|
||||||
|
|
||||||
// 获取原图并转换为Base64
|
const imageUrl = new URL(image.url, window.location.origin).href;
|
||||||
const response = await fetch(image.url);
|
const prompt = `图片变清晰处理 - ${image.alt}`;
|
||||||
const blob = await response.blob();
|
const { chatId, messageId } = image;
|
||||||
const reader = new FileReader();
|
const result = await requestLongTaskResult({
|
||||||
|
endpoint: "/api/enhance",
|
||||||
reader.onloadend = async () => {
|
payload: { imageUrl, prompt, chatId, messageId, includeBase64: false },
|
||||||
try {
|
pollingParams: { sourceImageUrl: imageUrl, prompt, chatId, messageId, includeBase64: "false" },
|
||||||
const base64Data = (reader.result as string).split(",")[1];
|
});
|
||||||
|
if (!result?.success) {
|
||||||
const result = await requestLongTaskResult({
|
throw new Error(result?.error || result?.detail || "变清晰处理失败");
|
||||||
endpoint: "/api/enhance",
|
}
|
||||||
payload: {
|
await fetchImages(pagination.page);
|
||||||
image_base64: base64Data,
|
toast.success(`变清晰完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
|
||||||
prompt: `图片变清晰处理 - ${image.alt}`,
|
|
||||||
chatId: image.chatId,
|
|
||||||
messageId: image.messageId,
|
|
||||||
},
|
|
||||||
pollingParams: {
|
|
||||||
prompt: `图片变清晰处理 - ${image.alt}`,
|
|
||||||
chatId: image.chatId,
|
|
||||||
messageId: image.messageId,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// 刷新相册列表以显示新图片
|
|
||||||
await fetchImages(pagination.page);
|
|
||||||
|
|
||||||
toast.success(`变清晰完成!处理时间: ${result.processing_time?.toFixed(2) || "未知"}秒`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[变清晰] 错误:", error);
|
|
||||||
toast.error(error instanceof Error ? error.message : "变清晰处理失败");
|
|
||||||
} finally {
|
|
||||||
setEnhancingImageId(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
reader.onerror = () => {
|
|
||||||
toast.error("图片读取失败");
|
|
||||||
setEnhancingImageId(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
reader.readAsDataURL(blob);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[变清晰] 错误:", error);
|
console.error("[变清晰] 错误:", error);
|
||||||
toast.error(error instanceof Error ? error.message : "变清晰处理失败");
|
toast.error(error instanceof Error ? error.message : "变清晰处理失败");
|
||||||
|
} finally {
|
||||||
setEnhancingImageId(null);
|
setEnhancingImageId(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -317,7 +247,12 @@ export default function GalleryPage() {
|
|||||||
<>
|
<>
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="flex flex-wrap justify-center gap-6 px-4">
|
<div className="flex flex-wrap justify-center gap-6 px-4">
|
||||||
{images.map((img) => (
|
{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>
|
||||||
|
) : (
|
||||||
<div
|
<div
|
||||||
key={img.id}
|
key={img.id}
|
||||||
className="group relative cursor-pointer rounded-lg border bg-muted overflow-hidden transition-all hover:shadow-lg hover:scale-105"
|
className="group relative cursor-pointer rounded-lg border bg-muted overflow-hidden transition-all hover:shadow-lg hover:scale-105"
|
||||||
@ -326,7 +261,7 @@ export default function GalleryPage() {
|
|||||||
>
|
>
|
||||||
<div className="relative w-full h-full">
|
<div className="relative w-full h-full">
|
||||||
<Image
|
<Image
|
||||||
src={img.thumbnailUrl || img.url}
|
src={isRetiredStorageUrl(img.thumbnailUrl) ? img.url : img.thumbnailUrl || img.url}
|
||||||
alt={img.alt}
|
alt={img.alt}
|
||||||
width={200}
|
width={200}
|
||||||
height={270}
|
height={270}
|
||||||
|
|||||||
@ -1,8 +1,10 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { requireAdmin } from "@/lib/middleware/admin";
|
import { requireAdmin } from "@/lib/middleware/admin";
|
||||||
import { ChatSDKError } from "@/lib/errors";
|
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 {
|
import {
|
||||||
listAiModelHealthEvents,
|
|
||||||
restoreAiModelHealth,
|
restoreAiModelHealth,
|
||||||
} from "@/lib/ai/runtime/model-health";
|
} from "@/lib/ai/runtime/model-health";
|
||||||
|
|
||||||
@ -15,14 +17,30 @@ export async function GET(request: Request) {
|
|||||||
await requireAdmin();
|
await requireAdmin();
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const modelId = searchParams.get("modelId") || undefined;
|
const modelId = searchParams.get("modelId");
|
||||||
const limit = Number(searchParams.get("limit") || 80);
|
const providerId = searchParams.get("providerId");
|
||||||
const events = await listAiModelHealthEvents({
|
const rawLimit = Number(searchParams.get("limit") || 20);
|
||||||
modelId,
|
const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(200, Math.floor(rawLimit))) : 20;
|
||||||
limit: Number.isFinite(limit) ? limit : 80,
|
const rawPage = Number(searchParams.get("page") || 1);
|
||||||
});
|
const page = Number.isFinite(rawPage) ? Math.max(1, Math.floor(rawPage)) : 1;
|
||||||
|
const filters = [];
|
||||||
return Response.json({ events });
|
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 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ChatSDKError) {
|
if (error instanceof ChatSDKError) {
|
||||||
return error.toResponse();
|
return error.toResponse();
|
||||||
|
|||||||
@ -1,9 +1,10 @@
|
|||||||
import { z } from "zod";
|
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 { requireAdmin } from "@/lib/middleware/admin";
|
||||||
import {
|
import {
|
||||||
getAllAiModels,
|
|
||||||
getAiModelById,
|
getAiModelById,
|
||||||
getAiModelsByProviderId,
|
|
||||||
createAiModel,
|
createAiModel,
|
||||||
updateAiModel,
|
updateAiModel,
|
||||||
deleteAiModel,
|
deleteAiModel,
|
||||||
@ -154,8 +155,14 @@ export async function GET(request: Request) {
|
|||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
const providerId = searchParams.get("providerId");
|
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) {
|
if (id) {
|
||||||
const model = await getAiModelById({ id });
|
const model = await db.query.aiModel.findFirst({ where: eq(aiModel.id, id) });
|
||||||
if (!model) {
|
if (!model) {
|
||||||
return new ChatSDKError("bad_request:api", "Model not found").toResponse();
|
return new ChatSDKError("bad_request:api", "Model not found").toResponse();
|
||||||
}
|
}
|
||||||
@ -163,12 +170,19 @@ export async function GET(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (providerId) {
|
if (providerId) {
|
||||||
const models = await getAiModelsByProviderId({ providerId });
|
const models = await db.select().from(aiModel).where(eq(aiModel.providerId, providerId));
|
||||||
return Response.json({ models: sortModelsForDisplay(models.map(normalizeModel)) });
|
return Response.json({ models: sortModelsForDisplay(models.map(normalizeModel)) });
|
||||||
}
|
}
|
||||||
|
|
||||||
const models = await getAllAiModels();
|
const models = await db.select().from(aiModel);
|
||||||
return Response.json({ models: sortModelsForDisplay(models.map(normalizeModel)) });
|
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) });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ChatSDKError) {
|
if (error instanceof ChatSDKError) {
|
||||||
return error.toResponse();
|
return error.toResponse();
|
||||||
|
|||||||
@ -1,237 +1,31 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { chat, generatedImage, message, user } from "@/lib/db/schema";
|
import { generatedImage, user } from "@/lib/db/schema";
|
||||||
import { eq, desc, sql, and, gte, lte, like, or, isNotNull } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { requireAdmin } from "@/lib/middleware/admin";
|
||||||
function extractVideoUrlFromParts(parts: unknown): string | null {
|
import { ChatSDKError } from "@/lib/errors";
|
||||||
const text = Array.isArray(parts)
|
import { mediaRecordsQuery, parseMediaQuery } from "@/lib/admin/media-records";
|
||||||
? parts
|
import { resolveArchivedImageUrls } from "@/lib/storage/image-archive-db";
|
||||||
.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) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await auth();
|
const session = await requireAdmin();
|
||||||
|
const operator = await db.query.user.findFirst({ where: eq(user.id, session.user.id) });
|
||||||
if (!session?.user?.id) {
|
if (operator?.role !== "admin") return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
const query = parseMediaQuery(request.nextUrl.searchParams);
|
||||||
|
if (query.startDate && query.endDate && query.startDate > query.endDate) {
|
||||||
|
return NextResponse.json({ error: "开始日期不能晚于结束日期" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
const [result] = await db.execute(mediaRecordsQuery(query));
|
||||||
// 检查是否为管理员
|
const images = await resolveArchivedImageUrls(result.records);
|
||||||
const currentUser = await db.query.user.findFirst({
|
const total = Number(result.total);
|
||||||
where: eq(user.id, session.user.id),
|
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) } });
|
||||||
|
|
||||||
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) {
|
} catch (error) {
|
||||||
console.error("[Admin Images API] Error:", error);
|
if (error instanceof ChatSDKError) return error.toResponse();
|
||||||
return NextResponse.json({ error: "Failed to fetch images" }, { status: 500 });
|
console.error("[Admin Images API] GET failed", error);
|
||||||
|
return NextResponse.json({ error: "记录加载失败,请重试" }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
31
app/api/admin/media-tasks/route.ts
Normal file
31
app/api/admin/media-tasks/route.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
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,6 +106,22 @@ export async function POST(request: Request) {
|
|||||||
? catalogPresets.filter((preset) => existingModelIds.has(preset.modelId))
|
? catalogPresets.filter((preset) => existingModelIds.has(preset.modelId))
|
||||||
: catalogPresets;
|
: 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 addedModels: AiModel[] = [];
|
||||||
const updatedModels: AiModel[] = [];
|
const updatedModels: AiModel[] = [];
|
||||||
const disabledModels: AiModel[] = [];
|
const disabledModels: AiModel[] = [];
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { desc, eq } from "drizzle-orm";
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
|
import { z } from "zod";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { canvasProject } from "@/lib/db/schema";
|
import { canvasProject } from "@/lib/db/schema";
|
||||||
@ -56,14 +57,20 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const body = await request.json().catch(() => ({}));
|
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 title = String(body.title || "").trim() || "未命名生图项目";
|
||||||
const description = String(body.description || "").trim() || null;
|
const description = String(body.description || "").trim() || null;
|
||||||
const thumbnail = String(body.thumbnail || "").trim() || null;
|
const thumbnail = String(body.thumbnail || "").trim() || null;
|
||||||
const projectState = normalizeAgentGenerationProjectPersistedState(body.projectState);
|
const projectState = normalizeAgentGenerationProjectPersistedState(body.projectState);
|
||||||
|
|
||||||
const [project] = await db
|
const [insertedProject] = await db
|
||||||
.insert(canvasProject)
|
.insert(canvasProject)
|
||||||
.values({
|
.values({
|
||||||
|
id,
|
||||||
userId: session.user.id,
|
userId: session.user.id,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
@ -78,8 +85,22 @@ export async function POST(request: NextRequest) {
|
|||||||
agentProjectState: projectState,
|
agentProjectState: projectState,
|
||||||
} as any,
|
} as any,
|
||||||
})
|
})
|
||||||
|
.onConflictDoNothing({ target: canvasProject.id })
|
||||||
.returning();
|
.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) });
|
return NextResponse.json({ success: true, data: mapAgentProjectRow(project) });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[AgentProjects API] 创建项目失败:", error);
|
console.error("[AgentProjects API] 创建项目失败:", error);
|
||||||
|
|||||||
@ -450,7 +450,7 @@ async function analyzeFunctionalShowcaseImage(params: {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
temperature: 0,
|
temperature: 0,
|
||||||
maxTokens: 120,
|
maxOutputTokens: 120,
|
||||||
abortSignal: AbortSignal.timeout(25_000),
|
abortSignal: AbortSignal.timeout(25_000),
|
||||||
} as any);
|
} as any);
|
||||||
|
|
||||||
|
|||||||
@ -110,6 +110,7 @@ export async function POST(request: NextRequest) {
|
|||||||
const result = await executeRmbgJob({
|
const result = await executeRmbgJob({
|
||||||
userId: session.user.id,
|
userId: session.user.id,
|
||||||
imageBuffer,
|
imageBuffer,
|
||||||
|
includeBase64: false,
|
||||||
prompt,
|
prompt,
|
||||||
skipGallerySave: true,
|
skipGallerySave: true,
|
||||||
});
|
});
|
||||||
|
|||||||
20
app/api/agent-workflow/template-prompts/route.ts
Normal file
20
app/api/agent-workflow/template-prompts/route.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
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,6 +4,7 @@ import { auth } from "@/app/(auth)/auth";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { canvasImageTask, canvasProject, message } from "@/lib/db/schema";
|
import { canvasImageTask, canvasProject, message } from "@/lib/db/schema";
|
||||||
import { extractAgentProjectStateFromCanvasData, isAgentProjectRow } from "@/lib/agents/agent-project-compat";
|
import { extractAgentProjectStateFromCanvasData, isAgentProjectRow } from "@/lib/agents/agent-project-compat";
|
||||||
|
import { MAX_DETAIL_REPLACEMENT_REFERENCES } from "@/lib/agents/mode-workspace-state";
|
||||||
import {
|
import {
|
||||||
createCanvasImageTask,
|
createCanvasImageTask,
|
||||||
enqueueCanvasImageTask,
|
enqueueCanvasImageTask,
|
||||||
@ -146,6 +147,14 @@ export async function POST(request: Request) {
|
|||||||
.map((item) => [String(item.id), String(item.imageUrl)]),
|
.map((item) => [String(item.id), String(item.imageUrl)]),
|
||||||
);
|
);
|
||||||
const requested = Array.isArray(body.references) ? body.references : [];
|
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 references: DetailReplacementBatchReference[] = requested.map((raw: unknown) => {
|
||||||
const item = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
|
const item = raw && typeof raw === "object" ? raw as Record<string, unknown> : {};
|
||||||
return {
|
return {
|
||||||
@ -160,7 +169,6 @@ export async function POST(request: Request) {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
if (
|
if (
|
||||||
references.length === 0 || references.length > 40 ||
|
|
||||||
new Set(references.map((item) => item.id)).size !== references.length ||
|
new Set(references.map((item) => item.id)).size !== references.length ||
|
||||||
references.some((item) => !item.id || knownReferences.get(item.id) !== item.imageUrl)
|
references.some((item) => !item.id || knownReferences.get(item.id) !== item.imageUrl)
|
||||||
) {
|
) {
|
||||||
@ -187,6 +195,12 @@ export async function POST(request: Request) {
|
|||||||
if (!model || model === "auto" || !models.some((entry) => entry.model.id === model)) {
|
if (!model || model === "auto" || !models.some((entry) => entry.model.id === model)) {
|
||||||
return NextResponse.json({ error: "详情替换模型不可用,请检查模型配置" }, { status: 400 });
|
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);
|
const quota = await checkUserImageQuota(session.user.id);
|
||||||
if (!quota.allowed) {
|
if (!quota.allowed) {
|
||||||
return NextResponse.json({ error: "本月图片生成配额已用完" }, { status: 429 });
|
return NextResponse.json({ error: "本月图片生成配额已用完" }, { status: 429 });
|
||||||
|
|||||||
8
app/api/app-version/route.ts
Normal file
8
app/api/app-version/route.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
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,4 +1,5 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { buildThreeAssetUrl } from "@/lib/canvas/three-asset-url";
|
import { buildThreeAssetUrl } from "@/lib/canvas/three-asset-url";
|
||||||
|
|
||||||
@ -12,7 +13,6 @@ const ALLOWED_MODEL_HOST_DOMAINS = [
|
|||||||
"tripo3d.ai",
|
"tripo3d.ai",
|
||||||
"tripo3d.com",
|
"tripo3d.com",
|
||||||
"worldlabs.ai",
|
"worldlabs.ai",
|
||||||
"s3.1080p.hk",
|
|
||||||
"img.yydd.ai",
|
"img.yydd.ai",
|
||||||
"scqny.jiansun.vip",
|
"scqny.jiansun.vip",
|
||||||
"blob.vercel-storage.com",
|
"blob.vercel-storage.com",
|
||||||
@ -25,7 +25,6 @@ const ALLOWED_MODEL_HOST_DOMAINS = [
|
|||||||
|
|
||||||
const ALLOWED_HTTP_MODEL_HOST_DOMAINS = [
|
const ALLOWED_HTTP_MODEL_HOST_DOMAINS = [
|
||||||
"bbyy.ai",
|
"bbyy.ai",
|
||||||
"s3.1080p.hk",
|
|
||||||
"img.yydd.ai",
|
"img.yydd.ai",
|
||||||
];
|
];
|
||||||
|
|
||||||
@ -165,6 +164,9 @@ async function handleRequest(request: Request, method: "GET" | "HEAD") {
|
|||||||
|
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const rawUrl = String(searchParams.get("url") || "").trim();
|
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) {
|
if (!rawUrl) {
|
||||||
return NextResponse.json({ success: false, error: "缺少 url 参数" }, { status: 400 });
|
return NextResponse.json({ success: false, error: "缺少 url 参数" }, { status: 400 });
|
||||||
}
|
}
|
||||||
@ -180,6 +182,18 @@ async function handleRequest(request: Request, method: "GET" | "HEAD") {
|
|||||||
return NextResponse.json({ success: false, error: "仅支持 http/https 模型地址" }, { status: 400 });
|
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)) {
|
if (!isAllowedModelHost(targetUrl.hostname)) {
|
||||||
return NextResponse.json({ success: false, error: "不允许的模型地址域名" }, { status: 403 });
|
return NextResponse.json({ success: false, error: "不允许的模型地址域名" }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,12 +2,14 @@ import { NextResponse } from "next/server";
|
|||||||
import { ZodError } from "zod";
|
import { ZodError } from "zod";
|
||||||
|
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { RmbgServiceError } from "@/lib/ai/rmbg/service";
|
||||||
import { canvasCapabilityClientCommandSchema } from "@/lib/canvas/capabilities/client-command";
|
import { canvasCapabilityClientCommandSchema } from "@/lib/canvas/capabilities/client-command";
|
||||||
import { CanvasCapabilityRuntimeError } from "@/lib/canvas/capabilities/context";
|
import { CanvasCapabilityRuntimeError } from "@/lib/canvas/capabilities/context";
|
||||||
import { getCanvasCapabilityManifest } from "@/lib/canvas/capabilities/registry";
|
import { getCanvasCapabilityManifest } from "@/lib/canvas/capabilities/registry";
|
||||||
import { executeCanvasCapabilityRuntime } from "@/lib/canvas/capabilities/runtime";
|
import { executeCanvasCapabilityRuntime } from "@/lib/canvas/capabilities/runtime";
|
||||||
import { getCanvasCapabilityTask } from "@/lib/canvas/capabilities/task-store";
|
import { getCanvasCapabilityTask } from "@/lib/canvas/capabilities/task-store";
|
||||||
import { CanvasAgentMutationError } from "@/lib/canvas/agent-mutations";
|
import { CanvasAgentMutationError } from "@/lib/canvas/agent-mutations";
|
||||||
|
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const maxDuration = 600;
|
export const maxDuration = 600;
|
||||||
@ -39,7 +41,8 @@ export async function GET(
|
|||||||
{ status: 404 }
|
{ status: 404 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return NextResponse.json({ success: true, task });
|
const failure = task.status === "failed" ? getRequestFailureDetails(task.error) : undefined;
|
||||||
|
return NextResponse.json({ success: true, task: { ...task, failure, error: failure ? formatRequestFailure(failure, task.requestId) : task.error } });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
@ -51,9 +54,11 @@ export async function POST(
|
|||||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let requestId: string | undefined;
|
||||||
try {
|
try {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const command = canvasCapabilityClientCommandSchema.parse(await request.json());
|
const command = canvasCapabilityClientCommandSchema.parse(await request.json());
|
||||||
|
requestId = command.requestId;
|
||||||
const result = await executeCanvasCapabilityRuntime({
|
const result = await executeCanvasCapabilityRuntime({
|
||||||
command,
|
command,
|
||||||
projectId: id,
|
projectId: id,
|
||||||
@ -67,8 +72,9 @@ export async function POST(
|
|||||||
error instanceof CanvasCapabilityRuntimeError ||
|
error instanceof CanvasCapabilityRuntimeError ||
|
||||||
error instanceof CanvasAgentMutationError
|
error instanceof CanvasAgentMutationError
|
||||||
) {
|
) {
|
||||||
|
const failure = getRequestFailureDetails(error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, error: error.message, code: error.code },
|
{ success: false, error: formatRequestFailure(failure, requestId), code: error.code, failure, requestId },
|
||||||
{ status: error.status }
|
{ status: error.status }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -82,10 +88,10 @@ export async function POST(
|
|||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const message = error instanceof Error ? error.message : "执行画布能力失败";
|
const failure = getRequestFailureDetails(error, "执行画布能力失败");
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, error: message },
|
{ success: false, error: formatRequestFailure(failure, requestId), failure, requestId },
|
||||||
{ status: 500 }
|
{ status: error instanceof RmbgServiceError ? error.status : 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
app/api/canvas/[id]/feedback/route.ts
Normal file
12
app/api/canvas/[id]/feedback/route.ts
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import { feedbackGet, feedbackPost } from "@/lib/canvas/feedback-route";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
return feedbackPost(request, (await params).id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
return feedbackGet(request, (await params).id);
|
||||||
|
}
|
||||||
65
app/api/canvas/[id]/image-archives/route.ts
Normal file
65
app/api/canvas/[id]/image-archives/route.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { canvasProject, imageArchiveTask, generatedImage, canvasImageTask } from "@/lib/db/schema";
|
||||||
|
import { imageArchiveSourceKey } from "@/lib/storage/image-archive-db";
|
||||||
|
import { isGeneratedImageSource } from "@/lib/storage/image-archive-urls";
|
||||||
|
import { scheduleImageArchiveWorker } from "@/lib/storage/image-archive-worker";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
const { id } = await params;
|
||||||
|
const [project] = await db
|
||||||
|
.select({ id: canvasProject.id })
|
||||||
|
.from(canvasProject)
|
||||||
|
.where(and(eq(canvasProject.id, id), eq(canvasProject.userId, session.user.id)))
|
||||||
|
.limit(1);
|
||||||
|
if (!project) return NextResponse.json({ error: "画布不存在" }, { status: 404 });
|
||||||
|
const body = await request.json();
|
||||||
|
if (
|
||||||
|
!Array.isArray(body.urls) ||
|
||||||
|
body.urls.length > 100 ||
|
||||||
|
body.urls.some((url: unknown) => typeof url !== "string" || !isGeneratedImageSource(url))
|
||||||
|
) {
|
||||||
|
return NextResponse.json({ error: "图片地址格式错误" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const urls: string[] = [...new Set<string>(body.urls)];
|
||||||
|
if (!urls.length) return NextResponse.json({ replacements: {}, pending: [] });
|
||||||
|
const source = imageArchiveTask.sourceUrl;
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
sourceUrl: imageArchiveTask.sourceUrl,
|
||||||
|
targetUrl: imageArchiveTask.targetUrl,
|
||||||
|
status: imageArchiveTask.status,
|
||||||
|
})
|
||||||
|
.from(imageArchiveTask)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
inArray(imageArchiveTask.sourceUrl, urls.map(imageArchiveSourceKey)),
|
||||||
|
sql`(
|
||||||
|
exists (select 1 from ${generatedImage} where ${generatedImage.userId} = ${session.user.id}
|
||||||
|
and (${generatedImage.originalUrl} = ${source} or ${generatedImage.thumbnailUrl} = ${source}
|
||||||
|
or ${generatedImage.originalUrl} = ${imageArchiveTask.targetUrl} or ${generatedImage.thumbnailUrl} = ${imageArchiveTask.targetUrl}))
|
||||||
|
or exists (select 1 from ${canvasImageTask} where ${canvasImageTask.userId} = ${session.user.id}
|
||||||
|
and (position(${source} in ${canvasImageTask.result}::text) > 0 or position(${imageArchiveTask.targetUrl} in ${canvasImageTask.result}::text) > 0))
|
||||||
|
or exists (select 1 from ${canvasProject} where ${canvasProject.id} = ${id} and ${canvasProject.userId} = ${session.user.id}
|
||||||
|
and (position(${source} in ${canvasProject.canvasData}::text) > 0 or position(${imageArchiveTask.targetUrl} in ${canvasProject.canvasData}::text) > 0))
|
||||||
|
)`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const byKey = new Map(rows.map((row) => [row.sourceUrl, row]));
|
||||||
|
const replacements: Record<string, string> = {};
|
||||||
|
const pending: string[] = [];
|
||||||
|
for (const url of urls) {
|
||||||
|
const row = byKey.get(imageArchiveSourceKey(url));
|
||||||
|
if (row?.targetUrl) replacements[url] = row.targetUrl;
|
||||||
|
else if (row && row.status !== "abandoned") pending.push(url);
|
||||||
|
}
|
||||||
|
if (rows.some((row) => row.status === "pending")) scheduleImageArchiveWorker(true);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ replacements, pending },
|
||||||
|
{ headers: { "Cache-Control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -3,6 +3,7 @@ import { auth } from '@/app/(auth)/auth';
|
|||||||
import { db } from '@/lib/db';
|
import { db } from '@/lib/db';
|
||||||
import { canvasProject } from '@/lib/db/schema';
|
import { canvasProject } from '@/lib/db/schema';
|
||||||
import { syncCanvasNodesForProject } from '@/lib/db/queries';
|
import { syncCanvasNodesForProject } from '@/lib/db/queries';
|
||||||
|
import { resolveArchivedImageUrls } from '@/lib/storage/image-archive-db';
|
||||||
import { eq, and } from 'drizzle-orm';
|
import { eq, and } from 'drizzle-orm';
|
||||||
import {
|
import {
|
||||||
buildStaleCanvasSaveConflictPayload,
|
buildStaleCanvasSaveConflictPayload,
|
||||||
@ -122,7 +123,8 @@ export async function PUT(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { title, description, thumbnail, canvasData } = body;
|
const { title, description, canvasData } = body;
|
||||||
|
const thumbnail = await resolveArchivedImageUrls(body.thumbnail);
|
||||||
const baseCanvasRevision =
|
const baseCanvasRevision =
|
||||||
body?.baseCanvasUpdatedAt || body?.baseCanvasRevision;
|
body?.baseCanvasUpdatedAt || body?.baseCanvasRevision;
|
||||||
const workspaceType =
|
const workspaceType =
|
||||||
@ -205,7 +207,11 @@ export async function PUT(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
.returning();
|
.returning();
|
||||||
return NextResponse.json({ success: true, data: saved });
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
data: saved,
|
||||||
|
previousCanvasRevision: existingProject?.updatedAt.toISOString() ?? null,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("更新/创建画布失败:", error);
|
console.error("更新/创建画布失败:", error);
|
||||||
|
|||||||
57
app/api/canvas/[id]/tvstar-sessions/route.ts
Normal file
57
app/api/canvas/[id]/tvstar-sessions/route.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
import { and, desc, eq, lte } from "drizzle-orm";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { tvstarSession } from "@/lib/db/schema";
|
||||||
|
import { ownsTaskProject } from "@/lib/video-canvas/task-store";
|
||||||
|
import { tvstarSessionSchema } from "@/lib/video-canvas/tvstar-session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
async function authorize(projectId: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { error: NextResponse.json({ error: "未登录" }, { status: 401 }) };
|
||||||
|
if (!z.string().uuid().safeParse(projectId).success || !await ownsTaskProject(session.user.id, projectId)) {
|
||||||
|
return { error: NextResponse.json({ error: "画布不存在" }, { status: 404 }) };
|
||||||
|
}
|
||||||
|
return { userId: session.user.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const access = await authorize(id);
|
||||||
|
if (access.error) return access.error;
|
||||||
|
const rows = await db.select({ snapshot: tvstarSession.snapshot, shareToken: tvstarSession.shareToken })
|
||||||
|
.from(tvstarSession)
|
||||||
|
.where(and(eq(tvstarSession.userId, access.userId!), eq(tvstarSession.projectId, id)))
|
||||||
|
.orderBy(desc(tvstarSession.clientUpdatedAt)).limit(20);
|
||||||
|
return NextResponse.json({ sessions: rows.map(({ snapshot, shareToken }) => ({
|
||||||
|
...(snapshot as Record<string, unknown>), shareToken: shareToken || undefined,
|
||||||
|
})) }, { headers: { "Cache-Control": "no-store" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const access = await authorize(id);
|
||||||
|
if (access.error) return access.error;
|
||||||
|
const raw = await request.text();
|
||||||
|
if (raw.length > 900_000) return NextResponse.json({ error: "对话记录过大" }, { status: 413 });
|
||||||
|
let body: unknown;
|
||||||
|
try { body = JSON.parse(raw); } catch { return NextResponse.json({ error: "请求格式无效" }, { status: 400 }); }
|
||||||
|
const parsed = z.object({ sessions: z.array(tvstarSessionSchema).max(20) }).safeParse(body);
|
||||||
|
if (!parsed.success) return NextResponse.json({ error: "对话记录格式无效" }, { status: 400 });
|
||||||
|
for (const session of parsed.data.sessions) {
|
||||||
|
const clientUpdatedAt = new Date(Math.min(session.updatedAt, Date.now() + 60_000));
|
||||||
|
await db.insert(tvstarSession).values({
|
||||||
|
id: session.id, projectId: id, userId: access.userId!, title: session.title,
|
||||||
|
snapshot: session, clientUpdatedAt,
|
||||||
|
}).onConflictDoNothing({ target: tvstarSession.id });
|
||||||
|
await db.update(tvstarSession).set({ title: session.title, snapshot: session, clientUpdatedAt, updatedAt: new Date() })
|
||||||
|
.where(and(
|
||||||
|
eq(tvstarSession.id, session.id), eq(tvstarSession.projectId, id), eq(tvstarSession.userId, access.userId!),
|
||||||
|
lte(tvstarSession.clientUpdatedAt, clientUpdatedAt),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
58
app/api/canvas/[id]/tvstar-sessions/share/route.ts
Normal file
58
app/api/canvas/[id]/tvstar-sessions/share/route.ts
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import { randomBytes } from "node:crypto";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { tvstarSession } from "@/lib/db/schema";
|
||||||
|
import { ownsTaskProject } from "@/lib/video-canvas/task-store";
|
||||||
|
import { publicTVstarSnapshot, tvstarSessionSchema } from "@/lib/video-canvas/tvstar-session";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
async function owner(projectId: string) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return { error: NextResponse.json({ error: "未登录" }, { status: 401 }) };
|
||||||
|
if (!z.string().uuid().safeParse(projectId).success || !await ownsTaskProject(session.user.id, projectId)) {
|
||||||
|
return { error: NextResponse.json({ error: "画布不存在" }, { status: 404 }) };
|
||||||
|
}
|
||||||
|
return { userId: session.user.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const access = await owner(id);
|
||||||
|
if (access.error) return access.error;
|
||||||
|
const raw = await request.text();
|
||||||
|
if (raw.length > 300_000) return NextResponse.json({ error: "对话记录过大" }, { status: 413 });
|
||||||
|
let body: unknown;
|
||||||
|
try { body = JSON.parse(raw); } catch { return NextResponse.json({ error: "请求格式无效" }, { status: 400 }); }
|
||||||
|
const parsed = z.object({ session: tvstarSessionSchema }).safeParse(body);
|
||||||
|
if (!parsed.success) return NextResponse.json({ error: "对话记录格式无效" }, { status: 400 });
|
||||||
|
const current = parsed.data.session;
|
||||||
|
const condition = and(eq(tvstarSession.id, current.id), eq(tvstarSession.projectId, id), eq(tvstarSession.userId, access.userId!));
|
||||||
|
await db.insert(tvstarSession).values({
|
||||||
|
id: current.id, projectId: id, userId: access.userId!, title: current.title,
|
||||||
|
snapshot: current, clientUpdatedAt: new Date(Math.min(current.updatedAt, Date.now() + 60_000)),
|
||||||
|
}).onConflictDoNothing({ target: tvstarSession.id });
|
||||||
|
const existing = (await db.select({ shareToken: tvstarSession.shareToken }).from(tvstarSession).where(condition).limit(1))[0];
|
||||||
|
if (!existing) return NextResponse.json({ error: "对话不存在" }, { status: 404 });
|
||||||
|
const token = existing.shareToken || randomBytes(24).toString("base64url");
|
||||||
|
if (!existing.shareToken) {
|
||||||
|
await db.update(tvstarSession).set({
|
||||||
|
shareToken: token, sharedSnapshot: publicTVstarSnapshot(current), sharedAt: new Date(), updatedAt: new Date(),
|
||||||
|
}).where(condition);
|
||||||
|
}
|
||||||
|
return NextResponse.json({ url: `/tvstar/share/${token}`, token });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const access = await owner(id);
|
||||||
|
if (access.error) return access.error;
|
||||||
|
const sessionId = new URL(request.url).searchParams.get("sessionId") || "";
|
||||||
|
if (!z.string().uuid().safeParse(sessionId).success) return NextResponse.json({ error: "对话 ID 无效" }, { status: 400 });
|
||||||
|
await db.update(tvstarSession).set({ shareToken: null, sharedSnapshot: null, sharedAt: null, updatedAt: new Date() })
|
||||||
|
.where(and(eq(tvstarSession.id, sessionId), eq(tvstarSession.projectId, id), eq(tvstarSession.userId, access.userId!)));
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
40
app/api/canvas/agent-capabilities/route.ts
Normal file
40
app/api/canvas/agent-capabilities/route.ts
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
import { PROJECT_AGENT_OPERATIONS, projectOperationAuthorized } from "@/lib/ai/canvas-agent-runtime/project-operation-catalog";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { canvasProject } from "@/lib/db/schema";
|
||||||
|
import { getSystemSetting } from "@/lib/db/queries";
|
||||||
|
import {
|
||||||
|
normalizeVideoCanvasFunctionConfig,
|
||||||
|
VIDEO_CANVAS_FUNCTION_CONFIG_KEY,
|
||||||
|
} from "@/lib/video-canvas/config";
|
||||||
|
import { getCanvasAgentAccessManifest } from "@/lib/ai/canvas-agent-runtime/capability-access";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
const parsed = z.string().uuid().safeParse(new URL(request.url).searchParams.get("projectId"));
|
||||||
|
if (!parsed.success) return NextResponse.json({ error: "画布编号无效" }, { status: 400 });
|
||||||
|
const [project] = await db
|
||||||
|
.select({ id: canvasProject.id, workspace: canvasProject.workspaceType })
|
||||||
|
.from(canvasProject)
|
||||||
|
.where(and(eq(canvasProject.id, parsed.data), eq(canvasProject.userId, session.user.id)))
|
||||||
|
.limit(1);
|
||||||
|
if (!project) return NextResponse.json({ error: "画布不存在" }, { status: 404 });
|
||||||
|
const config = normalizeVideoCanvasFunctionConfig(
|
||||||
|
(await getSystemSetting({ key: VIDEO_CANVAS_FUNCTION_CONFIG_KEY }))?.value,
|
||||||
|
);
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
workspace: project.workspace,
|
||||||
|
projectServices: PROJECT_AGENT_OPERATIONS.map(item => ({ ...item, authorized: projectOperationAuthorized(item) })),
|
||||||
|
utilityTools: ["getWeather", "createDocument", "updateDocument", "requestSuggestions", "loadProjectSkill"],
|
||||||
|
capabilities: getCanvasAgentAccessManifest(config).filter(
|
||||||
|
(item) => item.workspace === (project.workspace === "video" ? "video" : "canvas"),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ headers: { "Cache-Control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
496
app/api/canvas/agent-chat/route.ts
Normal file
496
app/api/canvas/agent-chat/route.ts
Normal file
@ -0,0 +1,496 @@
|
|||||||
|
import { agentModelCandidates } from "@/lib/ai/runtime/agent-model-failover";
|
||||||
|
import { agentModelCircuitStore } from "@/lib/ai/runtime/agent-model-circuit-store";
|
||||||
|
import { createAgentVisionExecutor } from "@/lib/ai/runtime/agent-vision-failover";
|
||||||
|
import { canvasAgentProgress } from "@/lib/ai/canvas-agent-runtime/progress";
|
||||||
|
import { getStyleProImageModelEntries } from "@/lib/style-pro/model-options";
|
||||||
|
import { registerProjectAgentTools } from "@/lib/ai/canvas-agent-runtime/project-tools";
|
||||||
|
import { isZcodeWorkspaceAuthorized } from "@/lib/ai/canvas-agent-runtime/authorization";
|
||||||
|
import {
|
||||||
|
createUIMessageStream,
|
||||||
|
createUIMessageStreamResponse,
|
||||||
|
generateText,
|
||||||
|
} from "ai";
|
||||||
|
import { after, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { siteSettings, canvasProject } from "@/lib/db/schema";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { postRequestBodySchema } from "@/app/(chat)/api/chat/schema";
|
||||||
|
import { entitlementsByUserType } from "@/lib/ai/entitlements";
|
||||||
|
import { getLanguageModelById } from "@/lib/ai/dynamic-provider";
|
||||||
|
import {
|
||||||
|
getAgentAiModelWithProvider,
|
||||||
|
getAccessibleAgentPresetById,
|
||||||
|
getEnabledAiModelsWithProvider,
|
||||||
|
getChatById,
|
||||||
|
getMessagesByChatId,
|
||||||
|
getMessageCountByUserId,
|
||||||
|
getSiteSettings,
|
||||||
|
saveChat,
|
||||||
|
saveMessages,
|
||||||
|
} from "@/lib/db/queries";
|
||||||
|
import { runZcodeCanvasTask } from "@/lib/ai/zcode-agent/task";
|
||||||
|
import { canvasAgentReplyText } from "@/lib/ai/zcode-agent/assistant-output";
|
||||||
|
import { createZcodeModelGateway } from "@/lib/ai/zcode-agent/model-gateway";
|
||||||
|
import { newAgentRunSnapshot, publicAgentError } from "@/lib/ai/canvas-agent-runtime/protocol";
|
||||||
|
import { shouldUseCanvasAgentRuntime } from "@/lib/ai/canvas-agent-runtime/routing";
|
||||||
|
import {
|
||||||
|
acquireAgentRun,
|
||||||
|
agentRunView,
|
||||||
|
AgentRunError,
|
||||||
|
checkpointAgentRun,
|
||||||
|
consumeAgentRunInputs,
|
||||||
|
heartbeatAgentRun,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/store";
|
||||||
|
import { readOwnedCanvas } from "@/lib/ai/canvas-agent-runtime/canvas";
|
||||||
|
import { buildCanvasRuntimeTools } from "@/lib/ai/canvas-agent-runtime/tools";
|
||||||
|
import { canvasRuntimeSystemPrompt } from "@/lib/ai/canvas-agent-runtime/prompt";
|
||||||
|
import { verifyCanvasAgentResults } from "@/lib/ai/canvas-agent-runtime/review";
|
||||||
|
import { inferCanvasTaskRequirements } from "@/lib/ai/canvas-agent-runtime/requirements";
|
||||||
|
import {
|
||||||
|
resolveRuntimeConversationSources,
|
||||||
|
persistRuntimeConversationResults,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/conversation";
|
||||||
|
import { getCanvasAgentFeatureFlagsFromSystemSettings } from "@/lib/canvas/agent-feature-settings";
|
||||||
|
import { canApplyCanvasAgentMutations } from "@/lib/canvas/agent-feature-flags";
|
||||||
|
|
||||||
|
import {
|
||||||
|
videoAgentSettingsSchema,
|
||||||
|
inferVideoTaskRequirements,
|
||||||
|
videoNodeUrl,
|
||||||
|
videoRuntimeSystemPrompt,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/video-protocol";
|
||||||
|
import { readOwnedVideoCanvas } from "@/lib/ai/canvas-agent-runtime/video-store";
|
||||||
|
import {
|
||||||
|
buildVideoRuntimeTools,
|
||||||
|
createVideoRuntimePorts,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/video-tools";
|
||||||
|
import { probeVideoMetadata } from "@/lib/ai/canvas-agent-runtime/video-probe";
|
||||||
|
import { verifyVideoAgentResults } from "@/lib/ai/canvas-agent-runtime/video-review";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
export const maxDuration = 1200;
|
||||||
|
const requestSchema = postRequestBodySchema.extend({
|
||||||
|
resumeRunId: z.string().uuid().optional(),
|
||||||
|
selectedImageModel: z.string().min(1).max(180).optional(),
|
||||||
|
workspaceVariant: z.enum(["canvas", "video"]).default("canvas"),
|
||||||
|
videoAgentSettings: videoAgentSettingsSchema.optional(),
|
||||||
|
});
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const body = requestSchema.parse(await request.json());
|
||||||
|
if (!shouldUseCanvasAgentRuntime(body))
|
||||||
|
throw new AgentRunError("此请求不属于画布 Agent 任务", 400);
|
||||||
|
const projectId = body.contextPayload!.projectId!;
|
||||||
|
const [ownedProject] = await db.select({ userId: canvasProject.userId, workspaceType: canvasProject.workspaceType })
|
||||||
|
.from(canvasProject).where(eq(canvasProject.id, projectId)).limit(1);
|
||||||
|
if (!ownedProject || ownedProject.userId !== session.user.id) throw new AgentRunError("画布不存在", 404);
|
||||||
|
if (!isZcodeWorkspaceAuthorized(ownedProject.workspaceType)) throw new AgentRunError("视频画布暂未授权给 ZCode Agent,请使用手工功能。", 403);
|
||||||
|
const isVideo = ownedProject.workspaceType === "video";
|
||||||
|
const preset = body.agentPresetId ? await getAccessibleAgentPresetById({ id: body.agentPresetId, userId: session.user.id }) : null;
|
||||||
|
if (preset && String(preset.type) === "video") throw new AgentRunError("视频技能暂未授权给 ZCode Agent", 403);
|
||||||
|
if (body.agentPresetId && (!preset || preset.status !== "active")) throw new AgentRunError("此 Agent 预设不可用", 403);
|
||||||
|
const objective = body.message.parts
|
||||||
|
.filter((part) => part.type === "text")
|
||||||
|
.map((part) => part.text)
|
||||||
|
.join("\n")
|
||||||
|
.trim();
|
||||||
|
if (!objective) throw new AgentRunError("请描述需要完成的创作任务", 400);
|
||||||
|
const settings = await getSiteSettings();
|
||||||
|
if (
|
||||||
|
!settings.agentEnabled ||
|
||||||
|
!canApplyCanvasAgentMutations(await getCanvasAgentFeatureFlagsFromSystemSettings())
|
||||||
|
) {
|
||||||
|
throw new AgentRunError("管理员尚未开启画布 Agent 操作", 403);
|
||||||
|
}
|
||||||
|
const [usageSettings] = await db.select().from(siteSettings).limit(1);
|
||||||
|
if (usageSettings?.usageTimeEnabled) {
|
||||||
|
const time = new Intl.DateTimeFormat("en-GB", {
|
||||||
|
timeZone: "Asia/Shanghai",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
}).format(new Date());
|
||||||
|
if (
|
||||||
|
time < (usageSettings.usageTimeStart || "08:00") ||
|
||||||
|
time > (usageSettings.usageTimeEnd || "20:00")
|
||||||
|
)
|
||||||
|
throw new AgentRunError(usageSettings.usageTimeMessage || "当前不在系统使用时间段内", 403);
|
||||||
|
}
|
||||||
|
const count = await getMessageCountByUserId({ id: session.user.id, differenceInHours: 24 });
|
||||||
|
if (count > entitlementsByUserType[session.user.type].maxMessagesPerDay)
|
||||||
|
throw new AgentRunError("今日对话次数已达到限额", 429);
|
||||||
|
const imageCanvas = isVideo ? null : await readOwnedCanvas(session.user.id, projectId);
|
||||||
|
if (imageCanvas?.project.workspaceType === "video")
|
||||||
|
throw new AgentRunError("请使用视频画布 Agent 入口", 400);
|
||||||
|
const videoCanvas = isVideo ? await readOwnedVideoCanvas(session.user.id, projectId) : null;
|
||||||
|
const nodes = imageCanvas?.nodes || [];
|
||||||
|
const availableIds = isVideo
|
||||||
|
? videoCanvas!.nodes.map((node) => node.id)
|
||||||
|
: nodes.map((node) => node.id);
|
||||||
|
const selectedNodeIds = body.contextPayload?.selectedNodeIds || [];
|
||||||
|
if (selectedNodeIds.some((id) => !availableIds.includes(id))) {
|
||||||
|
throw new AgentRunError("选中图片尚未保存到画布,请等待保存完成后重试。");
|
||||||
|
}
|
||||||
|
const existingChat = await getChatById({ id: body.id });
|
||||||
|
if (existingChat && existingChat.userId !== session.user.id)
|
||||||
|
throw new AgentRunError("对话不存在", 404);
|
||||||
|
if (!existingChat)
|
||||||
|
await saveChat({
|
||||||
|
id: body.id,
|
||||||
|
userId: session.user.id,
|
||||||
|
title: objective.slice(0, 80),
|
||||||
|
visibility: "private",
|
||||||
|
});
|
||||||
|
const conversation = isVideo
|
||||||
|
? {
|
||||||
|
sourceNodeIds: selectedNodeIds,
|
||||||
|
targetReason: "video-selected-nodes",
|
||||||
|
previousContext: null,
|
||||||
|
}
|
||||||
|
: await resolveRuntimeConversationSources({
|
||||||
|
userId: session.user.id,
|
||||||
|
chatId: body.id,
|
||||||
|
projectId,
|
||||||
|
text: objective,
|
||||||
|
parts: body.message.parts,
|
||||||
|
nodes,
|
||||||
|
selectedNodeIds,
|
||||||
|
});
|
||||||
|
const candidates = agentModelCandidates(await getAgentAiModelWithProvider(), await getEnabledAiModelsWithProvider());
|
||||||
|
const configured = candidates[0];
|
||||||
|
if (!configured) throw new AgentRunError("请先在后台配置可用的多模态 Agent 对话模型", 503);
|
||||||
|
let model = await getLanguageModelById(configured.model.id);
|
||||||
|
for (const candidate of candidates.slice(1)) {
|
||||||
|
if (model) break;
|
||||||
|
model = await getLanguageModelById(candidate.model.id);
|
||||||
|
}
|
||||||
|
if (!model) throw new AgentRunError("Agent 模型暂不可用", 503);
|
||||||
|
const visionModel = model;
|
||||||
|
const executeVisionModel = createAgentVisionExecutor(candidates, agentModelCircuitStore, getLanguageModelById);
|
||||||
|
// Validate the user's image choice independently of the Agent planning model.
|
||||||
|
if (body.selectedImageModel) {
|
||||||
|
const images = await getStyleProImageModelEntries();
|
||||||
|
if (!images.some(({ model }) => model.id === body.selectedImageModel && model.healthStatus !== "auto_disabled"))
|
||||||
|
throw new AgentRunError("你选择的生图模型当前不可用,请重新选择;不会自动换模型生成。", 400);
|
||||||
|
}
|
||||||
|
const assistantMessageId = crypto.randomUUID();
|
||||||
|
const previousVideoMessages =
|
||||||
|
existingChat
|
||||||
|
? (await getMessagesByChatId({ id: body.id })).slice(-6).map((message) => ({
|
||||||
|
role: message.role as "user" | "assistant",
|
||||||
|
content: (message.parts as Array<{ type: string; text?: string }>)
|
||||||
|
.filter((part) => part.type === "text")
|
||||||
|
.map((part) => part.text || "")
|
||||||
|
.join("\n")
|
||||||
|
.slice(0, 4000),
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
const initialSnapshot = newAgentRunSnapshot(objective, [
|
||||||
|
...previousVideoMessages,
|
||||||
|
{ role: "user", content: objective },
|
||||||
|
]);
|
||||||
|
initialSnapshot.workspace = isVideo ? "video" : "canvas";
|
||||||
|
if (isVideo) {
|
||||||
|
initialSnapshot.videoRequirements = inferVideoTaskRequirements(objective);
|
||||||
|
initialSnapshot.videoSettings = videoAgentSettingsSchema.parse({
|
||||||
|
...body.videoAgentSettings,
|
||||||
|
...(initialSnapshot.videoRequirements.duration
|
||||||
|
? { duration: initialSnapshot.videoRequirements.duration }
|
||||||
|
: {}),
|
||||||
|
...(initialSnapshot.videoRequirements.ratio
|
||||||
|
? { ratio: initialSnapshot.videoRequirements.ratio }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
initialSnapshot.sourceNodeIds = conversation.sourceNodeIds;
|
||||||
|
initialSnapshot.requirements = {
|
||||||
|
...inferCanvasTaskRequirements(objective, initialSnapshot.sourceNodeIds.length),
|
||||||
|
sourceCount: initialSnapshot.sourceNodeIds.length,
|
||||||
|
};
|
||||||
|
const run = await acquireAgentRun({
|
||||||
|
id: body.message.id,
|
||||||
|
userId: session.user.id,
|
||||||
|
projectId,
|
||||||
|
chatId: body.id,
|
||||||
|
assistantMessageId,
|
||||||
|
resumeRunId: body.resumeRunId,
|
||||||
|
snapshot: initialSnapshot,
|
||||||
|
});
|
||||||
|
const snapshot = run.snapshot;
|
||||||
|
snapshot.imagePreferences = {
|
||||||
|
...snapshot.imagePreferences,
|
||||||
|
// Each submitted turn captures the current controls, including switching back to Auto.
|
||||||
|
modelId: body.selectedImageModel,
|
||||||
|
parameters: body.imageParams || snapshot.imagePreferences?.parameters,
|
||||||
|
};
|
||||||
|
const taskSourceNodeIds = snapshot.sourceNodeIds ?? selectedNodeIds;
|
||||||
|
const context = {
|
||||||
|
recentConversation: previousVideoMessages,
|
||||||
|
preset: preset ? { name: preset.name, type: preset.type, promptTemplate: preset.promptTemplate, defaultModelId: preset.defaultModelId, defaultParams: preset.defaultParams, slots: preset.slots.map(slot => ({ title: slot.title, promptTemplate: slot.promptTemplate, defaultParams: slot.defaultParams })) } : null,
|
||||||
|
videoSettings: snapshot.videoSettings,
|
||||||
|
selectedNodeIds: taskSourceNodeIds,
|
||||||
|
nodes: nodes
|
||||||
|
.filter((node) => taskSourceNodeIds.includes(node.id))
|
||||||
|
.map((node) => ({
|
||||||
|
id: node.id,
|
||||||
|
type: node.type,
|
||||||
|
position: node.position,
|
||||||
|
size: node.size,
|
||||||
|
title: node.data.title,
|
||||||
|
})),
|
||||||
|
skillInstructions: body.hiddenPrompt || undefined,
|
||||||
|
imagePreferences: snapshot.imagePreferences,
|
||||||
|
targetReason: conversation.targetReason,
|
||||||
|
previousConversationContext: conversation.previousContext,
|
||||||
|
};
|
||||||
|
await saveMessages({
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
id: body.message.id,
|
||||||
|
chatId: body.id,
|
||||||
|
role: "user",
|
||||||
|
parts: body.message.parts,
|
||||||
|
attachments: [],
|
||||||
|
createdAt: new Date(),
|
||||||
|
videoStorageStatus: null,
|
||||||
|
temporaryVideoUrl: null,
|
||||||
|
permanentVideoUrl: null,
|
||||||
|
archivedAt: null,
|
||||||
|
videoMetadata: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
let archiveVideoResults: (() => Promise<void>) | undefined;
|
||||||
|
const stream = createUIMessageStream({
|
||||||
|
execute: async ({ writer }) => {
|
||||||
|
const emit = (type: string, data: unknown) => writer.write({
|
||||||
|
type,
|
||||||
|
data,
|
||||||
|
...(type === "data-canvasAgentRun" || type === "data-imageGenerationNotice" ? { transient: true } : {}),
|
||||||
|
} as never);
|
||||||
|
let cancelled = false;
|
||||||
|
let leaseLost = false;
|
||||||
|
const activeModelController = new AbortController();
|
||||||
|
const withModel: typeof executeVisionModel = (execute, signal) => executeVisionModel(execute,
|
||||||
|
signal ? AbortSignal.any([signal, activeModelController.signal]) : activeModelController.signal);
|
||||||
|
const heartbeat = setInterval(() => {
|
||||||
|
void heartbeatAgentRun(run)
|
||||||
|
.then((current) => {
|
||||||
|
if (!current) leaseLost = true;
|
||||||
|
if (current?.cancelRequested) cancelled = true;
|
||||||
|
if (cancelled || leaseLost) activeModelController?.abort();
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
leaseLost = true;
|
||||||
|
activeModelController?.abort();
|
||||||
|
});
|
||||||
|
emit("data-keepalive", { label: "canvas-agent-runtime", ts: Date.now() });
|
||||||
|
}, 10_000);
|
||||||
|
const textId = crypto.randomUUID();
|
||||||
|
writer.write({ type: "start", messageId: assistantMessageId });
|
||||||
|
writer.write({ type: "text-start", id: textId });
|
||||||
|
let streamedText = "";
|
||||||
|
const emitAssistantText = (delta: string) => {
|
||||||
|
streamedText += delta;
|
||||||
|
writer.write({ type: "text-delta", id: textId, delta });
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const videoPorts = isVideo
|
||||||
|
? await createVideoRuntimePorts({
|
||||||
|
userId: session.user.id,
|
||||||
|
chatId: body.id,
|
||||||
|
projectId,
|
||||||
|
runId: run.id,
|
||||||
|
assistantMessageId,
|
||||||
|
request,
|
||||||
|
snapshot,
|
||||||
|
emit,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
archiveVideoResults = videoPorts?.archiveResults;
|
||||||
|
const tools = isVideo
|
||||||
|
? buildVideoRuntimeTools({
|
||||||
|
runId: run.id,
|
||||||
|
projectId,
|
||||||
|
selectedNodeIds,
|
||||||
|
snapshot,
|
||||||
|
ports: videoPorts!,
|
||||||
|
})
|
||||||
|
: await buildCanvasRuntimeTools({
|
||||||
|
userId: session.user.id,
|
||||||
|
chatId: body.id,
|
||||||
|
projectId,
|
||||||
|
runId: run.id,
|
||||||
|
assistantMessageId,
|
||||||
|
selectedNodeIds: taskSourceNodeIds,
|
||||||
|
request,
|
||||||
|
model: visionModel || model,
|
||||||
|
supportsVision: Boolean(visionModel),
|
||||||
|
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(
|
||||||
|
"\n",
|
||||||
|
),
|
||||||
|
emit,
|
||||||
|
});
|
||||||
|
await registerProjectAgentTools({ session, projectId, request, objective: snapshot.objective,
|
||||||
|
definitions: tools.definitions, executable: tools.executable, emit,
|
||||||
|
imagePreferences: snapshot.imagePreferences });
|
||||||
|
const gateway = await createZcodeModelGateway(configured, undefined, candidates);
|
||||||
|
const status = await runZcodeCanvasTask({
|
||||||
|
runId: run.id, snapshot, definitions: tools.definitions,
|
||||||
|
instructions: (isVideo ? videoRuntimeSystemPrompt : canvasRuntimeSystemPrompt)(snapshot.objective, snapshot.summary, snapshot.inputs.map(input => input.text), context),
|
||||||
|
context, gateway, signal: activeModelController.signal,
|
||||||
|
onAssistantText: emitAssistantText,
|
||||||
|
tools: tools.executable,
|
||||||
|
checkpoint: async (state, stateStatus) => {
|
||||||
|
if (leaseLost) throw new AgentRunError("任务执行已中断");
|
||||||
|
const saved = await checkpointAgentRun(run, state, stateStatus);
|
||||||
|
cancelled ||= saved.cancelRequested;
|
||||||
|
emit("data-canvasAgentRun", agentRunView(saved));
|
||||||
|
},
|
||||||
|
consumeInputs: async (state) => {
|
||||||
|
if (leaseLost) throw new AgentRunError("任务执行已中断");
|
||||||
|
const control = await consumeAgentRunInputs(run, state);
|
||||||
|
cancelled ||= control.cancelled;
|
||||||
|
return { cancelled };
|
||||||
|
},
|
||||||
|
isCancelled: async () => {
|
||||||
|
const current = await heartbeatAgentRun(run);
|
||||||
|
if (!current) throw new AgentRunError("任务执行已中断");
|
||||||
|
cancelled ||= current.cancelRequested;
|
||||||
|
return cancelled;
|
||||||
|
},
|
||||||
|
verify: async (state) =>
|
||||||
|
isVideo
|
||||||
|
? verifyVideoAgentResults({
|
||||||
|
snapshot: state,
|
||||||
|
nodes: (await readOwnedVideoCanvas(session.user.id, projectId)).nodes,
|
||||||
|
inspect: async (node, requirements) => {
|
||||||
|
const metadata = await probeVideoMetadata(videoNodeUrl(node));
|
||||||
|
const report = await videoPorts!.analyze({
|
||||||
|
mode: "video-analysis",
|
||||||
|
prompt: `请基于真实抽帧画面检查主体、场景、镜头连贯性,说明不确定内容。用户要求:${requirements}`,
|
||||||
|
imageUrls: [],
|
||||||
|
videoUrls: [videoNodeUrl(node)],
|
||||||
|
});
|
||||||
|
const verdict = await generateText({
|
||||||
|
model,
|
||||||
|
system:
|
||||||
|
'你是视频验收员。依据实际抽帧分析判断是否满足用户要求;不能从文件名或提示词判断。若报告无法读取真实帧,必须不通过。抽帧只能检查画面,不能证明音频、精确时长或完整运动,涉及这些要求无法确认时说明需要人工检查。仅返回 JSON {"passed":boolean,"issues":string[]}。',
|
||||||
|
prompt: JSON.stringify({ requirements, report }),
|
||||||
|
maxOutputTokens: 1200,
|
||||||
|
maxRetries: 0,
|
||||||
|
abortSignal: AbortSignal.timeout(60_000),
|
||||||
|
});
|
||||||
|
state.inputTokens += verdict.usage.inputTokens || 0;
|
||||||
|
state.outputTokens += verdict.usage.outputTokens || 0;
|
||||||
|
const match = verdict.text.match(/\{[\s\S]*\}/);
|
||||||
|
if (!match) throw new Error("视频检查未返回有效结果");
|
||||||
|
return {
|
||||||
|
...z
|
||||||
|
.object({ passed: z.boolean(), issues: z.array(z.string()).max(12) })
|
||||||
|
.parse(JSON.parse(match[0])),
|
||||||
|
...metadata,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: verifyCanvasAgentResults({
|
||||||
|
snapshot: state,
|
||||||
|
userId: session.user.id,
|
||||||
|
projectId,
|
||||||
|
model: visionModel || model,
|
||||||
|
supportsVision: Boolean(visionModel),
|
||||||
|
withModel,
|
||||||
|
signal: activeModelController.signal,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const finalText = canvasAgentReplyText(snapshot);
|
||||||
|
const progress = canvasAgentProgress(agentRunView({ ...run, snapshot, status }));
|
||||||
|
writer.write({ type: "data-canvasAgentProgress", id: run.id, data: progress });
|
||||||
|
if (!isVideo)
|
||||||
|
await persistRuntimeConversationResults({
|
||||||
|
userId: session.user.id,
|
||||||
|
chatId: body.id,
|
||||||
|
projectId,
|
||||||
|
assistantMessageId,
|
||||||
|
snapshot,
|
||||||
|
}).catch((error) => {
|
||||||
|
console.warn("[Canvas Agent] Conversation memory update failed", {
|
||||||
|
runId: run.id,
|
||||||
|
error: publicAgentError(error),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await saveMessages({
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
id: assistantMessageId,
|
||||||
|
chatId: body.id,
|
||||||
|
role: "assistant",
|
||||||
|
parts: [{ type: "text", text: finalText }, { type: "data-canvasAgentProgress", data: progress }],
|
||||||
|
attachments: [],
|
||||||
|
createdAt: new Date(),
|
||||||
|
videoStorageStatus: null,
|
||||||
|
temporaryVideoUrl: null,
|
||||||
|
permanentVideoUrl: null,
|
||||||
|
archivedAt: null,
|
||||||
|
videoMetadata: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
emitAssistantText(finalText.startsWith(streamedText) ? finalText.slice(streamedText.length) : `\n\n${snapshot.message}`);
|
||||||
|
} catch (error) {
|
||||||
|
const statusText = publicAgentError(error);
|
||||||
|
const text = canvasAgentReplyText({ ...snapshot, message: statusText });
|
||||||
|
await checkpointAgentRun(run, { ...snapshot, message: statusText }, "needs_review").catch(
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
const progress = canvasAgentProgress(agentRunView({ ...run, snapshot: { ...snapshot, message: statusText }, status: "needs_review" }));
|
||||||
|
writer.write({ type: "data-canvasAgentProgress", id: run.id, data: progress });
|
||||||
|
await saveMessages({ messages: [{ id: assistantMessageId, chatId: body.id, role: "assistant",
|
||||||
|
parts: [{ type: "text", text }, { type: "data-canvasAgentProgress", data: progress }],
|
||||||
|
attachments: [], createdAt: new Date(), videoStorageStatus: null, temporaryVideoUrl: null,
|
||||||
|
permanentVideoUrl: null, archivedAt: null, videoMetadata: null }] }).catch(() => undefined);
|
||||||
|
emitAssistantText(text.startsWith(streamedText) ? text.slice(streamedText.length) : `\n\n${statusText}`);
|
||||||
|
} finally {
|
||||||
|
clearInterval(heartbeat);
|
||||||
|
writer.write({ type: "text-end", id: textId });
|
||||||
|
writer.write({ type: "finish" });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Browser disconnection does not cancel paid image work. Keep consuming on the server.
|
||||||
|
const [client, background] = stream.tee();
|
||||||
|
after(async () => {
|
||||||
|
const reader = background.getReader();
|
||||||
|
try {
|
||||||
|
while (!(await reader.read()).done) {
|
||||||
|
/* Drain the server branch. */
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
await archiveVideoResults?.();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return createUIMessageStreamResponse({
|
||||||
|
stream: client,
|
||||||
|
headers: { "Cache-Control": "no-store", "X-Accel-Buffering": "no" },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: publicAgentError(error), message: publicAgentError(error) },
|
||||||
|
{
|
||||||
|
status:
|
||||||
|
error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
65
app/api/canvas/agent-runs/route.ts
Normal file
65
app/api/canvas/agent-runs/route.ts
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import {
|
||||||
|
AgentRunError,
|
||||||
|
agentRunView,
|
||||||
|
assertAgentRunOwnership,
|
||||||
|
controlAgentRun,
|
||||||
|
getAgentRun,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/store";
|
||||||
|
import { publicAgentError } from "@/lib/ai/canvas-agent-runtime/protocol";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
const scope = z.object({
|
||||||
|
chatId: z.string().uuid(),
|
||||||
|
projectId: z.string().uuid(),
|
||||||
|
runId: z.string().uuid().optional(),
|
||||||
|
});
|
||||||
|
const control = scope
|
||||||
|
.extend({
|
||||||
|
runId: z.string().uuid(),
|
||||||
|
action: z.enum(["steer", "cancel"]),
|
||||||
|
inputId: z.string().uuid().optional(),
|
||||||
|
text: z.string().trim().min(1).max(2000).optional(),
|
||||||
|
})
|
||||||
|
.refine(
|
||||||
|
(input) => input.action !== "steer" || Boolean(input.inputId && input.text),
|
||||||
|
"补充要求缺少内容或请求号",
|
||||||
|
);
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const input = scope.parse(Object.fromEntries(new URL(request.url).searchParams));
|
||||||
|
await assertAgentRunOwnership(session.user.id, input.projectId, input.chatId);
|
||||||
|
const run = await getAgentRun(session.user.id, input.chatId, input.projectId, input.runId);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ run: run ? agentRunView(run) : null },
|
||||||
|
{ headers: { "Cache-Control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return failure(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const input = control.parse(await request.json());
|
||||||
|
await assertAgentRunOwnership(session.user.id, input.projectId, input.chatId);
|
||||||
|
return NextResponse.json({ run: await controlAgentRun({ ...input, userId: session.user.id }) });
|
||||||
|
} catch (error) {
|
||||||
|
return failure(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function failure(error: unknown) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: publicAgentError(error) },
|
||||||
|
{
|
||||||
|
status:
|
||||||
|
error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -9,10 +9,10 @@ export async function GET() {
|
|||||||
const models = await listCanvasAudioModels();
|
const models = await listCanvasAudioModels();
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
models: models.map(({ model }) => ({
|
models: models.map(({ model, provider }) => ({
|
||||||
id: model.id,
|
id: model.id,
|
||||||
modelId: model.modelId,
|
modelId: model.modelId,
|
||||||
name: model.displayName,
|
name: `${model.displayName} · ${provider.type === "vip98k" ? "98K" : "阿里云"}`,
|
||||||
...audioContract(model.modelId),
|
...audioContract(model.modelId),
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
|
|||||||
77
app/api/canvas/batch-instruction/route.ts
Normal file
77
app/api/canvas/batch-instruction/route.ts
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { createCanvasImageTask, enqueueCanvasImageTask } from "@/lib/canvas/image-task-queue";
|
||||||
|
import { getSystemSetting } from "@/lib/db/queries";
|
||||||
|
import { batchInstructionSizeSchema } from "@/lib/canvas/batch-instruction-size";
|
||||||
|
import type { CanvasGenerateImageRequest } from "@/lib/canvas/generate-image";
|
||||||
|
|
||||||
|
const imageUrl = z.string().trim().max(8192).refine(value => {
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return (url.protocol === "https:" || url.protocol === "http:") &&
|
||||||
|
!url.username && !url.password;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const submission = z.object({
|
||||||
|
taskId: z.string().uuid(),
|
||||||
|
image: imageUrl,
|
||||||
|
reference: imageUrl.optional(),
|
||||||
|
instruction: z.string().trim().max(3000),
|
||||||
|
square: z.boolean(),
|
||||||
|
outputSize: batchInstructionSizeSchema.optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
const parsed = submission.safeParse(await request.json().catch(() => null));
|
||||||
|
if (!parsed.success) return NextResponse.json({ error: "请检查原图、输出尺寸和编辑指令" }, { status: 400 });
|
||||||
|
|
||||||
|
const { taskId, image, reference, instruction, square, outputSize } = parsed.data;
|
||||||
|
if (!instruction && (!outputSize || reference)) {
|
||||||
|
return NextResponse.json({ error: "请填写统一编辑指令。若只调整尺寸,请选择自定义宽高并移除共用参考图" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (reference === image) return NextResponse.json({ error: "共用参考图和待编辑原图相同" }, { status: 400 });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const setting = await getSystemSetting({ key: "scene_fusion_config" });
|
||||||
|
if ((setting?.value as { enabled?: boolean } | null)?.enabled === false) {
|
||||||
|
return NextResponse.json({ error: "批量处理功能已被管理员禁用" }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const referenceImages = reference ? [image, reference] : [image];
|
||||||
|
const imageRequest: CanvasGenerateImageRequest = {
|
||||||
|
prompt: instruction ? [
|
||||||
|
"编辑第一张图。保留第一张图的完整构图、原始宽高比和所有未要求修改的内容。",
|
||||||
|
reference && "第二张图只提供指令指定的人脸、商品或其他特征。以第一张图为底图,保持第一张图中其余人物、姿势、衣着、商品、背景和光线,除非指令明确要求更改。",
|
||||||
|
"保持原图整幅画面的四边,避免裁切或拉伸。只输出一张编辑后的图片。",
|
||||||
|
"编辑指令:" + instruction,
|
||||||
|
].filter(Boolean).join("\n") : "",
|
||||||
|
displayPrompt: instruction,
|
||||||
|
aspectRatio: "auto",
|
||||||
|
imageCount: 1,
|
||||||
|
referenceImages,
|
||||||
|
requiredReferenceImageCount: referenceImages.length,
|
||||||
|
agentImageMode: "auto",
|
||||||
|
promptExtend: false,
|
||||||
|
padBatchInstructionToSquare: square && !outputSize || undefined,
|
||||||
|
batchInstructionOutputSize: outputSize,
|
||||||
|
batchInstructionWithReference: Boolean(reference) || undefined,
|
||||||
|
debugLabel: "batch-instruction-edit",
|
||||||
|
};
|
||||||
|
const task = await createCanvasImageTask({
|
||||||
|
userId: session.user.id,
|
||||||
|
request: { ...imageRequest },
|
||||||
|
taskId,
|
||||||
|
});
|
||||||
|
if (task.status === "pending") await enqueueCanvasImageTask(task.id);
|
||||||
|
return NextResponse.json({ taskId: task.id }, { status: 202 });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[BatchInstruction] Task submission failed", { taskId, error });
|
||||||
|
return NextResponse.json({ error: "暂时无法确认是否提交成功,请查询原任务" }, { status: 503 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,100 +1,15 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import {
|
import { executeBoxCutoutPOST } from "@/lib/canvas/operations/box-cutout";
|
||||||
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 runtime = "nodejs";
|
||||||
export const maxDuration = 60;
|
export const maxDuration = 60;
|
||||||
|
|
||||||
type BoxCutoutRequest = {
|
export async function POST(request: Request) {
|
||||||
imageUrl?: string;
|
const session = await auth();
|
||||||
cropRect?: {
|
if (!session?.user?.id) {
|
||||||
x?: number;
|
return NextResponse.json({ success: false, error: "未授权,请先登录" }, { status: 401 });
|
||||||
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."
|
? "You are both an art director and a marketing director for high-conversion e-commerce detail pages. Output JSON only."
|
||||||
: "你同时扮演高转化电商详情页的平面设计总监与营销总监。仅输出JSON。",
|
: "你同时扮演高转化电商详情页的平面设计总监与营销总监。仅输出JSON。",
|
||||||
temperature: params.isLocalMoonshot ? 1 : 0.1,
|
temperature: params.isLocalMoonshot ? 1 : 0.1,
|
||||||
maxTokens: 2000,
|
maxOutputTokens: 2000,
|
||||||
...(params.kimiOptions || {}),
|
...(params.kimiOptions || {}),
|
||||||
}, params.timeoutMs || DETAIL_PLAN_PREFLIGHT_TIMEOUT_MS);
|
}, params.timeoutMs || DETAIL_PLAN_PREFLIGHT_TIMEOUT_MS);
|
||||||
|
|
||||||
@ -2040,7 +2040,7 @@ export async function POST(request: Request) {
|
|||||||
kimiDetailProfile: plannerKimiOptions.headers
|
kimiDetailProfile: plannerKimiOptions.headers
|
||||||
? {
|
? {
|
||||||
thinking: plannerKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
thinking: plannerKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
||||||
maxTokens: plannerKimiOptions.maxTokens,
|
maxOutputTokens: plannerKimiOptions.maxOutputTokens,
|
||||||
}
|
}
|
||||||
: null,
|
: 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"}]}]}]}`,
|
`{"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,
|
temperature: 0.25,
|
||||||
...(localDetailAgentResolved ? { temperature: 1 } : {}),
|
...(localDetailAgentResolved ? { temperature: 1 } : {}),
|
||||||
maxTokens: 1800,
|
maxOutputTokens: 1800,
|
||||||
...plannerKimiOptions,
|
...plannerKimiOptions,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -323,7 +323,7 @@ export async function POST(request: Request) {
|
|||||||
kimiDetailProfile: reviewKimiOptions.headers
|
kimiDetailProfile: reviewKimiOptions.headers
|
||||||
? {
|
? {
|
||||||
thinking: reviewKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
thinking: reviewKimiOptions.headers["x-detail-agent-kimi-thinking"],
|
||||||
maxTokens: reviewKimiOptions.maxTokens,
|
maxOutputTokens: reviewKimiOptions.maxOutputTokens,
|
||||||
}
|
}
|
||||||
: null,
|
: 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."
|
? "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。",
|
: "你同时是高转化电商详情页的平面设计总监与营销总监。按严格专业标准评估,仅输出JSON。",
|
||||||
temperature: localDetailAgentResolved ? 1 : 0.1,
|
temperature: localDetailAgentResolved ? 1 : 0.1,
|
||||||
maxTokens: 800,
|
maxOutputTokens: 800,
|
||||||
...reviewKimiOptions,
|
...reviewKimiOptions,
|
||||||
} as any);
|
} as any);
|
||||||
text = String(result?.text || "");
|
text = String(result?.text || "");
|
||||||
|
|||||||
@ -1,5 +1,13 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
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 { after, NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { getDownloadPreparationQueue, type DownloadPreparationInput } from "@/lib/canvas/download-preparation";
|
||||||
|
import { extractImageProxySourceUrl, inferOriginalImageUrl } from "@/lib/image-url";
|
||||||
import {
|
import {
|
||||||
buildAttachmentContentDisposition,
|
buildAttachmentContentDisposition,
|
||||||
fetchCanvasDownloadAsset,
|
fetchCanvasDownloadAsset,
|
||||||
@ -8,6 +16,51 @@ import {
|
|||||||
|
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
export const maxDuration = 120;
|
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
|
||||||
|
// upstream request through our own server (and create another HTTP timeout).
|
||||||
|
const sources = [...new Set(input.urls.map(url => {
|
||||||
|
const source = extractImageProxySourceUrl(url) || url;
|
||||||
|
return inferOriginalImageUrl(source) || source;
|
||||||
|
}))];
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let attempt = 0; attempt < 2; 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,
|
||||||
|
});
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
throw new Error(String(lastError || "Original image sources unavailable"));
|
||||||
|
}
|
||||||
|
|
||||||
function getRequestOrigin(request: NextRequest): string {
|
function getRequestOrigin(request: NextRequest): string {
|
||||||
const forwardedHost = (request.headers.get("x-forwarded-host") || "").split(",")[0]?.trim();
|
const forwardedHost = (request.headers.get("x-forwarded-host") || "").split(",")[0]?.trim();
|
||||||
@ -46,21 +99,63 @@ function resolveDownloadUrls(body: Record<string, unknown>, origin: string): str
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
|
const requestId = randomUUID();
|
||||||
try {
|
try {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
return failed(getDownloadFailure("未登录"), requestId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
||||||
const requestOrigin = getRequestOrigin(request);
|
const requestOrigin = getRequestOrigin(request);
|
||||||
const urls = resolveDownloadUrls(body, requestOrigin);
|
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 requestedUrls = [...urls];
|
||||||
if (urls.length === 0) {
|
if (urls.length === 0) {
|
||||||
return NextResponse.json({ success: false, error: "图片地址无效" }, { status: 400 });
|
return failed(getDownloadFailure("图片地址无效"), requestId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = sanitizeCanvasDownloadFileName(String(body.name || ""), "canvas-image");
|
const name = sanitizeCanvasDownloadFileName(String(body.name || ""), "canvas-image");
|
||||||
|
if (body.preferDirect === true) {
|
||||||
|
const { task, direct, canPrepareDirect } = await resolveCanvasCdnDownload(urls, `${name}.png`);
|
||||||
|
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 && !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") || "";
|
const cookie = request.headers.get("cookie") || "";
|
||||||
|
if (body.preparation === "async") {
|
||||||
|
const result = await getDownloadPreparationQueue(prepareDownload, after).request({
|
||||||
|
userId: session.user.id, urls: requestedUrls, requestOrigin, cookie,
|
||||||
|
});
|
||||||
|
if (result.status === "preparing") {
|
||||||
|
return preparing(result.requestId);
|
||||||
|
}
|
||||||
|
if (result.status === "failed") {
|
||||||
|
return failed(result.failure, result.requestId);
|
||||||
|
}
|
||||||
|
return new NextResponse(new Uint8Array(result.asset.buffer), { headers: {
|
||||||
|
"Content-Type": result.asset.contentType,
|
||||||
|
"Content-Length": String(result.asset.buffer.length),
|
||||||
|
"Content-Disposition": buildAttachmentContentDisposition(`${name}.png`),
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
} });
|
||||||
|
}
|
||||||
let result: Awaited<ReturnType<typeof fetchCanvasDownloadAsset>> | null = null;
|
let result: Awaited<ReturnType<typeof fetchCanvasDownloadAsset>> | null = null;
|
||||||
const failures: string[] = [];
|
const failures: string[] = [];
|
||||||
|
|
||||||
@ -73,17 +168,14 @@ export async function POST(request: NextRequest) {
|
|||||||
includeSequencePrefix: false,
|
includeSequencePrefix: false,
|
||||||
});
|
});
|
||||||
if (result.ok) break;
|
if (result.ok) break;
|
||||||
failures.push(`${url}: ${result.error}`);
|
failures.push(result.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!result?.ok) {
|
if (!result?.ok) {
|
||||||
if (failures.length > 0) {
|
if (failures.length > 0) {
|
||||||
console.warn("[CanvasDownloadImage] All candidates failed:", failures);
|
logger.warn("all_sources_failed", { requestId, failures });
|
||||||
}
|
}
|
||||||
return NextResponse.json(
|
return failed(getDownloadFailure(result?.error), requestId);
|
||||||
{ success: false, error: result?.error || "图片源文件暂时不可访问" },
|
|
||||||
{ status: 502 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new NextResponse(result.bytes, {
|
return new NextResponse(result.bytes, {
|
||||||
@ -96,7 +188,7 @@ export async function POST(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[CanvasDownloadImage] Failed:", error);
|
logger.error("download_failed", error, { requestId });
|
||||||
return NextResponse.json({ success: false, error: "图片下载失败" }, { status: 500 });
|
return failed(getDownloadFailure(error), requestId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,54 +1,23 @@
|
|||||||
|
import { readDownloadZip } from "@/lib/canvas/download-zip-stream";
|
||||||
|
import { claimZipTask, loadZipTask, saveZipTask, zipTaskPath, assertZipDiskSpace, cleanupZipTasks, assertZipTaskCapacity, type ZipTask } from "@/lib/canvas/download-zip-task-store";
|
||||||
|
import { parseDownloadByteRange } from "@/lib/canvas/download-byte-range";
|
||||||
|
import { mkdir, stat, rm } from "node:fs/promises";
|
||||||
|
import { join } from "node:path";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { after, NextRequest, NextResponse } from "next/server";
|
||||||
import JSZip from "jszip";
|
import { prepareCanvasZip } from "@/lib/canvas/download-zip-prepare";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { fetchCanvasDownloadAsset } from "@/lib/canvas/photoshop-safe-download";
|
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 runtime = "nodejs";
|
||||||
export const maxDuration = 300;
|
export const maxDuration = 300;
|
||||||
|
type DownloadFileItem = { url: string; name?: string };
|
||||||
type DownloadFileItem = {
|
|
||||||
url: string;
|
|
||||||
name?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ZipTaskStatus = "pending" | "running" | "completed" | "failed";
|
|
||||||
|
|
||||||
type ZipTask = {
|
|
||||||
id: string;
|
|
||||||
userId: string;
|
|
||||||
folderName: string;
|
|
||||||
files: DownloadFileItem[];
|
|
||||||
totalCount: number;
|
|
||||||
processedCount: number;
|
|
||||||
successCount: number;
|
|
||||||
failedCount: number;
|
|
||||||
compressPercent: number;
|
|
||||||
status: ZipTaskStatus;
|
|
||||||
stage: string;
|
|
||||||
error?: string;
|
|
||||||
zipBuffer?: Buffer;
|
|
||||||
contentDisposition?: string;
|
|
||||||
createdAt: number;
|
|
||||||
updatedAt: number;
|
|
||||||
expiresAt: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const MAX_CONCURRENCY = 8;
|
|
||||||
const MAX_DOWNLOAD_FILES = 200;
|
const MAX_DOWNLOAD_FILES = 200;
|
||||||
const TASK_TTL_MS = 30 * 60 * 1000;
|
const TASK_TTL_MS = 24 * 60 * 60_000;
|
||||||
|
const PREPARATION_TTL_MS = 6 * 60 * 60_000;
|
||||||
const globalTaskStore = globalThis as typeof globalThis & {
|
const running = (globalThis as typeof globalThis & { __canvasZipRunning?: Set<string> });
|
||||||
__canvasDownloadZipTasks?: Map<string, ZipTask>;
|
const active = running.__canvasZipRunning ??= new Set<string>();
|
||||||
};
|
|
||||||
|
|
||||||
function getTaskStore() {
|
|
||||||
if (!globalTaskStore.__canvasDownloadZipTasks) {
|
|
||||||
globalTaskStore.__canvasDownloadZipTasks = new Map<string, ZipTask>();
|
|
||||||
}
|
|
||||||
return globalTaskStore.__canvasDownloadZipTasks;
|
|
||||||
}
|
|
||||||
|
|
||||||
function sanitizeFolderName(value: string): string {
|
function sanitizeFolderName(value: string): string {
|
||||||
const cleaned = String(value || "")
|
const cleaned = String(value || "")
|
||||||
.replace(/[\\/:*?"<>|]+/g, "-")
|
.replace(/[\\/:*?"<>|]+/g, "-")
|
||||||
@ -56,17 +25,7 @@ function sanitizeFolderName(value: string): string {
|
|||||||
.replace(/-+/g, "-")
|
.replace(/-+/g, "-")
|
||||||
.replace(/^-+|-+$/g, "")
|
.replace(/^-+|-+$/g, "")
|
||||||
.trim();
|
.trim();
|
||||||
return cleaned || `canvas-images-${Date.now()}`;
|
return cleaned && !/^\.+$/.test(cleaned) ? cleaned.slice(0, 100) : `canvas-images-${Date.now()}`;
|
||||||
}
|
|
||||||
|
|
||||||
function buildContentDisposition(folderName: string): string {
|
|
||||||
const encodedName = encodeURIComponent(`${folderName}.zip`);
|
|
||||||
const asciiName =
|
|
||||||
folderName
|
|
||||||
.replace(/[^\x20-\x7E]+/g, "")
|
|
||||||
.replace(/"/g, "")
|
|
||||||
.trim() || "canvas-images";
|
|
||||||
return `attachment; filename="${asciiName}.zip"; filename*=UTF-8''${encodedName}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRequestOrigin(request: NextRequest): string {
|
function getRequestOrigin(request: NextRequest): string {
|
||||||
@ -110,258 +69,161 @@ function toDownloadItems(input: unknown, origin: string): DownloadFileItem[] {
|
|||||||
.slice(0, MAX_DOWNLOAD_FILES);
|
.slice(0, MAX_DOWNLOAD_FILES);
|
||||||
}
|
}
|
||||||
|
|
||||||
function cleanupExpiredTasks() {
|
|
||||||
const now = Date.now();
|
|
||||||
const store = getTaskStore();
|
|
||||||
for (const [taskId, task] of store.entries()) {
|
|
||||||
if (task.expiresAt <= now) {
|
|
||||||
store.delete(taskId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getTaskProgress(task: ZipTask) {
|
|
||||||
if (task.status === "completed") {
|
|
||||||
return 100;
|
|
||||||
}
|
|
||||||
if (task.status === "failed") {
|
|
||||||
return Math.max(
|
|
||||||
0,
|
|
||||||
Math.min(100, Math.round((task.processedCount / Math.max(1, task.totalCount)) * 85))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (task.processedCount >= task.totalCount && task.totalCount > 0) {
|
|
||||||
return Math.min(99, 85 + Math.round((task.compressPercent / 100) * 14));
|
|
||||||
}
|
|
||||||
return Math.max(
|
|
||||||
4,
|
|
||||||
Math.min(85, Math.round((task.processedCount / Math.max(1, task.totalCount)) * 85))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function serializeTask(task: ZipTask) {
|
function serializeTask(task: ZipTask) {
|
||||||
const downloadUrl =
|
return { id: task.id, folderName: task.folderName, status: task.status, stage: task.stage,
|
||||||
task.status === "completed"
|
totalCount: task.totalCount, processedCount: task.processedCount, successCount: task.successCount,
|
||||||
? `/api/canvas/download-zip-task?taskId=${encodeURIComponent(task.id)}&download=1`
|
failedCount: task.failedCount, progress: task.status === "completed" ? 100 : Math.min(99,
|
||||||
: "";
|
Math.round(task.processedCount / Math.max(1, task.totalCount) * 85 + task.compressPercent * .14)),
|
||||||
return {
|
error: task.error || "", expiresAt: task.expiresAt,
|
||||||
id: task.id,
|
downloadUrl: task.status === "completed" ? `/api/canvas/download-zip-task?taskId=${task.id}&download=1` : "" };
|
||||||
folderName: task.folderName,
|
|
||||||
status: task.status,
|
|
||||||
stage: task.stage,
|
|
||||||
totalCount: task.totalCount,
|
|
||||||
processedCount: task.processedCount,
|
|
||||||
successCount: task.successCount,
|
|
||||||
failedCount: task.failedCount,
|
|
||||||
progress: getTaskProgress(task),
|
|
||||||
error: task.error || "",
|
|
||||||
downloadUrl,
|
|
||||||
createdAt: task.createdAt,
|
|
||||||
updatedAt: task.updatedAt,
|
|
||||||
expiresAt: task.expiresAt,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
async function processTask(id: string, userId: string, requestOrigin: string, cookie: string) {
|
||||||
async function processZipTask(params: {
|
if (active.has(id) || active.size >= 2) return;
|
||||||
task: ZipTask;
|
active.add(id);
|
||||||
requestOrigin: string;
|
let release: (() => Promise<void>) | null = null;
|
||||||
cookie: string;
|
let task: ZipTask | null = null;
|
||||||
}) {
|
|
||||||
const { task, requestOrigin, cookie } = params;
|
|
||||||
const store = getTaskStore();
|
|
||||||
try {
|
try {
|
||||||
task.status = "running";
|
release = await claimZipTask(id);
|
||||||
task.stage = "正在读取源图";
|
if (!release) return;
|
||||||
task.updatedAt = Date.now();
|
task = await loadZipTask(id, userId);
|
||||||
|
if (!task || task.status === "completed" || task.status === "failed") return;
|
||||||
const zip = new JSZip();
|
if (task.remote) {
|
||||||
const folder = zip.folder(task.folderName) || zip;
|
const { updateRemoteCanvasZip } = await import("@/lib/canvas/remote-zip-client");
|
||||||
const results: Array<
|
await updateRemoteCanvasZip(task, requestOrigin);
|
||||||
| Awaited<ReturnType<typeof fetchCanvasDownloadAsset>>
|
return;
|
||||||
| null
|
|
||||||
> = new Array(task.files.length).fill(null);
|
|
||||||
let cursor = 0;
|
|
||||||
const workerCount = Math.min(MAX_CONCURRENCY, task.files.length);
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
Array.from({ length: workerCount }, async () => {
|
|
||||||
while (true) {
|
|
||||||
const index = cursor;
|
|
||||||
cursor += 1;
|
|
||||||
if (index >= task.files.length) break;
|
|
||||||
|
|
||||||
const file = task.files[index]!;
|
|
||||||
results[index] = await fetchCanvasDownloadAsset({
|
|
||||||
file,
|
|
||||||
index,
|
|
||||||
requestOrigin,
|
|
||||||
cookie,
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = results[index];
|
|
||||||
task.processedCount += 1;
|
|
||||||
if (result?.ok) {
|
|
||||||
task.successCount += 1;
|
|
||||||
} else {
|
|
||||||
task.failedCount += 1;
|
|
||||||
}
|
|
||||||
task.stage = `正在处理 ${task.processedCount}/${task.totalCount} 张`;
|
|
||||||
task.updatedAt = Date.now();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
const failures: Array<{ index: number; url: string; name?: string; error: string }> = [];
|
|
||||||
for (const [index, item] of results.entries()) {
|
|
||||||
if (!item || !item.ok) {
|
|
||||||
failures.push({
|
|
||||||
index: index + 1,
|
|
||||||
url: item?.ok === false ? item.url : task.files[index]?.url || "",
|
|
||||||
name: item?.ok === false ? item.name : task.files[index]?.name,
|
|
||||||
error: item?.ok === false ? item.error : "未知错误",
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
folder.file(item.filename, item.bytes);
|
|
||||||
}
|
}
|
||||||
|
if (task.preferQiniu || task.qiniu) {
|
||||||
if (failures.length > 0) {
|
const { processQiniuCanvasZip } = await import("@/lib/canvas/qiniu-canvas-zip");
|
||||||
folder.file(
|
if (await processQiniuCanvasZip(task, requestOrigin)) return;
|
||||||
"_download-failures.txt",
|
delete task.preferQiniu;
|
||||||
[
|
}
|
||||||
"以下图片暂时无法下载。可稍后重试,或复制链接检查源图是否仍可访问。",
|
await assertZipDiskSpace();
|
||||||
"",
|
const existingZip = task.zipFile && task.contentDisposition && await stat(task.zipFile.path).catch(() => null);
|
||||||
...failures.map((item) => {
|
const reuseZip = existingZip && existingZip.size === task.zipFile!.bytes;
|
||||||
const label = item.name ? `${item.index}. ${item.name}` : `${item.index}. image`;
|
task.status = "running"; task.stage = reuseZip ? "正在准备加速下载" : "正在准备原图"; task.updatedAt = Date.now();
|
||||||
return `${label}\nURL: ${item.url}\n原因: ${item.error}`;
|
await saveZipTask(task);
|
||||||
}),
|
if (!reuseZip) {
|
||||||
].join("\n\n")
|
await prepareCanvasZip(task, (params) =>
|
||||||
|
fetchCanvasDownloadAsset({ ...params, requestOrigin, cookie })
|
||||||
);
|
);
|
||||||
console.warn("[CanvasDownloadZipTask] Partial download failures:", failures);
|
|
||||||
}
|
}
|
||||||
|
task.stage = "正在准备下载链接"; await saveZipTask(task);
|
||||||
task.stage = "正在生成 ZIP 文件";
|
const cdn = await publishCanvasZip({ id: task.id, ...task.zipFile!, disposition: task.contentDisposition!,
|
||||||
task.updatedAt = Date.now();
|
onProgress: async bytes => {
|
||||||
task.zipBuffer = await zip.generateAsync(
|
task!.stage = `正在传送至七牛 ${Math.round(bytes / task!.zipFile!.bytes * 100)}%`;
|
||||||
{
|
task!.updatedAt = Date.now(); await saveZipTask(task!);
|
||||||
type: "nodebuffer",
|
} });
|
||||||
compression: "DEFLATE",
|
if (cdn) {
|
||||||
compressionOptions: { level: 6 },
|
task.cdnObject = { storageConfigId: cdn.storageConfigId, key: cdn.key };
|
||||||
},
|
if (!cdn.url) throw new Error(cdn.error || `ZIP 已打包,但加速下载未就绪,请再次点击下载继续传送原 ZIP。下载编号:${task.id}`);
|
||||||
(metadata) => {
|
task.cdnUrl = cdn.url;
|
||||||
task.compressPercent = Math.max(0, Math.min(100, metadata.percent || 0));
|
}
|
||||||
task.updatedAt = Date.now();
|
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);
|
||||||
task.contentDisposition = buildContentDisposition(task.folderName);
|
// The complete ZIP is enough for retries; release staged duplicate bytes.
|
||||||
task.status = "completed";
|
await Promise.all(task.files.filter(f => f.prepared).map(f => rm(join(zipTaskPath(id), f.prepared!), { force: true }).catch(() => undefined)));
|
||||||
task.stage = "打包完成";
|
console.info("[CanvasDownloadZipTask] Complete", { taskId: id, count: task.successCount, failed: task.failedCount,
|
||||||
task.compressPercent = 100;
|
bytes: task.zipFile!.bytes, delivery: task.cdnUrl ? "cdn" : "local" });
|
||||||
task.updatedAt = Date.now();
|
|
||||||
task.expiresAt = Date.now() + TASK_TTL_MS;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[CanvasDownloadZipTask] Failed:", error);
|
if (task) {
|
||||||
task.status = "failed";
|
task.status = "failed"; task.stage = task.zipFile ? "ZIP 已打包,加速下载未就绪" : "打包未完成";
|
||||||
task.stage = "打包失败";
|
task.error = error instanceof Error ? error.message : "打包失败,请稍后重试";
|
||||||
task.error = error instanceof Error ? error.message : "打包下载失败";
|
task.updatedAt = Date.now(); task.expiresAt = Date.now() + TASK_TTL_MS; await saveZipTask(task).catch(() => undefined);
|
||||||
task.updatedAt = Date.now();
|
}
|
||||||
task.expiresAt = Date.now() + TASK_TTL_MS;
|
console.error("[CanvasDownloadZipTask] Preparation failed", { taskId: id, message: task?.error });
|
||||||
} finally {
|
} finally { await release?.().catch(() => undefined); active.delete(id); }
|
||||||
store.set(task.id, task);
|
}
|
||||||
}
|
function schedule(task: ZipTask, request: NextRequest) {
|
||||||
|
const run = () => trackRuntimeWork(() => processTask(task.id, task.userId, getRequestOrigin(request), request.headers.get("cookie") || ""));
|
||||||
|
after(run);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
try {
|
try {
|
||||||
cleanupExpiredTasks();
|
const body = await request.json();
|
||||||
const session = await auth();
|
let id = typeof body.taskId === "string" ? body.taskId : randomUUID();
|
||||||
if (!session?.user?.id) {
|
let task = await loadZipTask(id, session.user.id);
|
||||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
if (!task) {
|
||||||
}
|
await assertZipTaskCapacity(session.user.id);
|
||||||
|
if (await stat(zipTaskPath(id)).catch(() => null)) id = randomUUID();
|
||||||
const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
|
const files = toDownloadItems(body.files, getRequestOrigin(request));
|
||||||
const requestOrigin = getRequestOrigin(request);
|
if (!files.length || !Array.isArray(body.files) || body.files.length > MAX_DOWNLOAD_FILES || files.length !== body.files.length)
|
||||||
const files = toDownloadItems(body.files, requestOrigin);
|
return NextResponse.json({ error: "请选择 1 到 200 张可下载图片" }, { status: 400 });
|
||||||
const folderName = sanitizeFolderName(String(body.folderName || ""));
|
// Exclusive creation prevents an arbitrary taskId from overwriting another owner's manifest.
|
||||||
if (files.length === 0) {
|
await mkdir(zipTaskPath(id), { recursive: false, mode: 0o700 }).catch(async error => {
|
||||||
return NextResponse.json({ success: false, error: "没有可下载的图片" }, { status: 400 });
|
if (error.code !== "ENOENT") throw error;
|
||||||
}
|
await mkdir((await import("@/lib/canvas/download-zip-stream")).downloadZipDirectory, { recursive: true, mode: 0o700 });
|
||||||
|
await mkdir(zipTaskPath(id), { mode: 0o700 });
|
||||||
const task: ZipTask = {
|
|
||||||
id: randomUUID(),
|
|
||||||
userId: session.user.id,
|
|
||||||
folderName,
|
|
||||||
files,
|
|
||||||
totalCount: files.length,
|
|
||||||
processedCount: 0,
|
|
||||||
successCount: 0,
|
|
||||||
failedCount: 0,
|
|
||||||
compressPercent: 0,
|
|
||||||
status: "pending",
|
|
||||||
stage: "等待服务端开始打包",
|
|
||||||
createdAt: Date.now(),
|
|
||||||
updatedAt: Date.now(),
|
|
||||||
expiresAt: Date.now() + TASK_TTL_MS,
|
|
||||||
};
|
|
||||||
getTaskStore().set(task.id, task);
|
|
||||||
|
|
||||||
void processZipTask({
|
|
||||||
task,
|
|
||||||
requestOrigin,
|
|
||||||
cookie: request.headers.get("cookie") || "",
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
task: serializeTask(task),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error("[CanvasDownloadZipTask] Create failed:", error);
|
|
||||||
return NextResponse.json({ success: false, error: "创建打包任务失败" }, { status: 500 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
cleanupExpiredTasks();
|
|
||||||
const session = await auth();
|
|
||||||
if (!session?.user?.id) {
|
|
||||||
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const taskId = String(request.nextUrl.searchParams.get("taskId") || "").trim();
|
|
||||||
if (!taskId) {
|
|
||||||
return NextResponse.json({ success: false, error: "缺少任务 ID" }, { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
const task = getTaskStore().get(taskId);
|
|
||||||
if (!task || task.userId !== session.user.id) {
|
|
||||||
return NextResponse.json({ success: false, error: "打包任务不存在或已过期" }, { status: 404 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (request.nextUrl.searchParams.get("download") === "1") {
|
|
||||||
if (task.status !== "completed" || !task.zipBuffer) {
|
|
||||||
return NextResponse.json({ success: false, error: "ZIP 文件尚未准备好" }, { status: 409 });
|
|
||||||
}
|
|
||||||
return new NextResponse(task.zipBuffer, {
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/zip",
|
|
||||||
"Content-Disposition": task.contentDisposition || buildContentDisposition(task.folderName),
|
|
||||||
"Content-Length": String(task.zipBuffer.length),
|
|
||||||
"Cache-Control": "no-store",
|
|
||||||
"X-Download-Success-Count": String(task.successCount),
|
|
||||||
"X-Download-Failed-Count": String(task.failedCount),
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
const now = Date.now();
|
||||||
|
const remote = (body.scope === "style-detail" || body.scope === "batch-instruction") &&
|
||||||
|
process.env.CANVAS_ZIP_WORKER_URL && process.env.CANVAS_ZIP_WORKER_TOKEN
|
||||||
|
? { attempt: 0 } : undefined;
|
||||||
|
task = { id, userId: session.user.id, folderName: sanitizeFolderName(String(body.folderName || "")), files, remote,
|
||||||
|
preferQiniu: body.scope === "canvas-selection" || undefined,
|
||||||
|
totalCount: files.length, processedCount: 0, successCount: 0, failedCount: 0, compressPercent: 0,
|
||||||
|
status: "pending", stage: "等待后台准备", createdAt: now, updatedAt: now, expiresAt: now + PREPARATION_TTL_MS };
|
||||||
|
await saveZipTask(task);
|
||||||
|
} else if ((task.status === "failed" || task.status === "completed" && task.cdnObject && !task.cdnUrl) && body.retry === true) {
|
||||||
|
task.status = "pending"; task.error = undefined;
|
||||||
|
await assertZipTaskCapacity(session.user.id);
|
||||||
|
if (task.remote) {
|
||||||
|
task.remote.attempt++;
|
||||||
|
delete task.remote.sources;
|
||||||
|
}
|
||||||
|
if (task.qiniu?.confirmedFailed) delete task.qiniu;
|
||||||
|
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;
|
||||||
|
await saveZipTask(task);
|
||||||
}
|
}
|
||||||
|
if (task.status === "pending" || task.status === "running") schedule(task, request);
|
||||||
return NextResponse.json({
|
after(() => cleanupZipTasks(async object => {
|
||||||
success: true,
|
const { removeCanvasZipObject } = await import("@/lib/storage/canvas-zip-delivery");
|
||||||
task: serializeTask(task),
|
await removeCanvasZipObject(object);
|
||||||
});
|
}).catch(() => { console.warn("[CanvasDownloadZipTask] Expired file cleanup deferred"); }));
|
||||||
|
return NextResponse.json({ success: true, task: serializeTask(task) }, { status: 202, headers: { "Cache-Control": "no-store" } });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("[CanvasDownloadZipTask] Query failed:", error);
|
console.warn("[CanvasDownloadZipTask] Create rejected", { message: (error as Error).message });
|
||||||
return NextResponse.json({ success: false, error: "查询打包任务失败" }, { status: 500 });
|
return NextResponse.json({ error: "无法创建打包任务,请稍后重试" }, { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const id = request.nextUrl.searchParams.get("taskId") || "";
|
||||||
|
const task = await loadZipTask(id, session.user.id);
|
||||||
|
if (!task) return NextResponse.json({ error: "打包任务不存在或已过期,请重新打包" }, { status: 404 });
|
||||||
|
if (request.nextUrl.searchParams.get("download") === "1") {
|
||||||
|
if ((task.remote || task.qiniu) && task.status === "completed" && task.cdnUrl)
|
||||||
|
return NextResponse.redirect(task.cdnUrl, 307);
|
||||||
|
if (task.status !== "completed" || !task.zipFile) return NextResponse.json({ error: "ZIP 尚未准备好" }, { status: 409 });
|
||||||
|
if (task.cdnUrl && request.nextUrl.searchParams.get("local") !== "1")
|
||||||
|
return NextResponse.redirect(task.cdnUrl, 307);
|
||||||
|
const info = await stat(task.zipFile.path).catch(() => null);
|
||||||
|
if (!info || info.size !== task.zipFile.bytes) return NextResponse.json({ error: "下载文件已过期,请重新打包" }, { status: 410 });
|
||||||
|
const etag = `"${task.id}-${info.size}"`;
|
||||||
|
const headers: Record<string, string> = { "Content-Type": "application/zip", "Content-Disposition": task.contentDisposition!,
|
||||||
|
"Accept-Ranges": "bytes", "ETag": etag, "Cache-Control": "private, no-store",
|
||||||
|
"X-Download-Success-Count": String(task.successCount), "X-Download-Failed-Count": String(task.failedCount) };
|
||||||
|
const ifRange = request.headers.get("if-range");
|
||||||
|
let range;
|
||||||
|
try { range = parseDownloadByteRange(!ifRange || ifRange === etag ? request.headers.get("range") : null, info.size); }
|
||||||
|
catch { return new NextResponse(null, { status: 416, headers: { ...headers, "Content-Range": `bytes */${info.size}` } }); }
|
||||||
|
headers["Content-Length"] = String(range ? range.end - range.start + 1 : info.size);
|
||||||
|
if (range) headers["Content-Range"] = `bytes ${range.start}-${range.end}/${info.size}`;
|
||||||
|
return new NextResponse(readDownloadZip(task.zipFile.path, range || undefined), { status: range ? 206 : 200, headers });
|
||||||
|
}
|
||||||
|
if (task.status === "pending" || task.status === "running") schedule(task, request);
|
||||||
|
return NextResponse.json({ success: true, task: serializeTask(task) }, { headers: { "Cache-Control": "no-store" } });
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "查询打包任务失败,请稍后重试" }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import { streamDownloadZip } from "@/lib/canvas/download-zip-stream";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import JSZip from "jszip";
|
import JSZip from "jszip";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
@ -159,13 +160,7 @@ export async function POST(request: NextRequest) {
|
|||||||
console.warn("[CanvasDownloadZip] Partial download failures:", failures);
|
console.warn("[CanvasDownloadZip] Partial download failures:", failures);
|
||||||
}
|
}
|
||||||
|
|
||||||
const zipBuffer = await zip.generateAsync({
|
return new NextResponse(streamDownloadZip(zip), {
|
||||||
type: "nodebuffer",
|
|
||||||
compression: "DEFLATE",
|
|
||||||
compressionOptions: { level: 6 },
|
|
||||||
});
|
|
||||||
|
|
||||||
return new NextResponse(zipBuffer, {
|
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/zip",
|
"Content-Type": "application/zip",
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import { executeCanvasImageResponse } from "@/lib/canvas/generate-image-response
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { getCanvasImageTaskForUser } from "@/lib/canvas/image-task-queue";
|
import { getCanvasImageTaskForUser } from "@/lib/canvas/image-task-queue";
|
||||||
|
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
|
||||||
|
|
||||||
export const maxDuration = 1200;
|
export const maxDuration = 1200;
|
||||||
|
|
||||||
@ -23,13 +24,15 @@ export async function GET(request: Request) {
|
|||||||
return NextResponse.json({ success: false, error: "任务不存在" }, { status: 404 });
|
return NextResponse.json({ success: false, error: "任务不存在" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const failure = task.status === "failed" ? getRequestFailureDetails(task.error) : undefined;
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
task: {
|
task: {
|
||||||
id: task.id,
|
id: task.id,
|
||||||
status: task.status,
|
status: task.status,
|
||||||
attempts: task.attempts,
|
attempts: task.attempts,
|
||||||
error: task.error || null,
|
error: failure ? formatRequestFailure(failure, task.id) : null,
|
||||||
|
failure,
|
||||||
result: task.result || null,
|
result: task.result || null,
|
||||||
createdAt: task.createdAt,
|
createdAt: task.createdAt,
|
||||||
startedAt: task.startedAt,
|
startedAt: task.startedAt,
|
||||||
|
|||||||
@ -14,6 +14,7 @@ import {
|
|||||||
ownsTaskProject,
|
ownsTaskProject,
|
||||||
} from "@/lib/video-canvas/task-store";
|
} from "@/lib/video-canvas/task-store";
|
||||||
import { runCanvasGenerationQueue } from "@/lib/video-canvas/task-worker";
|
import { runCanvasGenerationQueue } from "@/lib/video-canvas/task-worker";
|
||||||
|
import { preflightCanvasProductionRequests } from "@/lib/video-canvas/production-services";
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
export const maxDuration = 900;
|
export const maxDuration = 900;
|
||||||
|
|
||||||
@ -28,7 +29,7 @@ async function owner(projectId: unknown) {
|
|||||||
}
|
}
|
||||||
const fail = (error: unknown) =>
|
const fail = (error: unknown) =>
|
||||||
NextResponse.json(
|
NextResponse.json(
|
||||||
{ success: false, error: error instanceof Error ? error.message : "任务操作失败" },
|
{ success: false, error: error instanceof Error ? error.message : "任务操作失败", code: (error as any)?.code },
|
||||||
{ status: Number((error as any)?.status) || (error instanceof SyntaxError ? 400 : 500) },
|
{ status: Number((error as any)?.status) || (error instanceof SyntaxError ? 400 : 500) },
|
||||||
);
|
);
|
||||||
const kick = (userId: string, projectId: string) =>
|
const kick = (userId: string, projectId: string) =>
|
||||||
@ -65,7 +66,8 @@ export async function POST(request: Request) {
|
|||||||
throw Object.assign(Error("剪辑参数无效"), { status: 400 });
|
throw Object.assign(Error("剪辑参数无效"), { status: 400 });
|
||||||
if (parsed.data.kind === "video-upscale" && !videoUpscaleSchema.safeParse(parsed.data.params).success) throw Object.assign(Error("视频高清参数无效"), {status:400});
|
if (parsed.data.kind === "video-upscale" && !videoUpscaleSchema.safeParse(parsed.data.params).success) throw Object.assign(Error("视频高清参数无效"), {status:400});
|
||||||
const userId = await owner(parsed.data.projectId);
|
const userId = await owner(parsed.data.projectId);
|
||||||
const task = await createCanvasGenerationTask(userId, parsed.data);
|
const task = await createCanvasGenerationTask(userId, parsed.data,
|
||||||
|
() => preflightCanvasProductionRequests([parsed.data]));
|
||||||
kick(userId, parsed.data.projectId);
|
kick(userId, parsed.data.projectId);
|
||||||
return NextResponse.json({ success: true, task }, { status: 202 });
|
return NextResponse.json({ success: true, task }, { status: 202 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import {
|
|||||||
ownsTaskProject,
|
ownsTaskProject,
|
||||||
} from "@/lib/video-canvas/task-store";
|
} from "@/lib/video-canvas/task-store";
|
||||||
import { runCanvasGenerationQueue } from "@/lib/video-canvas/task-worker";
|
import { runCanvasGenerationQueue } from "@/lib/video-canvas/task-worker";
|
||||||
|
import { preflightCanvasProductionRequests } from "@/lib/video-canvas/production-services";
|
||||||
export const runtime = "nodejs",
|
export const runtime = "nodejs",
|
||||||
maxDuration = 900;
|
maxDuration = 900;
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
@ -27,12 +28,13 @@ export async function POST(request: Request) {
|
|||||||
userId = session.user.id;
|
userId = session.user.id;
|
||||||
if (!(await ownsTaskProject(userId, projectId)))
|
if (!(await ownsTaskProject(userId, projectId)))
|
||||||
return NextResponse.json({ error: "画布不存在" }, { status: 404 });
|
return NextResponse.json({ error: "画布不存在" }, { status: 404 });
|
||||||
const tasks = await createCanvasGroupTasks(userId, parsed.data);
|
const tasks = await createCanvasGroupTasks(userId, parsed.data,
|
||||||
|
() => preflightCanvasProductionRequests(parsed.data));
|
||||||
after(() => runCanvasGenerationQueue(userId, projectId));
|
after(() => runCanvasGenerationQueue(userId, projectId));
|
||||||
return NextResponse.json({ success: true, tasks }, { status: 202 });
|
return NextResponse.json({ success: true, tasks }, { status: 202 });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: e instanceof Error ? e.message : "编组执行失败" },
|
{ error: e instanceof Error ? e.message : "编组执行失败", code: (e as any)?.code },
|
||||||
{ status: Number((e as any)?.status) || 400 }
|
{ status: Number((e as any)?.status) || 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -976,7 +976,8 @@ export async function POST(request: NextRequest) {
|
|||||||
const annotatedFilename = `canvas-local-edit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`;
|
const annotatedFilename = `canvas-local-edit-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`;
|
||||||
const annotatedUpload = await uploadFile(
|
const annotatedUpload = await uploadFile(
|
||||||
annotatedFilename,
|
annotatedFilename,
|
||||||
toArrayBuffer(annotatedBuffer)
|
toArrayBuffer(annotatedBuffer),
|
||||||
|
{ preferQiniuForm: true }
|
||||||
);
|
);
|
||||||
const prompt = buildLocalEditPrompt(regions);
|
const prompt = buildLocalEditPrompt(regions);
|
||||||
const manualRegionReferenceImageUrls = regions.flatMap((region) =>
|
const manualRegionReferenceImageUrls = regions.flatMap((region) =>
|
||||||
|
|||||||
@ -1,15 +1,21 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { callQwen3Vl } from "@/lib/ai/qwen3-vl";
|
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 { createLogger } from "@/lib/observability/logger";
|
||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
|
import { detectCanvasTextRegions } from "@/lib/canvas/text-edit-ocr";
|
||||||
|
|
||||||
export const runtime = "nodejs";
|
export const runtime = "nodejs";
|
||||||
export const maxDuration = 120;
|
export const maxDuration = 120;
|
||||||
|
|
||||||
const requestSchema = z.object({
|
const requestSchema = z.object({
|
||||||
imageUrl: z.string().min(1, "图片地址不能为空"),
|
imageUrl: z.string().min(1, "图片地址不能为空"),
|
||||||
|
mode: z.literal("local").optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const OCR_IMAGE_FETCH_TIMEOUT_MS = 15000;
|
const OCR_IMAGE_FETCH_TIMEOUT_MS = 15000;
|
||||||
@ -90,6 +96,39 @@ 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) {
|
function shouldUseDataUrlFallback(error: unknown) {
|
||||||
const message =
|
const message =
|
||||||
error instanceof Error ? error.message.toLowerCase() : String(error || "").toLowerCase();
|
error instanceof Error ? error.message.toLowerCase() : String(error || "").toLowerCase();
|
||||||
@ -147,6 +186,16 @@ export async function POST(request: Request) {
|
|||||||
return NextResponse.json({ success: false, error: "仅支持 URL 图片,不允许 base64 传输" }, { status: 400 });
|
return NextResponse.json({ success: false, error: "仅支持 URL 图片,不允许 base64 传输" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (parsed.data.mode === "local") {
|
||||||
|
const data = await detectCanvasTextRegions(imageUrl);
|
||||||
|
return NextResponse.json({ success: true, data });
|
||||||
|
}
|
||||||
|
|
||||||
|
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" });
|
logger.debug("model_selected", { model: "qwen3-vl" });
|
||||||
const prompt = [
|
const prompt = [
|
||||||
"你是图片文字识别助手。",
|
"你是图片文字识别助手。",
|
||||||
@ -191,15 +240,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const parsedJson = parseJsonText(text || "");
|
const parsedJson = parseJsonText(text || "");
|
||||||
let items: OcrItem[] = [];
|
const items = Array.isArray(parsedJson?.items)
|
||||||
|
? sanitizeItems(parsedJson.items)
|
||||||
if (parsedJson && Array.isArray(parsedJson.items)) {
|
: fallbackItemsFromRaw(text);
|
||||||
items = sanitizeItems(parsedJson.items);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (items.length === 0 && text) {
|
|
||||||
items = fallbackItemsFromRaw(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
@ -213,7 +256,7 @@ export async function POST(request: Request) {
|
|||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
success: false,
|
success: false,
|
||||||
error: error instanceof Error ? error.message : "文字识别失败",
|
error: "图片文字识别暂不可用,请稍后重试",
|
||||||
},
|
},
|
||||||
{ status: 500 },
|
{ status: 500 },
|
||||||
);
|
);
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
@ -22,6 +23,11 @@ import { createKrea } from "@/lib/ai/providers/krea";
|
|||||||
import { createVolcanoVision } from "@/lib/ai/providers/volcano-vision";
|
import { createVolcanoVision } from "@/lib/ai/providers/volcano-vision";
|
||||||
import { isImageGenerationModelDescriptor } from "@/lib/ai/model-classification";
|
import { isImageGenerationModelDescriptor } from "@/lib/ai/model-classification";
|
||||||
import { normalizeOptionalHexColor } from "@/lib/canvas/text-edit-colors";
|
import { normalizeOptionalHexColor } from "@/lib/canvas/text-edit-colors";
|
||||||
|
import { editCanvasTextLocally, LocalTextEditError } from "@/lib/canvas/text-edit-local";
|
||||||
|
import { TEXT_EDIT_MAX_PIXELS } from "@/lib/canvas/text-edit-ocr";
|
||||||
|
import { textEditRegionSchema } from "@/lib/canvas/text-edit-region";
|
||||||
|
import { fetchImageBufferFromUrl } from "@/lib/ai/rmbg/service";
|
||||||
|
import { trackRuntimeWork } from "@/lib/observability/active-work";
|
||||||
import { createLogger } from "@/lib/observability/logger";
|
import { createLogger } from "@/lib/observability/logger";
|
||||||
import { uploadFile } from "@/lib/storage/service";
|
import { uploadFile } from "@/lib/storage/service";
|
||||||
|
|
||||||
@ -39,11 +45,13 @@ const textItemSchema = z.object({
|
|||||||
editedText: z.string().optional(),
|
editedText: z.string().optional(),
|
||||||
textColor: z.string().optional(),
|
textColor: z.string().optional(),
|
||||||
action: z.enum(["replace", "delete"]).optional(),
|
action: z.enum(["replace", "delete"]).optional(),
|
||||||
|
region: textEditRegionSchema.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const requestSchema = z.object({
|
const requestSchema = z.object({
|
||||||
imageUrl: z.string().min(1, "图片地址不能为空"),
|
imageUrl: z.string().min(1, "图片地址不能为空"),
|
||||||
items: z.array(textItemSchema).min(1, "至少需要一条文字修改"),
|
items: z.array(textItemSchema).min(1, "至少需要一条文字修改"),
|
||||||
|
mode: z.literal("local").optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const SUPPORTED_TEXT_EDIT_PROVIDER_TYPES = new Set([
|
const SUPPORTED_TEXT_EDIT_PROVIDER_TYPES = new Set([
|
||||||
@ -614,6 +622,38 @@ export async function POST(request: Request) {
|
|||||||
return NextResponse.json({ success: false, error: "未检测到有效的文字改动或删除" }, { status: 400 });
|
return NextResponse.json({ success: false, error: "未检测到有效的文字改动或删除" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (parsed.data.mode === "local") {
|
||||||
|
const regionsById = new Map(parsed.data.items.map((item) => [item.id, item.region]));
|
||||||
|
const edits = [
|
||||||
|
...replacements,
|
||||||
|
...deletions.map((item) => ({ ...item, editedText: "", textColor: undefined })),
|
||||||
|
].map((item) => {
|
||||||
|
const region = regionsById.get(item.id);
|
||||||
|
if (!region) throw new LocalTextEditError("文字缺少位置,请重新识别后再应用");
|
||||||
|
if (item.editedText.length > 400) throw new LocalTextEditError("每条替换文字最多 400 个字符");
|
||||||
|
return { ...item, region };
|
||||||
|
});
|
||||||
|
if (edits.length > 50) throw new LocalTextEditError("每次最多编辑 50 条文字");
|
||||||
|
return await trackRuntimeWork(async () => {
|
||||||
|
const source = await fetchImageBufferFromUrl(imageUrl);
|
||||||
|
const result = await editCanvasTextLocally(source, edits, TEXT_EDIT_MAX_PIXELS);
|
||||||
|
const uploaded = await uploadFile(
|
||||||
|
`canvas-text-edit-${randomUUID()}.png`,
|
||||||
|
bufferToArrayBuffer(result),
|
||||||
|
{ preferQiniuForm: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
originalUrl: uploaded.url,
|
||||||
|
thumbnailUrl: uploaded.url,
|
||||||
|
model: "local-text-edit",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const models = await getEnabledAiModelsWithProvider();
|
const models = await getEnabledAiModelsWithProvider();
|
||||||
const candidates = getTextEditModelCandidates(models);
|
const candidates = getTextEditModelCandidates(models);
|
||||||
|
|
||||||
@ -645,6 +685,9 @@ export async function POST(request: Request) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (error instanceof LocalTextEditError) {
|
||||||
|
return NextResponse.json({ success: false, error: error.message }, { status: 422 });
|
||||||
|
}
|
||||||
logger.error("request_failed", error);
|
logger.error("request_failed", error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
|
|||||||
78
app/api/canvas/video-agent/route.ts
Normal file
78
app/api/canvas/video-agent/route.ts
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { getChatById, getMessagesByChatId } from "@/lib/db/queries";
|
||||||
|
import {
|
||||||
|
readOwnedVideoCanvas,
|
||||||
|
saveVideoAgentCanvas,
|
||||||
|
} from "@/lib/ai/canvas-agent-runtime/video-store";
|
||||||
|
import { AgentRunError } from "@/lib/ai/canvas-agent-runtime/store";
|
||||||
|
import { publicAgentError } from "@/lib/ai/canvas-agent-runtime/protocol";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const projectId = z.string().uuid().parse(new URL(request.url).searchParams.get("projectId"));
|
||||||
|
await readOwnedVideoCanvas(session.user.id, projectId);
|
||||||
|
// One stable conversation per video workspace survives browser reloads.
|
||||||
|
const chat = await getChatById({ id: projectId });
|
||||||
|
if (chat && chat.userId !== session.user.id) throw new AgentRunError("对话不存在", 404);
|
||||||
|
const messages = chat ? (await getMessagesByChatId({ id: projectId })).slice(-40) : [];
|
||||||
|
return NextResponse.json(
|
||||||
|
{ messages: messages.map(({ id, role, parts }) => ({ id, role, parts })) },
|
||||||
|
{ headers: { "Cache-Control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: publicAgentError(error) },
|
||||||
|
{
|
||||||
|
status:
|
||||||
|
error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveSchema = z.object({
|
||||||
|
projectId: z.string().uuid(),
|
||||||
|
baseRevision: z.string().datetime(),
|
||||||
|
canvasData: z.object({
|
||||||
|
nodes: z.array(z.record(z.unknown())).max(2000),
|
||||||
|
edges: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
source: z.string(),
|
||||||
|
target: z.string(),
|
||||||
|
type: z.string().optional(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.max(4000),
|
||||||
|
selectedNodeIds: z.array(z.string()).max(20),
|
||||||
|
viewport: z.object({
|
||||||
|
x: z.number().finite(),
|
||||||
|
y: z.number().finite(),
|
||||||
|
zoom: z.number().positive(),
|
||||||
|
}),
|
||||||
|
tool: z.literal("select"),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id) return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||||
|
try {
|
||||||
|
const body = saveSchema.parse(await request.json());
|
||||||
|
await saveVideoAgentCanvas(session.user.id, body.projectId, body.baseRevision, body.canvasData);
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: publicAgentError(error) },
|
||||||
|
{
|
||||||
|
status:
|
||||||
|
error instanceof AgentRunError ? error.status : error instanceof z.ZodError ? 400 : 503,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,7 +1,8 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { generatedImage, user, aiModel } from "@/lib/db/schema";
|
import { generatedImage, user, aiModel } from "@/lib/db/schema";
|
||||||
import { eq, desc, sql } from "drizzle-orm";
|
import { and, eq, desc, sql } from "drizzle-orm";
|
||||||
|
import { isRetiredStorageUrl, RETIRED_STORAGE_URL_PATTERN } from "@/lib/storage/retired-storage";
|
||||||
import { cachedPublicJson } from "@/lib/public-api/performance";
|
import { cachedPublicJson } from "@/lib/public-api/performance";
|
||||||
|
|
||||||
const FEATURED_TIMEOUT_MS = 1800;
|
const FEATURED_TIMEOUT_MS = 1800;
|
||||||
@ -57,13 +58,17 @@ export async function GET(request: NextRequest) {
|
|||||||
userName: user.name,
|
userName: user.name,
|
||||||
userEmail: user.email,
|
userEmail: user.email,
|
||||||
userDepartment: user.department,
|
userDepartment: user.department,
|
||||||
modelName: aiModel.displayName,
|
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)`,
|
||||||
totalCount: sql<number>`count(*) over()::int`,
|
totalCount: sql<number>`count(*) over()::int`,
|
||||||
})
|
})
|
||||||
.from(generatedImage)
|
.from(generatedImage)
|
||||||
.leftJoin(user, eq(generatedImage.userId, user.id))
|
.leftJoin(user, eq(generatedImage.userId, user.id))
|
||||||
.leftJoin(aiModel, eq(generatedImage.modelId, aiModel.modelId))
|
.where(and(
|
||||||
.where(eq(generatedImage.isFeatured, true))
|
eq(generatedImage.isFeatured, true),
|
||||||
|
sql`${generatedImage.originalUrl} !~* ${RETIRED_STORAGE_URL_PATTERN}`,
|
||||||
|
))
|
||||||
.orderBy(desc(generatedImage.featuredAt))
|
.orderBy(desc(generatedImage.featuredAt))
|
||||||
.limit(pageSize)
|
.limit(pageSize)
|
||||||
.offset(offset);
|
.offset(offset);
|
||||||
@ -74,7 +79,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return {
|
return {
|
||||||
images: featuredImages.map((img) => ({
|
images: featuredImages.map((img) => ({
|
||||||
id: img.id,
|
id: img.id,
|
||||||
thumbnailUrl: img.thumbnailUrl,
|
thumbnailUrl: isRetiredStorageUrl(img.thumbnailUrl) ? img.originalUrl : img.thumbnailUrl,
|
||||||
originalUrl: img.originalUrl,
|
originalUrl: img.originalUrl,
|
||||||
imageSize: img.imageSize,
|
imageSize: img.imageSize,
|
||||||
prompt: img.prompt,
|
prompt: img.prompt,
|
||||||
|
|||||||
7
app/api/feedback/route.ts
Normal file
7
app/api/feedback/route.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { feedbackGet, feedbackPost } from "@/lib/canvas/feedback-route";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export const POST = (request: Request) => feedbackPost(request, null);
|
||||||
|
export const GET = (request: Request) => feedbackGet(request, null);
|
||||||
@ -1,4 +1,8 @@
|
|||||||
import type { FlowBoardDraft, FlowBoardSnapshotData } from "@/lib/db/schema";
|
import type {
|
||||||
|
FlowBoardDraft,
|
||||||
|
FlowBoardSheetSnapshotData,
|
||||||
|
FlowBoardSnapshotData,
|
||||||
|
} from "@/lib/db/schema";
|
||||||
|
|
||||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
@ -8,6 +12,73 @@ function normalizeRecord(value: unknown): Record<string, unknown> | null {
|
|||||||
return isRecord(value) ? value : null;
|
return isRecord(value) ? value : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_FLOW_BOARD_CANVAS = {
|
||||||
|
backgroundColor: "#f7f8fb",
|
||||||
|
gridColor: "#d8dde8",
|
||||||
|
gridEnabled: false,
|
||||||
|
gridSize: 24,
|
||||||
|
};
|
||||||
|
|
||||||
|
function normalizeCanvasColor(value: unknown, fallback: string) {
|
||||||
|
return typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value)
|
||||||
|
? value.toLowerCase()
|
||||||
|
: fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFlowBoardCanvas(value: unknown): Record<string, unknown> {
|
||||||
|
const canvas = isRecord(value) ? value : {};
|
||||||
|
const requestedGridSize =
|
||||||
|
typeof canvas.gridSize === "number" && Number.isFinite(canvas.gridSize)
|
||||||
|
? Math.round(canvas.gridSize)
|
||||||
|
: DEFAULT_FLOW_BOARD_CANVAS.gridSize;
|
||||||
|
|
||||||
|
return {
|
||||||
|
backgroundColor: normalizeCanvasColor(
|
||||||
|
canvas.backgroundColor,
|
||||||
|
DEFAULT_FLOW_BOARD_CANVAS.backgroundColor
|
||||||
|
),
|
||||||
|
gridColor: normalizeCanvasColor(
|
||||||
|
canvas.gridColor,
|
||||||
|
DEFAULT_FLOW_BOARD_CANVAS.gridColor
|
||||||
|
),
|
||||||
|
gridEnabled:
|
||||||
|
typeof canvas.gridEnabled === "boolean"
|
||||||
|
? canvas.gridEnabled
|
||||||
|
: DEFAULT_FLOW_BOARD_CANVAS.gridEnabled,
|
||||||
|
gridSize: Math.min(64, Math.max(8, requestedGridSize)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSheetId(value: unknown, index: number) {
|
||||||
|
const id = typeof value === "string" ? value.trim().slice(0, 128) : "";
|
||||||
|
return id || `sheet-${index + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSheetTitle(value: unknown, index: number) {
|
||||||
|
const title = typeof value === "string" ? value.trim().slice(0, 128) : "";
|
||||||
|
return title || `画布 ${index + 1}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeFlowBoardSheet(
|
||||||
|
value: unknown,
|
||||||
|
index: number
|
||||||
|
): FlowBoardSheetSnapshotData | null {
|
||||||
|
if (!isRecord(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: normalizeSheetId(value.id, index),
|
||||||
|
title: normalizeSheetTitle(value.title, index),
|
||||||
|
children: Array.isArray(value.children)
|
||||||
|
? value.children.filter(isRecord)
|
||||||
|
: [],
|
||||||
|
viewport: normalizeRecord(value.viewport),
|
||||||
|
theme: normalizeRecord(value.theme),
|
||||||
|
canvas: normalizeFlowBoardCanvas(value.canvas),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeFlowBoardTitle(value: unknown) {
|
export function normalizeFlowBoardTitle(value: unknown) {
|
||||||
const title = String(value || "").trim();
|
const title = String(value || "").trim();
|
||||||
return title.slice(0, 256) || "未命名流程白板";
|
return title.slice(0, 256) || "未命名流程白板";
|
||||||
@ -17,15 +88,67 @@ export function normalizeFlowBoardSnapshot(
|
|||||||
value: unknown
|
value: unknown
|
||||||
): FlowBoardSnapshotData {
|
): FlowBoardSnapshotData {
|
||||||
const raw = isRecord(value) ? value : {};
|
const raw = isRecord(value) ? value : {};
|
||||||
|
const legacyChildren = Array.isArray(raw.children)
|
||||||
|
? raw.children.filter(isRecord)
|
||||||
|
: [];
|
||||||
|
const normalizedSheets = Array.isArray(raw.sheets)
|
||||||
|
? raw.sheets
|
||||||
|
.map(normalizeFlowBoardSheet)
|
||||||
|
.filter(
|
||||||
|
(sheet): sheet is FlowBoardSheetSnapshotData => Boolean(sheet)
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
const sheets =
|
||||||
|
normalizedSheets.length > 0
|
||||||
|
? normalizedSheets
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
id: "sheet-1",
|
||||||
|
title: "画布 1",
|
||||||
|
children: legacyChildren,
|
||||||
|
viewport: normalizeRecord(raw.viewport),
|
||||||
|
theme: normalizeRecord(raw.theme),
|
||||||
|
canvas: normalizeFlowBoardCanvas(raw.canvas),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const requestedActiveSheetId =
|
||||||
|
typeof raw.activeSheetId === "string" ? raw.activeSheetId.trim() : "";
|
||||||
|
const activeSheet =
|
||||||
|
sheets.find((sheet) => sheet.id === requestedActiveSheetId) || sheets[0];
|
||||||
|
const activeChildren = Array.isArray(raw.children)
|
||||||
|
? legacyChildren
|
||||||
|
: activeSheet.children;
|
||||||
|
const activeViewport = isRecord(raw.viewport)
|
||||||
|
? raw.viewport
|
||||||
|
: activeSheet.viewport;
|
||||||
|
const activeTheme = isRecord(raw.theme) ? raw.theme : activeSheet.theme;
|
||||||
|
const activeCanvas = isRecord(raw.canvas)
|
||||||
|
? normalizeFlowBoardCanvas(raw.canvas)
|
||||||
|
: normalizeFlowBoardCanvas(activeSheet.canvas);
|
||||||
|
const nextSheets = sheets.map((sheet) =>
|
||||||
|
sheet.id === activeSheet.id
|
||||||
|
? {
|
||||||
|
...sheet,
|
||||||
|
children: activeChildren,
|
||||||
|
viewport: activeViewport,
|
||||||
|
theme: activeTheme,
|
||||||
|
canvas: activeCanvas,
|
||||||
|
}
|
||||||
|
: sheet
|
||||||
|
);
|
||||||
const updatedAt =
|
const updatedAt =
|
||||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim()
|
typeof raw.updatedAt === "string" && raw.updatedAt.trim()
|
||||||
? raw.updatedAt
|
? raw.updatedAt
|
||||||
: new Date().toISOString();
|
: new Date().toISOString();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
children: Array.isArray(raw.children) ? raw.children.filter(isRecord) : [],
|
version: 2,
|
||||||
viewport: normalizeRecord(raw.viewport),
|
activeSheetId: activeSheet.id,
|
||||||
theme: normalizeRecord(raw.theme),
|
sheets: nextSheets,
|
||||||
|
children: activeChildren,
|
||||||
|
viewport: activeViewport,
|
||||||
|
theme: activeTheme,
|
||||||
|
canvas: activeCanvas,
|
||||||
updatedAt,
|
updatedAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
34
app/api/generated-image-preview/[key]/route.ts
Normal file
34
app/api/generated-image-preview/[key]/route.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { imageArchiveTask } from "@/lib/db/schema";
|
||||||
|
|
||||||
|
// The SHA-256 URL is a capability, like the provider's signed image URL. It must be
|
||||||
|
// readable by image nodes and reference-image providers without a session cookie.
|
||||||
|
export async function GET(request: NextRequest, { params }: { params: Promise<{ key: string }> }) {
|
||||||
|
const { key } = await params;
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(key)) return new NextResponse(null, { status: 404 });
|
||||||
|
const configured =
|
||||||
|
process.env.NEXT_PUBLIC_APP_URL || process.env.AUTH_URL || process.env.NEXTAUTH_URL;
|
||||||
|
const origin = configured
|
||||||
|
? new URL(configured).origin
|
||||||
|
: `http://localhost:${process.env.PORT || "3000"}`;
|
||||||
|
const sourceUrl = `${origin}/api/generated-image-preview/${key}`;
|
||||||
|
const [task] = await db
|
||||||
|
.select({ targetUrl: imageArchiveTask.targetUrl, metadata: imageArchiveTask.metadata })
|
||||||
|
.from(imageArchiveTask)
|
||||||
|
.where(eq(imageArchiveTask.sourceUrl, sourceUrl))
|
||||||
|
.limit(1);
|
||||||
|
if (task?.targetUrl) return NextResponse.redirect(task.targetUrl, 307);
|
||||||
|
const inline = (task?.metadata as { inlineSource?: string } | null)?.inlineSource;
|
||||||
|
const match = inline?.match(/^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=]+)$/i);
|
||||||
|
if (!match) return new NextResponse(null, { status: 404 });
|
||||||
|
return new NextResponse(Buffer.from(match[2], "base64"), {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": match[1],
|
||||||
|
"Cache-Control": "private, no-store",
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"Content-Security-Policy": "default-src 'none'; sandbox",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,7 +1,12 @@
|
|||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
|
import { isRetiredStorageUrl, normalizeLegacyAliyunStorageUrl, RETIRED_STORAGE_MESSAGE } from "@/lib/storage/retired-storage";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
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";
|
export const runtime = "nodejs";
|
||||||
|
const logger = createLogger("image.download");
|
||||||
|
|
||||||
const DEFAULT_QUALITY = 82;
|
const DEFAULT_QUALITY = 82;
|
||||||
const MAX_WIDTH = 4096;
|
const MAX_WIDTH = 4096;
|
||||||
@ -9,6 +14,7 @@ const MIN_WIDTH = 64;
|
|||||||
const MIN_QUALITY = 40;
|
const MIN_QUALITY = 40;
|
||||||
const MAX_QUALITY = 100;
|
const MAX_QUALITY = 100;
|
||||||
const FETCH_TIMEOUT_MS = 15000;
|
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_BYTES = 64 * 1024 * 1024;
|
||||||
const DEFAULT_MEMORY_CACHE_MAX_ITEMS = 256;
|
const DEFAULT_MEMORY_CACHE_MAX_ITEMS = 256;
|
||||||
|
|
||||||
@ -230,6 +236,7 @@ function resolveDirectImageTarget(
|
|||||||
requestedQuality: number | null,
|
requestedQuality: number | null,
|
||||||
requestedFormat: string | null
|
requestedFormat: string | null
|
||||||
): URL | null {
|
): URL | null {
|
||||||
|
if (isAlibabaModelImageUrl(target.toString())) return null;
|
||||||
if (!isBrowserImageRequest(request)) {
|
if (!isBrowserImageRequest(request)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -258,7 +265,19 @@ function redirectToDirectImage(target: URL): NextResponse {
|
|||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
const { searchParams } = request.nextUrl;
|
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();
|
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) {
|
if (!rawUrl) {
|
||||||
return NextResponse.json({ error: "Missing url parameter" }, { status: 400 });
|
return NextResponse.json({ error: "Missing url parameter" }, { status: 400 });
|
||||||
}
|
}
|
||||||
@ -274,6 +293,24 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: "Only http/https is supported" }, { status: 400 });
|
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)) {
|
if (isBlockedHost(target.hostname)) {
|
||||||
return NextResponse.json({ error: "Blocked target host" }, { status: 403 });
|
return NextResponse.json({ error: "Blocked target host" }, { status: 403 });
|
||||||
}
|
}
|
||||||
@ -285,8 +322,60 @@ export async function GET(request: NextRequest) {
|
|||||||
const directQuality = requestedQuality ? clamp(requestedQuality, MIN_QUALITY, MAX_QUALITY) : null;
|
const directQuality = requestedQuality ? clamp(requestedQuality, MIN_QUALITY, MAX_QUALITY) : null;
|
||||||
const requestedFormat = searchParams.get("f");
|
const requestedFormat = searchParams.get("f");
|
||||||
const forceProxy = searchParams.get("proxy") === "1";
|
const forceProxy = searchParams.get("proxy") === "1";
|
||||||
|
const original = searchParams.get("original") === "1";
|
||||||
|
|
||||||
if (!forceProxy) {
|
if (original && (requestedWidth || requestedQuality || requestedFormat)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Original images cannot be transformed" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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(
|
const directImageTarget = resolveDirectImageTarget(
|
||||||
request,
|
request,
|
||||||
target,
|
target,
|
||||||
@ -299,10 +388,12 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const cacheKey = `${target.toString()}|${width || "auto"}|${quality}|${requestedFormat || "auto"}`;
|
const cacheKey = original
|
||||||
|
? `${target.toString()}|original-v1`
|
||||||
|
: `${target.toString()}|${width || "auto"}|${quality}|${requestedFormat || "auto"}`;
|
||||||
const etag = buildEtag(cacheKey);
|
const etag = buildEtag(cacheKey);
|
||||||
const ifNoneMatch = request.headers.get("if-none-match");
|
const ifNoneMatch = request.headers.get("if-none-match");
|
||||||
if (ifNoneMatch && ifNoneMatch === etag) {
|
if (!original && ifNoneMatch && ifNoneMatch === etag) {
|
||||||
return new NextResponse(null, {
|
return new NextResponse(null, {
|
||||||
status: 304,
|
status: 304,
|
||||||
headers: {
|
headers: {
|
||||||
@ -312,7 +403,7 @@ export async function GET(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const cached = getCachedImageResponse(cacheKey);
|
const cached = original ? null : getCachedImageResponse(cacheKey);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
return buildImageResponse(cached.body, {
|
return buildImageResponse(cached.body, {
|
||||||
contentType: cached.contentType,
|
contentType: cached.contentType,
|
||||||
@ -322,32 +413,82 @@ export async function GET(request: NextRequest) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let upstreamResponse: Response;
|
const fetchSignal = AbortSignal.any([
|
||||||
try {
|
request.signal,
|
||||||
upstreamResponse = await fetch(target.toString(), {
|
AbortSignal.timeout(original ? 60_000 : isAlibabaModelImageUrl(target.toString()) || width && width <= 256 ? SMALL_PREVIEW_FETCH_TIMEOUT_MS : FETCH_TIMEOUT_MS),
|
||||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
]);
|
||||||
headers: {
|
const upstreamFailure = (error: unknown) => {
|
||||||
Accept: "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
|
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";
|
||||||
} catch (error) {
|
|
||||||
console.error("[ImageProxy] Upstream fetch failed:", error);
|
|
||||||
return NextResponse.json({ error: "Failed to fetch upstream image" }, { status: 502 });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!upstreamResponse.ok) {
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: `Upstream responded with ${upstreamResponse.status}` },
|
{ error: timedOut ? "读取源图片超时,请重试" : "源图片传输中断,请重试" },
|
||||||
{ status: 502 }
|
{ 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);
|
||||||
|
}
|
||||||
|
|
||||||
const contentType = upstreamResponse.headers.get("content-type") || "application/octet-stream";
|
if (!upstreamResponse.ok) {
|
||||||
if (!contentType.toLowerCase().startsWith("image/")) {
|
if (original) return downloadFailure(`HTTP ${upstreamResponse.status}`);
|
||||||
return NextResponse.json({ error: "Upstream is not an image" }, { status: 400 });
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const originalBuffer = Buffer.from(await upstreamResponse.arrayBuffer());
|
|
||||||
const isSvg = contentType.toLowerCase().includes("image/svg");
|
const isSvg = contentType.toLowerCase().includes("image/svg");
|
||||||
const isGif = contentType.toLowerCase().includes("image/gif");
|
const isGif = contentType.toLowerCase().includes("image/gif");
|
||||||
|
|
||||||
|
|||||||
@ -114,7 +114,7 @@ export async function POST(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
temperature: 0.2,
|
temperature: 0.2,
|
||||||
maxTokens: 1200,
|
maxOutputTokens: 1200,
|
||||||
} as any);
|
} as any);
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
|
|||||||
@ -45,6 +45,7 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
...result,
|
...result,
|
||||||
|
image_base64: body.includeBase64 === false ? undefined : result.image_base64,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ResizeServiceError) {
|
if (error instanceof ResizeServiceError) {
|
||||||
|
|||||||
@ -6,6 +6,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
import { preprocessProductImageWithRmbg } from "@/lib/scene-fusion/preprocess-product";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
@ -69,7 +70,6 @@ const SCENE_FUSION_REQUEST_STAGGER_MS = 350;
|
|||||||
const SCENE_FUSION_AGENT_TIMEOUT_MS = 20000;
|
const SCENE_FUSION_AGENT_TIMEOUT_MS = 20000;
|
||||||
const SCENE_FUSION_AGENT_MAX_WORKERS = 3;
|
const SCENE_FUSION_AGENT_MAX_WORKERS = 3;
|
||||||
const SCENE_FUSION_PROCESS_MAX_WORKERS = 4;
|
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_TIMEOUT_MS = 20_000;
|
||||||
const SCENE_FUSION_ECHO_HASH_THRESHOLD = 8;
|
const SCENE_FUSION_ECHO_HASH_THRESHOLD = 8;
|
||||||
const SCENE_FUSION_REVIEW_TIMEOUT_MS = 25_000;
|
const SCENE_FUSION_REVIEW_TIMEOUT_MS = 25_000;
|
||||||
@ -236,41 +236,6 @@ 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 {
|
function normalizeUrlForCompare(input: string): string {
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(input);
|
const parsed = new URL(input);
|
||||||
@ -988,102 +953,6 @@ 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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建缩略图
|
* 创建缩略图
|
||||||
*/
|
*/
|
||||||
@ -2436,12 +2305,13 @@ export async function POST(request: Request) {
|
|||||||
productImageUrl = await uploadBase64ToS3(productImage, "scene-fusion-product");
|
productImageUrl = await uploadBase64ToS3(productImage, "scene-fusion-product");
|
||||||
}
|
}
|
||||||
const shouldForcePreRmbg = resolvedSceneMode === "random-bg";
|
const shouldForcePreRmbg = resolvedSceneMode === "random-bg";
|
||||||
const preprocessedProduct = await preprocessProductImageWithRmbg(
|
const preprocessedProduct = await preprocessProductImageWithRmbg({
|
||||||
request,
|
request,
|
||||||
requestId,
|
requestId,
|
||||||
|
userId: session.user.id,
|
||||||
productImageUrl,
|
productImageUrl,
|
||||||
shouldForcePreRmbg ? true : config.preRmbgEnabled
|
preRmbgEnabled: shouldForcePreRmbg ? true : config.preRmbgEnabled,
|
||||||
);
|
});
|
||||||
const fusionProductImageUrl = preprocessedProduct.productImageUrl;
|
const fusionProductImageUrl = preprocessedProduct.productImageUrl;
|
||||||
logger.info("pre_rmbg_resolved", {
|
logger.info("pre_rmbg_resolved", {
|
||||||
requestId,
|
requestId,
|
||||||
|
|||||||
@ -1,15 +1,18 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { resolveSiteBranding } from "@/lib/site-branding";
|
||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import {
|
import {
|
||||||
|
aiModel,
|
||||||
aiProvider,
|
aiProvider,
|
||||||
siteSettings,
|
siteSettings,
|
||||||
systemSettingHistory,
|
systemSettingHistory,
|
||||||
systemSettingSnapshot,
|
systemSettingSnapshot,
|
||||||
systemSettings,
|
systemSettings,
|
||||||
} from "@/lib/db/schema";
|
} from "@/lib/db/schema";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||||
|
import { omitAgentWorkflowPrompts } from "@/lib/agents/workflow-loading";
|
||||||
import { auth } from "@/app/(auth)/auth";
|
import { auth } from "@/app/(auth)/auth";
|
||||||
import { isAgentWorkflowAdminType, isSiteAdminType } from "@/lib/middleware/admin";
|
import { isAgentWorkflowAdminType, isSiteAdminType } from "@/lib/middleware/admin";
|
||||||
import {
|
import {
|
||||||
@ -152,7 +155,7 @@ import {
|
|||||||
} from "@/lib/ai-wash/config";
|
} from "@/lib/ai-wash/config";
|
||||||
import { STYLE_PRO_CONFIG_KEY, normalizeStyleProConfig } from "@/lib/style-pro/config";
|
import { STYLE_PRO_CONFIG_KEY, normalizeStyleProConfig } from "@/lib/style-pro/config";
|
||||||
import { withTimeout } from "@/lib/public-api/performance";
|
import { withTimeout } from "@/lib/public-api/performance";
|
||||||
import type { AgentCategoryTreeConfig } from "@/types/agent";
|
import type { AgentCategoryTreeConfig, AgentWorkflowUiConfig } from "@/types/agent";
|
||||||
|
|
||||||
// Historically stored as "home_surprise_categories" but used for the featured gallery categories.
|
// Historically stored as "home_surprise_categories" but used for the featured gallery categories.
|
||||||
const HOME_SURPRISE_CATEGORIES_KEY = "home_surprise_categories";
|
const HOME_SURPRISE_CATEGORIES_KEY = "home_surprise_categories";
|
||||||
@ -552,6 +555,9 @@ function normalizeAgentCategoryTreeConfig(value: unknown): AgentCategoryTreeConf
|
|||||||
type PublicSiteSettingsScope =
|
type PublicSiteSettingsScope =
|
||||||
| "agent-brand-model"
|
| "agent-brand-model"
|
||||||
| "agent-canvas"
|
| "agent-canvas"
|
||||||
|
| "agent-canvas-base"
|
||||||
|
| "agent-workflow-templates"
|
||||||
|
| "agent-entry"
|
||||||
| "agent-presets"
|
| "agent-presets"
|
||||||
| "auth"
|
| "auth"
|
||||||
| "branding"
|
| "branding"
|
||||||
@ -563,6 +569,9 @@ type PublicSiteSettingsScope =
|
|||||||
const PUBLIC_SITE_SETTINGS_SCOPES = new Set<string>([
|
const PUBLIC_SITE_SETTINGS_SCOPES = new Set<string>([
|
||||||
"agent-brand-model",
|
"agent-brand-model",
|
||||||
"agent-canvas",
|
"agent-canvas",
|
||||||
|
"agent-canvas-base",
|
||||||
|
"agent-workflow-templates",
|
||||||
|
"agent-entry",
|
||||||
"agent-presets",
|
"agent-presets",
|
||||||
"auth",
|
"auth",
|
||||||
"branding",
|
"branding",
|
||||||
@ -606,22 +615,60 @@ const HOME_SITE_SETTINGS_FALLBACK: Record<string, unknown> = {
|
|||||||
lovartHomeSidebarConfig: normalizeLovartHomeSidebarConfig(undefined),
|
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(
|
function createScopedSiteSettingsResponse(
|
||||||
scope: PublicSiteSettingsScope,
|
scope: PublicSiteSettingsScope,
|
||||||
data: Record<string, unknown>,
|
data: Record<string, unknown>,
|
||||||
cacheStatus: "HIT" | "MISS" | "STALE" | "FALLBACK" = "MISS",
|
cacheStatus: "HIT" | "MISS" | "STALE" | "FALLBACK" = "MISS",
|
||||||
cacheKey: string = scope,
|
cacheKey: string = scope,
|
||||||
options: { fallback?: boolean; startedAt?: number } = {}
|
options: { fallback?: boolean; startedAt?: number; etag?: string } = {}
|
||||||
) {
|
) {
|
||||||
if (cacheStatus === "MISS") {
|
if (cacheStatus === "MISS") {
|
||||||
setScopedSiteSettingsCache(
|
setScopedSiteSettingsCache(
|
||||||
cacheKey,
|
cacheKey,
|
||||||
data,
|
data,
|
||||||
PUBLIC_SITE_SETTINGS_CACHE_TTL_MS
|
PUBLIC_SITE_SETTINGS_CACHE_TTL_MS,
|
||||||
|
options.etag
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = NextResponse.json(data);
|
const response = NextResponse.json(data);
|
||||||
|
if (options.etag) response.headers.set("ETag", options.etag);
|
||||||
// Lightweight public settings change rarely; keep them browser-local briefly
|
// Lightweight public settings change rarely; keep them browser-local briefly
|
||||||
// so page opens do not repeatedly wait on the large full settings endpoint.
|
// so page opens do not repeatedly wait on the large full settings endpoint.
|
||||||
response.headers.set(
|
response.headers.set(
|
||||||
@ -641,7 +688,7 @@ function createScopedSiteSettingsResponse(
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readScopedSiteSettings(keys: string[]) {
|
async function readScopedSiteSettings(keys: string[], omitWorkflowSteps = false) {
|
||||||
const [settings, settingRows] = await Promise.all([
|
const [settings, settingRows] = await Promise.all([
|
||||||
db
|
db
|
||||||
.select()
|
.select()
|
||||||
@ -649,8 +696,14 @@ async function readScopedSiteSettings(keys: string[]) {
|
|||||||
.limit(1)
|
.limit(1)
|
||||||
.then((rows) => rows[0]),
|
.then((rows) => rows[0]),
|
||||||
keys.length > 0
|
keys.length > 0
|
||||||
? db
|
? (omitWorkflowSteps
|
||||||
.select()
|
? 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())
|
||||||
.from(systemSettings)
|
.from(systemSettings)
|
||||||
.where(inArray(systemSettings.key, keys))
|
.where(inArray(systemSettings.key, keys))
|
||||||
: Promise.resolve([]),
|
: Promise.resolve([]),
|
||||||
@ -663,12 +716,12 @@ async function readScopedSiteSettings(keys: string[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createBrandingSettings(settings: Record<string, unknown> | undefined) {
|
function createBrandingSettings(settings: Record<string, unknown> | undefined) {
|
||||||
return {
|
return resolveSiteBranding({
|
||||||
siteName: String(settings?.siteName || "𝗕𝘂𝗬𝗶"),
|
siteName: String(settings?.siteName || "𝗕𝘂𝗬𝗶"),
|
||||||
siteLogo: settings?.siteLogo || null,
|
siteLogo: String(settings?.siteLogo || ""),
|
||||||
siteLogoDark: settings?.siteLogoDark || null,
|
siteLogoDark: String(settings?.siteLogoDark || ""),
|
||||||
favicon: settings?.favicon || null,
|
favicon: String(settings?.favicon || ""),
|
||||||
};
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getScopedPublicSiteSettings(
|
async function getScopedPublicSiteSettings(
|
||||||
@ -676,6 +729,7 @@ async function getScopedPublicSiteSettings(
|
|||||||
options: {
|
options: {
|
||||||
brandName?: string;
|
brandName?: string;
|
||||||
cacheKey?: string;
|
cacheKey?: string;
|
||||||
|
etag?: string;
|
||||||
} = {}
|
} = {}
|
||||||
) {
|
) {
|
||||||
if (scope === "auth") {
|
if (scope === "auth") {
|
||||||
@ -737,23 +791,17 @@ async function getScopedPublicSiteSettings(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (scope === "agent-canvas") {
|
if (scope === "agent-workflow-templates") {
|
||||||
const { settings, valueByKey } = await readScopedSiteSettings([
|
const [setting] = await db.select({ value: systemSettings.value })
|
||||||
REALTIME_CANVAS_CONFIG_KEY,
|
.from(systemSettings).where(eq(systemSettings.key, AGENT_WORKFLOW_UI_CONFIG_KEY)).limit(1);
|
||||||
REALTIME_CANVAS_MODE_ICON_CONFIG_KEY,
|
const config = normalizeAgentWorkflowUiConfig(setting?.value);
|
||||||
CANVAS_TOOLBAR_CONFIG_SETTING_KEY,
|
return createScopedSiteSettingsResponse(scope, {
|
||||||
LAYER_SPLIT_CONFIG_KEY,
|
steps: omitAgentWorkflowPrompts(config.steps),
|
||||||
ANGLE_EDIT_CONFIG_KEY,
|
}, "MISS", options.cacheKey || scope, { etag: options.etag });
|
||||||
CANVAS_AGENT_MODE_ENABLED_KEY,
|
}
|
||||||
...CANVAS_AGENT_FEATURE_SETTING_KEYS,
|
|
||||||
VIDEO_CANVAS_ENABLED_KEY,
|
if (scope === "agent-canvas" || scope === "agent-canvas-base" || scope === "agent-entry") {
|
||||||
VIDEO_CANVAS_SIDEBAR_ENABLED_KEY,
|
const { settings, valueByKey } = await readScopedSiteSettings(AGENT_CANVAS_SETTING_KEYS, scope !== "agent-canvas");
|
||||||
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(
|
const canvasFeatureAvailability = await readCanvasFeatureAvailability(
|
||||||
valueByKey
|
valueByKey
|
||||||
);
|
);
|
||||||
@ -761,6 +809,8 @@ async function getScopedPublicSiteSettings(
|
|||||||
const videoCanvasSidebarEnabled = normalizeVideoCanvasSidebarEnabled(
|
const videoCanvasSidebarEnabled = normalizeVideoCanvasSidebarEnabled(
|
||||||
valueByKey.get(VIDEO_CANVAS_SIDEBAR_ENABLED_KEY)
|
valueByKey.get(VIDEO_CANVAS_SIDEBAR_ENABLED_KEY)
|
||||||
);
|
);
|
||||||
|
const rawUiConfig = valueByKey.get(AGENT_WORKFLOW_UI_CONFIG_KEY) as
|
||||||
|
Partial<AgentWorkflowUiConfig> | undefined;
|
||||||
return createScopedSiteSettingsResponse(scope, {
|
return createScopedSiteSettingsResponse(scope, {
|
||||||
...createBrandingSettings(typedSettings),
|
...createBrandingSettings(typedSettings),
|
||||||
agentEnabled: typedSettings?.agentEnabled ?? true,
|
agentEnabled: typedSettings?.agentEnabled ?? true,
|
||||||
@ -796,12 +846,20 @@ async function getScopedPublicSiteSettings(
|
|||||||
tripo3dEnabled: canvasFeatureAvailability.tripo3dEnabled,
|
tripo3dEnabled: canvasFeatureAvailability.tripo3dEnabled,
|
||||||
worldlabs3dEnabled: canvasFeatureAvailability.worldlabs3dEnabled,
|
worldlabs3dEnabled: canvasFeatureAvailability.worldlabs3dEnabled,
|
||||||
agentWorkflowUiConfig: normalizeAgentWorkflowUiConfig(
|
agentWorkflowUiConfig: normalizeAgentWorkflowUiConfig(
|
||||||
valueByKey.get(AGENT_WORKFLOW_UI_CONFIG_KEY)
|
scope === "agent-entry"
|
||||||
|
? {
|
||||||
|
steps: [],
|
||||||
|
pageFeatureSettings: rawUiConfig?.pageFeatureSettings,
|
||||||
|
businessModeSettings: rawUiConfig?.businessModeSettings,
|
||||||
|
}
|
||||||
|
: scope === "agent-canvas-base"
|
||||||
|
? { ...rawUiConfig, steps: [] }
|
||||||
|
: rawUiConfig
|
||||||
),
|
),
|
||||||
agentWorkflowShowcaseConfig: normalizeAgentWorkflowShowcaseConfig(
|
agentWorkflowShowcaseConfig: normalizeAgentWorkflowShowcaseConfig(
|
||||||
valueByKey.get(AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY)
|
valueByKey.get(AGENT_WORKFLOW_SHOWCASE_CONFIG_KEY)
|
||||||
),
|
),
|
||||||
});
|
}, "MISS", options.cacheKey || scope, { etag: options.etag });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (scope === "branding") {
|
if (scope === "branding") {
|
||||||
@ -1055,13 +1113,24 @@ export async function GET(request: NextRequest) {
|
|||||||
const cacheKey = brandName.trim()
|
const cacheKey = brandName.trim()
|
||||||
? `${scopedScope}:${brandName.trim().toLowerCase()}`
|
? `${scopedScope}:${brandName.trim().toLowerCase()}`
|
||||||
: scopedScope;
|
: 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);
|
const cached = getScopedSiteSettingsCache(cacheKey);
|
||||||
if (cached && cached.expiresAt > Date.now()) {
|
if (cached && cached.expiresAt > Date.now() && (!etag || cached.etag === etag)) {
|
||||||
return createScopedSiteSettingsResponse(
|
return createScopedSiteSettingsResponse(
|
||||||
scopedScope,
|
scopedScope,
|
||||||
cached.data,
|
cached.data,
|
||||||
"HIT",
|
"HIT",
|
||||||
cacheKey
|
cacheKey,
|
||||||
|
{ etag }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (cached && scopedScope !== "home") {
|
if (cached && scopedScope !== "home") {
|
||||||
@ -1072,6 +1141,7 @@ export async function GET(request: NextRequest) {
|
|||||||
const responsePromise = getScopedPublicSiteSettings(scopedScope, {
|
const responsePromise = getScopedPublicSiteSettings(scopedScope, {
|
||||||
brandName,
|
brandName,
|
||||||
cacheKey,
|
cacheKey,
|
||||||
|
etag,
|
||||||
});
|
});
|
||||||
return scopedScope === "home"
|
return scopedScope === "home"
|
||||||
? await withTimeout(responsePromise, 1600, "site-settings:home")
|
? await withTimeout(responsePromise, 1600, "site-settings:home")
|
||||||
@ -1541,7 +1611,7 @@ export async function GET(request: NextRequest) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const response = NextResponse.json({
|
const response = NextResponse.json({
|
||||||
...baseSettings,
|
...resolveSiteBranding(baseSettings),
|
||||||
lovartPromoText:
|
lovartPromoText:
|
||||||
baseSettings.lovartPromoText ||
|
baseSettings.lovartPromoText ||
|
||||||
"现在升级,立享 Kling 3.0 与 Nano Banana Pro,最高 5 折优惠",
|
"现在升级,立享 Kling 3.0 与 Nano Banana Pro,最高 5 折优惠",
|
||||||
@ -2143,6 +2213,14 @@ export async function PUT(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const data = updateSchema.parse(body);
|
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 {
|
const {
|
||||||
surpriseCategories,
|
surpriseCategories,
|
||||||
aiDetailGenerationEnabled,
|
aiDetailGenerationEnabled,
|
||||||
|
|||||||
35
app/api/tvstar/plugin/download/route.ts
Normal file
35
app/api/tvstar/plugin/download/route.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import JSZip from "jszip";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
|
const packageFiles = [
|
||||||
|
"package.json", "package-lock.json", "api-client.mjs", "cli.mjs", "mcp-server.mjs",
|
||||||
|
"yedir-canvas/SKILL.md", "yedir-canvas/agents/openai.yaml",
|
||||||
|
"yedir-canvas/references/operation-protocol.md",
|
||||||
|
];
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id || session.user.type === "guest") {
|
||||||
|
return NextResponse.json({ error: "请先登录正式账号" }, { status: 401 });
|
||||||
|
}
|
||||||
|
const zip = new JSZip();
|
||||||
|
const base = path.join(process.cwd(), "integrations", "openclaw");
|
||||||
|
try {
|
||||||
|
await Promise.all(packageFiles.map(async file => {
|
||||||
|
zip.file(`tvstar-mcp/${file}`, await readFile(path.join(base, file)));
|
||||||
|
}));
|
||||||
|
const archive = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
|
||||||
|
return new NextResponse(archive, { headers: {
|
||||||
|
"Content-Type": "application/zip",
|
||||||
|
"Content-Disposition": 'attachment; filename="tvstar-mcp.zip"',
|
||||||
|
"Cache-Control": "private, no-store",
|
||||||
|
} });
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "插件安装包暂不可用" }, { status: 503 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -6,6 +6,7 @@ import { eq } from "drizzle-orm";
|
|||||||
import { uploadFile } from "@/lib/storage/service";
|
import { uploadFile } from "@/lib/storage/service";
|
||||||
import {
|
import {
|
||||||
createMediaAssetRelation,
|
createMediaAssetRelation,
|
||||||
|
getDefaultStorageConfig,
|
||||||
getPointsSystemConfig,
|
getPointsSystemConfig,
|
||||||
getMediaAssetsByUserAndUrls,
|
getMediaAssetsByUserAndUrls,
|
||||||
upsertMediaAsset,
|
upsertMediaAsset,
|
||||||
@ -21,6 +22,27 @@ export const maxDuration = 600;
|
|||||||
const WATERMARK_SYNC_WAIT_TIMEOUT_MS = 20_000;
|
const WATERMARK_SYNC_WAIT_TIMEOUT_MS = 20_000;
|
||||||
const WATERMARK_POLL_INTERVAL_MS = 1200;
|
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配置
|
// 获取去水印API配置
|
||||||
async function getWatermarkRemoveConfig() {
|
async function getWatermarkRemoveConfig() {
|
||||||
try {
|
try {
|
||||||
@ -131,13 +153,16 @@ async function persistWatermarkResult(params: {
|
|||||||
processing_time?: number;
|
processing_time?: number;
|
||||||
}> {
|
}> {
|
||||||
try {
|
try {
|
||||||
const imageResponse = await fetch(params.processedImageUrl);
|
let resultUrl = await resolveStoredQiniuImageUrl(params.processedImageUrl);
|
||||||
if (!imageResponse.ok) {
|
if (!resultUrl) {
|
||||||
throw new Error("下载处理后的图片失败");
|
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 imageBuffer = await imageResponse.arrayBuffer();
|
|
||||||
const filename = `watermark-removed-${Date.now()}.png`;
|
|
||||||
const uploadResult = await uploadFile(filename, imageBuffer);
|
|
||||||
|
|
||||||
let saved = false;
|
let saved = false;
|
||||||
let saveError: unknown = null;
|
let saveError: unknown = null;
|
||||||
@ -150,8 +175,8 @@ async function persistWatermarkResult(params: {
|
|||||||
try {
|
try {
|
||||||
([savedImage] = await db.insert(generatedImage).values({
|
([savedImage] = await db.insert(generatedImage).values({
|
||||||
userId: params.userId,
|
userId: params.userId,
|
||||||
thumbnailUrl: uploadResult.url,
|
thumbnailUrl: resultUrl,
|
||||||
originalUrl: uploadResult.url,
|
originalUrl: resultUrl,
|
||||||
imageSize: "2K",
|
imageSize: "2K",
|
||||||
prompt: "去水印处理",
|
prompt: "去水印处理",
|
||||||
modelId: "watermark-remove",
|
modelId: "watermark-remove",
|
||||||
@ -184,9 +209,9 @@ async function persistWatermarkResult(params: {
|
|||||||
mediaType: "image",
|
mediaType: "image",
|
||||||
sourceType: "edited",
|
sourceType: "edited",
|
||||||
status: "ready",
|
status: "ready",
|
||||||
originalUrl: uploadResult.url,
|
originalUrl: resultUrl,
|
||||||
previewUrl: uploadResult.url,
|
previewUrl: resultUrl,
|
||||||
thumbnailUrl: uploadResult.url,
|
thumbnailUrl: resultUrl,
|
||||||
displayName: "去水印处理",
|
displayName: "去水印处理",
|
||||||
prompt: "去水印处理",
|
prompt: "去水印处理",
|
||||||
modelId: "watermark-remove",
|
modelId: "watermark-remove",
|
||||||
@ -217,8 +242,8 @@ async function persistWatermarkResult(params: {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
original_url: uploadResult.url,
|
original_url: resultUrl,
|
||||||
thumbnail_url: uploadResult.url,
|
thumbnail_url: resultUrl,
|
||||||
processing_time:
|
processing_time:
|
||||||
typeof params.startedAt === "number" ? (Date.now() - params.startedAt) / 1000 : undefined,
|
typeof params.startedAt === "number" ? (Date.now() - params.startedAt) / 1000 : undefined,
|
||||||
};
|
};
|
||||||
@ -362,7 +387,7 @@ export async function POST(request: NextRequest) {
|
|||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const { image_url } = body;
|
const { image_url } = body;
|
||||||
|
|
||||||
if (!image_url) {
|
if (typeof image_url !== "string" || !image_url) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "请提供图片URL" },
|
{ error: "请提供图片URL" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
@ -413,24 +438,24 @@ export async function POST(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 如果是 HTTP/HTTPS URL,下载后重新上传确保公网可访问
|
// 七牛上的公开图片可以直接交给去水印服务读取。
|
||||||
else if (image_url.startsWith("http://") || image_url.startsWith("https://")) {
|
else if (image_url.startsWith("http://") || image_url.startsWith("https://")) {
|
||||||
try {
|
const storedImageUrl = await resolveStoredQiniuImageUrl(image_url);
|
||||||
console.log("[WatermarkRemove] 下载原图并上传到S3...");
|
publicImageUrl = storedImageUrl || image_url;
|
||||||
const imageResponse = await fetch(image_url);
|
if (!storedImageUrl) {
|
||||||
if (!imageResponse.ok) {
|
try {
|
||||||
throw new Error("下载原图失败");
|
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);
|
||||||
}
|
}
|
||||||
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 {
|
} else {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -48,8 +48,13 @@ export default function CanvasStyleProPage() {
|
|||||||
const canvasData = result.data.canvasData;
|
const canvasData = result.data.canvasData;
|
||||||
const latestState = useCanvasStore.getState();
|
const latestState = useCanvasStore.getState();
|
||||||
setProject(result.data.id, result.data.title);
|
setProject(result.data.id, result.data.title);
|
||||||
if (latestState.nodes.length === 0 && latestState.edges.length === 0) {
|
if (
|
||||||
|
latestState.projectId !== id ||
|
||||||
|
(latestState.nodes.length === 0 && latestState.edges.length === 0)
|
||||||
|
) {
|
||||||
loadCanvas(canvasData);
|
loadCanvas(canvasData);
|
||||||
|
const revision = String(result.data.updatedAt || "");
|
||||||
|
useCanvasStore.getState().setCanvasRevision(revision, revision);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
17
app/dev/flow-board-preview/page.tsx
Normal file
17
app/dev/flow-board-preview/page.tsx
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { FlowBoardClient } from "@/components/flow-board/flow-board-client";
|
||||||
|
|
||||||
|
export default function FlowBoardPreviewPage() {
|
||||||
|
if (process.env.NODE_ENV === "production") {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<FlowBoardClient
|
||||||
|
previewMode
|
||||||
|
siteLogo={null}
|
||||||
|
siteLogoDark={null}
|
||||||
|
siteName="SnapGen"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
116
app/feedback/[id]/page.tsx
Normal file
116
app/feedback/[id]/page.tsx
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
import { notFound, redirect } from "next/navigation";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { auth } from "@/app/(auth)/auth";
|
||||||
|
import { feedbackReceipt, findCanvasFeedback } from "@/lib/canvas/feedback-store";
|
||||||
|
import { formatFeedbackTime } from "@/lib/canvas/feedback-contract";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function CanvasFeedbackPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
if (!z.string().uuid().safeParse(id).success) notFound();
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.user?.id || session.user.type === "guest") {
|
||||||
|
const query = new URLSearchParams({ callbackUrl: `/feedback/${id}` });
|
||||||
|
redirect(`/login?${query}`);
|
||||||
|
}
|
||||||
|
const feedback = await findCanvasFeedback(id);
|
||||||
|
if (!feedback || (feedback.userId !== session.user.id && session.user.type !== "admin"))
|
||||||
|
notFound();
|
||||||
|
const { reporter, project, request, client, userAgent } = feedback.snapshot;
|
||||||
|
const fields = [
|
||||||
|
["反馈编号", feedback.id],
|
||||||
|
["反馈人", `${reporter.name} · ${reporter.email} · ${reporter.department || "未登记部门"}`],
|
||||||
|
["用户编号", reporter.id],
|
||||||
|
["反馈时间", formatFeedbackTime(feedback.createdAt.toISOString())],
|
||||||
|
...(project.id ? [
|
||||||
|
["画布", `${project.title}(${project.id})`],
|
||||||
|
["对话编号", client.chatId || "未打开对话"],
|
||||||
|
["请求号", request?.requestId || "尚未获取"],
|
||||||
|
["任务或消息编号", request?.id || "未关联"],
|
||||||
|
["请求时间", request?.createdAt ? formatFeedbackTime(request.createdAt) : "未记录"],
|
||||||
|
["状态与模型", `${request?.status || "页面问题"} / ${request?.model || "未记录"}`],
|
||||||
|
[
|
||||||
|
"处理耗时",
|
||||||
|
request?.durationMs != null
|
||||||
|
? `${(request.durationMs / 1000).toFixed(1)} 秒`
|
||||||
|
: "未记录或尚未结束",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"资料来源",
|
||||||
|
request?.evidence === "browser"
|
||||||
|
? "浏览器当前对话,服务端尚无对应消息记录"
|
||||||
|
: "服务端记录及浏览器当前页面",
|
||||||
|
],
|
||||||
|
] : [["页面", project.title]]),
|
||||||
|
["页面版本", client.pageVersion],
|
||||||
|
["浏览器", userAgent],
|
||||||
|
[
|
||||||
|
"窗口与网络",
|
||||||
|
`${client.viewport.width} × ${client.viewport.height} · ${client.online ? "在线" : "离线"}`,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<main className="mx-auto max-w-3xl space-y-6 px-6 py-8 text-foreground">
|
||||||
|
<h1 className="text-2xl font-semibold">问题反馈</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">{feedbackReceipt(feedback).message}</p>
|
||||||
|
<dl className="space-y-3">
|
||||||
|
{fields.map(([label, value]) => (
|
||||||
|
<div key={label} className="grid gap-1 text-sm sm:grid-cols-[8rem_1fr]">
|
||||||
|
<dt className="text-muted-foreground">{label}</dt>
|
||||||
|
<dd className="whitespace-pre-wrap break-words">{value}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
{[
|
||||||
|
["用户说明", feedback.description || "未补充说明"],
|
||||||
|
["请求内容", request?.prompt || "未关联具体请求"],
|
||||||
|
["错误信息", request?.error || client.errors.join("\n") || "未记录明确错误"],
|
||||||
|
].map(([label, value]) => (
|
||||||
|
<section key={label} className="space-y-2">
|
||||||
|
<h2 className="text-base font-medium">{label}</h2>
|
||||||
|
<p className="whitespace-pre-wrap break-words rounded-lg bg-muted p-4 text-sm">{value}</p>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
{request?.parameters && Object.keys(request.parameters).length > 0 && (
|
||||||
|
<section className="space-y-2">
|
||||||
|
<h2 className="text-base font-medium">请求参数</h2>
|
||||||
|
<pre className="overflow-auto whitespace-pre-wrap break-all rounded-lg bg-muted p-4 text-sm">
|
||||||
|
{JSON.stringify(request.parameters, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
{project.id && client.nodes.length > 0 && (
|
||||||
|
<details className="text-sm">
|
||||||
|
<summary className="cursor-pointer">相关画布节点</summary>
|
||||||
|
<pre className="mt-3 overflow-auto whitespace-pre-wrap break-all">
|
||||||
|
{JSON.stringify(client.nodes, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{project.id && (
|
||||||
|
<>
|
||||||
|
<details className="text-sm">
|
||||||
|
<summary className="cursor-pointer">当前对话上下文</summary>
|
||||||
|
<div className="mt-4 space-y-4">
|
||||||
|
{client.messages.map((item) => (
|
||||||
|
<div key={item.id} className="space-y-1">
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{item.role === "user" ? "用户" : "助手"} · {item.id}
|
||||||
|
</p>
|
||||||
|
<p className="whitespace-pre-wrap break-words">{item.text}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
<a
|
||||||
|
className="inline-block text-sm underline underline-offset-4"
|
||||||
|
href={`/canvas/${project.id}`}
|
||||||
|
>
|
||||||
|
打开相关画布
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
298
app/globals.css
298
app/globals.css
@ -519,3 +519,301 @@
|
|||||||
padding: 0 12px 12px;
|
padding: 0 12px 12px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Lovart surface typography and controls, scoped to the home and image canvas. */
|
||||||
|
.lovart-home-surface,
|
||||||
|
.lovart-canvas-surface {
|
||||||
|
font-family: Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lovart-suggestion {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
gap: 8px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border: 1px solid #e5e5e5;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: white;
|
||||||
|
color: #333;
|
||||||
|
font-size: 13px;
|
||||||
|
white-space: nowrap;
|
||||||
|
transition: background-color 150ms, border-color 150ms;
|
||||||
|
}
|
||||||
|
.lovart-suggestion:hover { background: #f7f7f7; border-color: #d5d5d5; }
|
||||||
|
.lovart-suggestion:focus-visible,
|
||||||
|
.lovart-start-action:focus-visible { outline: 2px solid #8c8c8c; outline-offset: 3px; }
|
||||||
|
|
||||||
|
.lovart-start-action {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
gap: 9px;
|
||||||
|
min-width: 172px;
|
||||||
|
height: 40px;
|
||||||
|
padding: 0 16px;
|
||||||
|
border: 1px solid #e5e5e5;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: white;
|
||||||
|
color: #333;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 400;
|
||||||
|
box-shadow: 0 1px 2px rgb(0 0 0 / 4%);
|
||||||
|
transition: background-color 150ms, border-color 150ms;
|
||||||
|
}
|
||||||
|
.lovart-start-action:hover { background: #f7f7f7; border-color: #d4d4d4; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-header { border-bottom: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-composer { padding: 0 8px 8px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-composer > [data-canvas-chat-input-anchor] {
|
||||||
|
min-height: 120px;
|
||||||
|
border-color: #e5e5e5;
|
||||||
|
box-shadow: 0 1px 3px rgb(0 0 0 / 5%);
|
||||||
|
}
|
||||||
|
/* The promo backplate continues underneath the composer's rounded corners. */
|
||||||
|
.lovart-chat-promo-connected { padding: 0 8px; }
|
||||||
|
.lovart-chat-promo-surface { padding-bottom: 24px; border-radius: 24px 24px 0 0; background: #ebebeb; }
|
||||||
|
.lovart-chat-promo-row { display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 10px 0 16px; }
|
||||||
|
.lovart-chat-promo-message { display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1; padding: 0; border: 0; background: transparent; color: #202020; font-size: 14px; font-weight: 400; line-height: 20px; text-align: left; cursor: pointer; }
|
||||||
|
.lovart-chat-promo-message:disabled { cursor: default; opacity: 1; }
|
||||||
|
.lovart-chat-promo-message > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.lovart-chat-promo-badge { flex-shrink: 0; }
|
||||||
|
.lovart-chat-promo-close { display: flex; align-items: center; justify-content: center; flex-shrink: 0; width: 28px; height: 28px; border: 0; border-radius: 50%; background: transparent; color: #262626; cursor: pointer; }
|
||||||
|
.lovart-chat-promo-close:hover { background: rgb(0 0 0 / 5%); }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-promo-connected + .lovart-chat-composer { position: relative; z-index: 1; margin-top: -24px; background: transparent; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-composer > [data-canvas-chat-input-anchor][data-canvas-composer-mode="image"] { min-height: 184px; border-radius: 24px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-upload { margin: 8px 8px 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-tile { flex-direction: column; gap: 8px; width: 56px; height: 68px; border: 0; border-radius: 18px; background: #f5f5f5; color: #aaa; font-size: 12px; font-weight: 400; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-tile:hover { background: #ececec; color: #777; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-tile > svg { width: 14px; height: 14px; stroke-width: 1.5; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-text-region { padding: 12px 16px 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] [role="textbox"] { min-height: 40px; font-size: 14px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] [role="textbox"]:empty::before { color: #b0b0b0; }
|
||||||
|
.dark .lovart-chat-promo-surface { background: #27272a; }
|
||||||
|
.dark .lovart-chat-promo-message, .dark .lovart-chat-promo-close { color: #eee; }
|
||||||
|
.dark .lovart-chat-promo-close:hover { background: rgb(255 255 255 / 10%); }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-tile { background: #27272a; color: #a1a1aa; }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] .lovart-reference-tile:hover { background: #3f3f46; color: #eee; }
|
||||||
|
.dark .lovart-suggestion,
|
||||||
|
.dark .lovart-start-action { border-color: rgb(255 255 255 / 12%); background: #18181b; color: #eee; }
|
||||||
|
.dark .lovart-suggestion:hover,
|
||||||
|
.dark .lovart-start-action:hover { background: #27272a; border-color: rgb(255 255 255 / 22%); }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-header { border-color: rgb(255 255 255 / 10%); }
|
||||||
|
.dark [data-canvas-right-panel="true"] > .border-l { border-left-color: #27272a; }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] .lovart-chat-composer > [data-canvas-chat-input-anchor] { border-color: rgb(255 255 255 / 12%); }
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.lovart-home-surface main { padding-top: calc(72px + var(--home-banner-offset, 0px)); }
|
||||||
|
.lovart-hero { margin-top: 16px; }
|
||||||
|
.lovart-home-composer { border-radius: 20px; }
|
||||||
|
.lovart-suggestion { padding: 0 11px; font-size: 12px; }
|
||||||
|
.lovart-start-action { min-width: 160px; }
|
||||||
|
.lovart-chat-welcome h1 { font-size: 15px; }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.lovart-home-surface *, .lovart-canvas-surface * { scroll-behavior: auto !important; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.lovart-home-surface :is(button, input, textarea, select),
|
||||||
|
.lovart-canvas-surface :is(button, input, textarea, select) { font-family: inherit; }
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.lovart-canvas-surface[data-canvas-panel-open="true"] :is([data-canvas-topbar], [data-canvas-floating-toolbar], [data-canvas-compact-controls]) { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Reference icon sizing is independent of the application's root rem scale. */
|
||||||
|
.lovart-suggestion { gap: 8px; padding: 0 12px; }
|
||||||
|
.lovart-start-action { min-width: 172.71875px; gap: 8px; padding: 0 12px; }
|
||||||
|
.lovart-canvas-surface [data-canvas-floating-toolbar] button { min-width: 32px; height: 32px; border-radius: 8px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-mode-selector { width: 90px; height: 32px; padding: 0 8px; background: transparent; font-size: 14px; font-weight: 400; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-mode-selector > span { font-size: 13px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-mode-selector:hover,
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-image-params:hover,
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-model-selector:hover { background: rgb(0 0 0 / 4%); }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-image-params { width: 105.3828125px; min-width: 105.3828125px; height: 32px; padding: 0 4px 0 12px; background: transparent; font-size: 13px; gap: 4px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-model-selector { flex: 0 0 121px; width: 121px; height: 32px; padding: 0 4px 0 8px; gap: 0; border: 0; background: transparent; box-shadow: none; font-size: 13px; font-weight: 400; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-model-selector > [data-reference-icon]:first-child { margin-right: 8px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-model-selector > span:not([data-reference-icon]) { max-width: 65px; }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] :is(.lovart-model-selector, .lovart-image-params) { color: #eee; }
|
||||||
|
.dark .lovart-canvas-surface [data-lovart-chat="true"] :is(.lovart-model-selector, .lovart-image-params, .lovart-composer-mode-selector):hover { background: rgb(255 255 255 / 8%); }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-footer { padding: 0 8px 8px; gap: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-footer > div:first-child { flex: 0 0 90px; padding-right: 0; overflow: visible; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-footer > div:last-child { flex: 1 1 0; min-width: 0; gap: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-composer-mode="image"] .lovart-composer-send { min-width: 32px; width: auto; height: 32px; padding: 0 8px; gap: 2px; font-size: 13px; font-weight: 400; }
|
||||||
|
|
||||||
|
/* Adapt to the resizable chat panel, independently of the browser width. */
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] { container: canvas-composer / inline-size; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-composer-footer { gap: 4px; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-composer-footer > div:first-child { flex: 0 0 auto; overflow: visible; padding-right: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-composer-footer > div:last-child { flex: 0 1 auto; min-width: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-composer-mode-selector { width: auto; max-width: none; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-image-params { width: auto; min-width: 0; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-image-params-label { overflow: visible; text-overflow: clip; white-space: nowrap; }
|
||||||
|
.lovart-image-params-icon { display: none; }
|
||||||
|
@container canvas-composer (max-width: 480px) {
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-composer-mode-selector { width: 32px; min-width: 32px; padding: 0; }
|
||||||
|
.lovart-composer-mode-selector .lovart-composer-mode-label,
|
||||||
|
.lovart-composer-mode-selector [data-reference-icon="chevron-down"] { display: none; }
|
||||||
|
.lovart-composer-mode-selector > span > :first-child { margin-right: 0; }
|
||||||
|
}
|
||||||
|
@container canvas-composer (max-width: 360px) {
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-model-selector { flex: 0 0 32px; width: 32px; padding: 0; justify-content: center; }
|
||||||
|
.lovart-model-selector > span:not([data-reference-icon]),
|
||||||
|
.lovart-model-selector > [data-reference-icon="chevron-down"] { display: none; }
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] .lovart-model-selector > [data-reference-icon]:first-child { margin-right: 0; }
|
||||||
|
}
|
||||||
|
@container canvas-composer (max-width: 480px) {
|
||||||
|
.lovart-canvas-surface [data-lovart-chat="true"] [data-canvas-responsive-composer="true"] .lovart-image-params { width: 32px; min-width: 32px; padding: 0; justify-content: center; }
|
||||||
|
.lovart-image-params .lovart-image-params-icon { display: block; }
|
||||||
|
.lovart-image-params .lovart-image-params-label,
|
||||||
|
.lovart-image-params > [data-reference-icon="chevron-down"] { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The existing image toolbar is scaled to 80%; these dimensions render at
|
||||||
|
the reference's 44px bar, 32px buttons, and 20px icons. */
|
||||||
|
.lovart-image-action-bar {
|
||||||
|
height: 55px;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 0 7.5px;
|
||||||
|
border: 1.25px solid rgba(0, 0, 0, 0.07);
|
||||||
|
border-radius: 17.5px;
|
||||||
|
background: #fff !important;
|
||||||
|
color: #000;
|
||||||
|
box-shadow: 0 1.25px 2.5px rgba(0, 0, 0, 0.04);
|
||||||
|
backdrop-filter: none;
|
||||||
|
}
|
||||||
|
.lovart-image-action-bar::before { display: none; }
|
||||||
|
.lovart-image-action-bar > button {
|
||||||
|
width: 40px;
|
||||||
|
min-width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
margin: 0;
|
||||||
|
gap: 0;
|
||||||
|
padding: 0;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: transparent;
|
||||||
|
color: #000;
|
||||||
|
font-size: 0;
|
||||||
|
font-weight: 400;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
.lovart-image-action-bar > button:hover,
|
||||||
|
.lovart-image-action-bar > button[data-state="open"],
|
||||||
|
.lovart-image-action-bar > button[data-reference-active="true"] {
|
||||||
|
background: rgba(0, 0, 0, 0.04);
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
.lovart-image-action-bar > button:disabled {
|
||||||
|
background: transparent;
|
||||||
|
color: rgba(0, 0, 0, 0.3);
|
||||||
|
}
|
||||||
|
.lovart-image-action-bar > button > svg,
|
||||||
|
.lovart-image-action-bar > button > [data-reference-icon],
|
||||||
|
.lovart-image-action-bar > button > span[aria-hidden="true"],
|
||||||
|
.lovart-image-action-bar > button > img {
|
||||||
|
width: 25px;
|
||||||
|
height: 25px;
|
||||||
|
margin: 0;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.lovart-image-action-bar > button > img { filter: brightness(0); }
|
||||||
|
.lovart-image-action-bar > div.h-px,
|
||||||
|
.lovart-image-action-bar > div.w-px {
|
||||||
|
width: 1.25px;
|
||||||
|
height: 55px;
|
||||||
|
margin: 0 2.5px;
|
||||||
|
background: rgba(0, 0, 0, 0.07);
|
||||||
|
}
|
||||||
|
.lovart-image-action-menu [role="menuitem"] > svg,
|
||||||
|
.lovart-image-action-menu [role="menuitem"] > [data-reference-icon] {
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
}
|
||||||
|
.dark .lovart-image-action-bar {
|
||||||
|
border-color: rgba(255, 255, 255, 0.1);
|
||||||
|
background: #18191c !important;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.dark .lovart-image-action-bar > button { color: #fff; }
|
||||||
|
.dark .lovart-image-action-bar > button:hover,
|
||||||
|
.dark .lovart-image-action-bar > button[data-state="open"],
|
||||||
|
.dark .lovart-image-action-bar > button[data-reference-active="true"] {
|
||||||
|
background: rgba(255, 255, 255, 0.08);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.dark .lovart-image-action-bar > button:disabled { color: rgba(255, 255, 255, 0.3); }
|
||||||
|
.dark .lovart-image-action-bar > button > img { filter: brightness(0) invert(1); }
|
||||||
|
.dark .lovart-image-action-bar > div.w-px { background: rgba(255, 255, 255, 0.1); }
|
||||||
|
|
||||||
|
.lovart-image-action-bar[data-show-tool-names="true"] > button[data-tool-key] { width: auto; gap: 7.5px; padding: 0 12.5px; font-size: 16.25px; }
|
||||||
|
.lovart-image-tool-label { white-space: nowrap; }
|
||||||
|
.lovart-image-tool-tooltip { z-index: 10030; border: 0; border-radius: 6px; background: #1b1b1b; padding: 6px 9px; color: #fff; font-size: 13px; line-height: 18px; box-shadow: 0 4px 10px #00000012; --tw-ring-shadow: 0 0 transparent; }
|
||||||
|
.lovart-image-custom-more { min-width: 172px; padding: 6px 12px; border: 1px solid #e8e8e8; border-radius: 12px; background: #fff; }
|
||||||
|
.lovart-image-custom-more [role="menuitem"] { min-height: 32px; gap: 10px; padding: 4px 0; font-size: 14px; font-weight: 400; }
|
||||||
|
.lovart-image-custom-more .lovart-customize-entry { justify-content: center; gap: 5px; }
|
||||||
|
.lovart-toolbar-customizer-overlay { z-index: 10010; background: #0006; }
|
||||||
|
.lovart-toolbar-customizer { z-index: 10020; display: flex; flex-direction: column; width: min(720px, calc(100vw - 32px)); max-width: 720px; max-height: calc(100dvh - 48px); gap: 0; padding: 20px 24px 24px; border: 1px solid #e5e5e5; border-radius: 16px; background: #fff; color: #242424; box-shadow: 0 8px 24px #00000012; }
|
||||||
|
.lovart-customizer-header { display: flex; flex-shrink: 0; justify-content: space-between; align-items: flex-start; gap: 16px; }
|
||||||
|
.lovart-customizer-header h2 { margin: 0; font-size: 18px; line-height: 24px; font-weight: 600; }
|
||||||
|
.lovart-customizer-header p { margin-top: 2px; color: inherit; font-size: 14px; line-height: 22px; }
|
||||||
|
.lovart-customizer-header-actions { display: flex; gap: 4px; }
|
||||||
|
.lovart-customizer-header-actions button { display: flex; width: 28px; height: 28px; align-items: center; justify-content: center; border-radius: 7px; }
|
||||||
|
.lovart-customizer-header-actions button:last-child { background: #f1f1f1; }
|
||||||
|
.lovart-customizer-header-actions button:hover { background: #e9e9e9; }
|
||||||
|
.lovart-customizer-body { min-height: 0; overflow-y: auto; margin: 24px 0 20px; }
|
||||||
|
.lovart-customizer-preview { display: flex; height: 180px; align-items: center; overflow: hidden; padding: 16px; border-radius: 10px; background: #e5edef url("/icons/lovart/toolbar-preview.png") center / cover; }
|
||||||
|
.lovart-customizer-preview-bar { display: flex; align-items: center; flex: 1; min-width: 0; gap: 4px; padding: 5px 8px; border: 1px solid #e5e5e5; border-radius: 14px; background: #fff; overflow-x: auto; scrollbar-width: thin; }
|
||||||
|
.lovart-preview-fixed,.lovart-preview-chip { display: flex; align-items: center; flex-shrink: 0; height: 32px; gap: 8px; padding: 0 10px; font-size: 13px; white-space: nowrap; }
|
||||||
|
.lovart-preview-chip { position: relative; margin-top: 5px; margin-bottom: 5px; border-radius: 8px; background: #f4f4f4; cursor: grab; }
|
||||||
|
.lovart-preview-chip:active { cursor: grabbing; }
|
||||||
|
.lovart-preview-chip > button:last-child { position: absolute; top: -5px; right: -3px; display: flex; width: 16px; height: 16px; align-items: center; justify-content: center; border: 1px solid #e6e6e6; border-radius: 50%; background: #fff; color: #888; }
|
||||||
|
.lovart-customizer-tools { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 8px; margin-top: 24px; }
|
||||||
|
.lovart-customizer-tools > button { display: flex; align-items: center; gap: 10px; height: 36px; min-width: 0; padding: 0 12px; border: 1px solid #e2e2e2; border-radius: 8px; background: #fff; font-size: 14px; text-align: left; }
|
||||||
|
.lovart-customizer-tools > button > span:not([aria-hidden]) { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.lovart-customizer-tools > button > svg:last-child { flex-shrink: 0; }
|
||||||
|
.lovart-customizer-tools > button:hover { background: #f7f7f7; }
|
||||||
|
.lovart-customizer-footer { display: flex; flex-shrink: 0; align-items: center; justify-content: space-between; gap: 16px; }
|
||||||
|
.lovart-customizer-footer > label,.lovart-customizer-footer > div { display: flex; align-items: center; gap: 8px; font-size: 14px; }
|
||||||
|
.lovart-customizer-switch { width: 32px; height: 18px; padding: 2px; border-radius: 20px; background: #d5d5d5; }
|
||||||
|
.lovart-customizer-switch > span { display: block; width: 14px; height: 14px; border-radius: 50%; background: #fff; transition: transform .15s; }
|
||||||
|
.lovart-customizer-switch[aria-checked="true"] { background: #2c2c2c; }
|
||||||
|
.lovart-customizer-switch[aria-checked="true"] > span { transform: translateX(14px); }
|
||||||
|
.lovart-customizer-footer > div > button { width: 80px; height: 36px; border: 1px solid #e3e3e3; border-radius: 8px; font-size: 14px; }
|
||||||
|
.lovart-customizer-footer .lovart-customizer-save { border-color: #2c2c2c; background: #2c2c2c; color: #fff; }
|
||||||
|
.lovart-customizer-footer > div > button:hover { opacity: .8; }
|
||||||
|
.lovart-toolbar-customizer button:focus-visible,.lovart-preview-chip:focus-visible { outline: 2px solid #397dff; outline-offset: 2px; }
|
||||||
|
.dark .lovart-toolbar-customizer,.dark .lovart-image-custom-more { background: #202124; border-color: #3d3e40; color: #f5f5f5; }
|
||||||
|
.dark .lovart-customizer-preview-bar,.dark .lovart-customizer-tools > button { background: #26272a; border-color: #46474a; }
|
||||||
|
.dark .lovart-preview-chip,.dark .lovart-customizer-header-actions button:last-child { background: #35363a; }
|
||||||
|
.dark .lovart-preview-chip > button:last-child { background: #26272a; border-color: #46474a; color: #ccc; }
|
||||||
|
.dark .lovart-customizer-tools > button:hover { background: #35363a; }
|
||||||
|
@media(max-width:600px) { .lovart-toolbar-customizer { padding: 18px; } .lovart-customizer-tools { grid-template-columns: repeat(2,minmax(0,1fr)); } .lovart-customizer-preview { height: 140px; } }
|
||||||
|
|
||||||
|
.lovart-preview-handle { display: flex; align-items: center; gap: 8px; white-space: nowrap; cursor: grab; }
|
||||||
|
|
||||||
|
.lovart-image-tool-tooltip { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.lovart-image-tool-cost { margin-left: auto; padding: 0; background: transparent; color: #999; font-size: 12px; font-weight: 400; box-shadow: none; }
|
||||||
|
.lovart-image-tool-cost > svg { width: 12px; height: 12px; }
|
||||||
|
|
||||||
|
/* Preserve the canvas's own skills as the primary welcome content. */
|
||||||
|
.canvas-welcome-action {
|
||||||
|
display: inline-flex;
|
||||||
|
min-height: 36px;
|
||||||
|
min-width: 0;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid #e5e5e5;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: white;
|
||||||
|
color: #333;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 16px;
|
||||||
|
transition: background-color 150ms, border-color 150ms;
|
||||||
|
}
|
||||||
|
.canvas-welcome-action:hover { background: #f7f7f7; border-color: #d4d4d4; }
|
||||||
|
.canvas-welcome-action:focus-visible { outline: 2px solid #8c8c8c; outline-offset: 3px; }
|
||||||
|
.dark .canvas-welcome-action { border-color: rgb(255 255 255 / 12%); background: #18181b; color: #eee; }
|
||||||
|
.dark .canvas-welcome-action:hover { background: #27272a; border-color: rgb(255 255 255 / 22%); }
|
||||||
|
|||||||
@ -3,6 +3,9 @@ import { Toaster } from "sonner";
|
|||||||
import { ThemeProvider } from "@/components/theme-provider";
|
import { ThemeProvider } from "@/components/theme-provider";
|
||||||
import { FaviconUpdater } from "@/components/favicon-updater";
|
import { FaviconUpdater } from "@/components/favicon-updater";
|
||||||
import { ImageDeliveryOptimizer } from "@/components/image-delivery-optimizer";
|
import { ImageDeliveryOptimizer } from "@/components/image-delivery-optimizer";
|
||||||
|
import { PageFeedback } from "@/components/page-feedback";
|
||||||
|
import { AppUpdateNotice } from "@/components/app-update-notice";
|
||||||
|
import { PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE } from "@/lib/client/page-refresh";
|
||||||
import { getSiteSettings } from "@/lib/db/queries";
|
import { getSiteSettings } from "@/lib/db/queries";
|
||||||
|
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
@ -94,18 +97,33 @@ const CHUNK_ERROR_RECOVERY_SCRIPT = `\
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function safeRemoveSessionStorage(key) {
|
// Keep one attempt per route for the browser session. A cooldown alone can
|
||||||
try {
|
// turn a recurring editor exception into an endless reload cycle.
|
||||||
sessionStorage.removeItem(key);
|
var RECOVERY_KEY = 'chunk-reload-attempted-v3:' + window.location.pathname;
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var RECOVERY_KEY = 'chunk-reload-attempted-v2';
|
|
||||||
var lastReloadAt = Number(safeGetSessionStorage(RECOVERY_KEY) || '0') || 0;
|
var lastReloadAt = Number(safeGetSessionStorage(RECOVERY_KEY) || '0') || 0;
|
||||||
|
var recoveryNoticeShown = false;
|
||||||
|
|
||||||
|
function isFlowBoardEditing() {
|
||||||
|
var path = window.location.pathname;
|
||||||
|
return path === '/flow-board' || path.indexOf('/flow-board/') === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showManualRecoveryNotice() {
|
||||||
|
if (recoveryNoticeShown) return;
|
||||||
|
recoveryNoticeShown = true;
|
||||||
|
function show() {
|
||||||
|
if (!document.body || !isFlowBoardEditing()) return;
|
||||||
|
var notice = document.createElement('div');
|
||||||
|
notice.setAttribute('role', 'alert');
|
||||||
|
notice.setAttribute('data-runtime-recovery-notice', 'true');
|
||||||
|
notice.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);z-index:2147483647;max-width:calc(100vw - 32px);padding:12px 16px;border:1px solid var(--border,#e4e4e7);border-radius:12px;background:var(--background,#fff);color:var(--foreground,#27272a);box-shadow:0 4px 20px #0002;font:14px/1.5 system-ui;';
|
||||||
|
notice.textContent = '部分页面资源加载失败,请先保存白板后手动刷新页面。';
|
||||||
|
document.body.appendChild(notice);
|
||||||
|
}
|
||||||
|
if (document.body) show();
|
||||||
|
else window.addEventListener('DOMContentLoaded', show, { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
function shouldAutoRecover(message) {
|
function shouldAutoRecover(message) {
|
||||||
if (!message) return false;
|
if (!message) return false;
|
||||||
var normalized = String(message).toLowerCase();
|
var normalized = String(message).toLowerCase();
|
||||||
@ -117,28 +135,37 @@ const CHUNK_ERROR_RECOVERY_SCRIPT = `\
|
|||||||
normalized.indexOf('error loading dynamically imported module') !== -1 ||
|
normalized.indexOf('error loading dynamically imported module') !== -1 ||
|
||||||
normalized.indexOf('importing a module script failed') !== -1 ||
|
normalized.indexOf('importing a module script failed') !== -1 ||
|
||||||
normalized.indexOf('module script load failed') !== -1 ||
|
normalized.indexOf('module script load failed') !== -1 ||
|
||||||
normalized.indexOf('/_next/static/chunks/') !== -1 ||
|
normalized.indexOf('failed to find server action') !== -1
|
||||||
normalized.indexOf('failed to find server action') !== -1 ||
|
|
||||||
normalized.indexOf('server components render') !== -1 ||
|
|
||||||
normalized.indexOf('application error: a client-side exception') !== -1
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function triggerAutoRecover(reason) {
|
function triggerAutoRecover(reason) {
|
||||||
|
if (isFlowBoardEditing()) {
|
||||||
|
showManualRecoveryNotice();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (lastReloadAt || document.documentElement.hasAttribute('${PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE}')) return;
|
||||||
var now = Date.now();
|
var now = Date.now();
|
||||||
if (lastReloadAt && now - lastReloadAt < 30000) return;
|
// If storage is blocked, a reload cannot remember its attempt and must not run.
|
||||||
|
if (!safeSetSessionStorage(RECOVERY_KEY, String(now))) return;
|
||||||
lastReloadAt = now;
|
lastReloadAt = now;
|
||||||
console.warn('[RuntimeRecover] 检测到前端运行时异常,自动刷新页面...', reason || '');
|
console.warn('[RuntimeRecover] 检测到页面资源加载失败,尝试恢复一次...', reason || '');
|
||||||
safeSetSessionStorage(RECOVERY_KEY, String(now));
|
|
||||||
setTimeout(function() {
|
setTimeout(function() {
|
||||||
|
if (isFlowBoardEditing()) {
|
||||||
|
showManualRecoveryNotice();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (document.documentElement.hasAttribute('${PAGE_DOWNLOAD_ACTIVE_ATTRIBUTE}')) {
|
||||||
|
if (safeSetSessionStorage(RECOVERY_KEY, '0')) lastReloadAt = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
}, 800);
|
}, 800);
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('error', function(event) {
|
window.addEventListener('error', function(event) {
|
||||||
var message = '';
|
var message = '';
|
||||||
if (event && event.message) message += event.message;
|
if (event && event.message) message += event.message;
|
||||||
if (event && event.filename) message += ' ' + event.filename;
|
|
||||||
if (event && event.error && event.error.message) {
|
if (event && event.error && event.error.message) {
|
||||||
message += ' ' + event.error.message;
|
message += ' ' + event.error.message;
|
||||||
}
|
}
|
||||||
@ -157,12 +184,6 @@ const CHUNK_ERROR_RECOVERY_SCRIPT = `\
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 页面稳定一段时间后清除标记,避免旧资源异常无限刷新。
|
|
||||||
window.addEventListener('load', function() {
|
|
||||||
setTimeout(function() {
|
|
||||||
safeRemoveSessionStorage(RECOVERY_KEY);
|
|
||||||
}, 120000);
|
|
||||||
});
|
|
||||||
})();`;
|
})();`;
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
@ -201,7 +222,11 @@ export default function RootLayout({
|
|||||||
enableSystem
|
enableSystem
|
||||||
>
|
>
|
||||||
<Toaster position="top-center" />
|
<Toaster position="top-center" />
|
||||||
<SessionProvider>{children}</SessionProvider>
|
<AppUpdateNotice />
|
||||||
|
<SessionProvider>
|
||||||
|
{children}
|
||||||
|
<PageFeedback />
|
||||||
|
</SessionProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
83
app/tvstar/plugin/page.tsx
Normal file
83
app/tvstar/plugin/page.tsx
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
type KeyItem = { id: string; name: string; tokenPrefix: string; scopes: string[]; revokedAt: string | null; expiresAt: string | null };
|
||||||
|
|
||||||
|
export default function TVstarPluginPage() {
|
||||||
|
const [keys, setKeys] = useState<KeyItem[]>([]);
|
||||||
|
const [createdToken, setCreatedToken] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [origin, setOrigin] = useState("https://ai.yydd.ai");
|
||||||
|
useEffect(() => { setOrigin(window.location.origin); }, []);
|
||||||
|
const loadKeys = useCallback(async () => {
|
||||||
|
const response = await fetch("/api/user/access-keys", { cache: "no-store" });
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok || !data.success) throw new Error(data.error || "读取密钥失败");
|
||||||
|
setKeys(Array.isArray(data.data) ? data.data : []);
|
||||||
|
}, []);
|
||||||
|
useEffect(() => { void loadKeys().catch(error => toast.error(error.message)); }, [loadKeys]);
|
||||||
|
|
||||||
|
const createKey = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/user/access-keys", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: "TVstar MCP", scopes: ["canvas:read", "canvas:write"], expiresInDays: 90 }) });
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok || !data.success || !data.data?.token) throw new Error(data.error || "创建密钥失败");
|
||||||
|
setCreatedToken(data.data.token);
|
||||||
|
await loadKeys();
|
||||||
|
toast.success("密钥已创建;请立即复制,关闭后不会再次显示");
|
||||||
|
} catch (error) { toast.error(error instanceof Error ? error.message : "创建密钥失败"); }
|
||||||
|
finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
const revokeKey = async (id: string) => {
|
||||||
|
if (!window.confirm("撤销后使用此密钥的 Agent 将失去画布访问权限,确定继续吗?")) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/user/access-keys/${id}`, { method: "DELETE" });
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok || !data.success) throw new Error(data.error || "撤销失败");
|
||||||
|
setCreatedToken("");
|
||||||
|
await loadKeys();
|
||||||
|
toast.success("密钥已撤销");
|
||||||
|
} catch (error) { toast.error(error instanceof Error ? error.message : "撤销失败"); }
|
||||||
|
finally { setBusy(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const example = JSON.stringify({ mcpServers: { tvstar: { command: "node", args: ["/替换为解压目录/tvstar-mcp/mcp-server.mjs"],
|
||||||
|
env: { YEDIR_BASE_URL: origin, YEDIR_ACCESS_TOKEN: "粘贴新创建的 Access Key" } } } }, null, 2);
|
||||||
|
|
||||||
|
return <main className="min-h-screen bg-[#151515] px-4 py-10 text-white">
|
||||||
|
<div className="mx-auto max-w-4xl">
|
||||||
|
<p className="text-sm text-cyan-300">TVstar Plugin</p>
|
||||||
|
<h1 className="mt-2 text-3xl font-semibold">让 Agent 操作视频画布</h1>
|
||||||
|
<p className="mt-3 text-sm leading-7 text-white/60">当前插件提供画布列表、读取和有版本保护的节点操作。视频生成与合成仍由 TVstar 画布内的任务系统执行,MCP 暂未提供直接发起生成的工具。</p>
|
||||||
|
<div className="mt-8 grid gap-4 md:grid-cols-2">
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-[#222] p-5">
|
||||||
|
<h2 className="font-medium">1. 下载并安装</h2>
|
||||||
|
<p className="mt-2 text-sm text-white/50">需要 Node.js 20 或更新版本。解压后在 tvstar-mcp 目录运行:</p>
|
||||||
|
<a className="mt-4 inline-block rounded-lg bg-white px-4 py-2 text-sm font-medium text-black" href="/api/tvstar/plugin/download">下载 TVstar MCP 安装包</a>
|
||||||
|
<pre className="mt-4 overflow-x-auto rounded-lg bg-black/40 p-3 text-xs">cd tvstar-mcp{"\n"}npm ci</pre>
|
||||||
|
</section>
|
||||||
|
<section className="rounded-2xl border border-white/10 bg-[#222] p-5">
|
||||||
|
<h2 className="font-medium">2. 创建画布 Access Key</h2>
|
||||||
|
<p className="mt-2 text-sm text-white/50">读取和修改画布需要对应权限。密钥只在创建时显示一次。</p>
|
||||||
|
<button className="mt-4 rounded-lg bg-white px-4 py-2 text-sm font-medium text-black disabled:opacity-50" disabled={busy} onClick={() => void createKey()}>{busy ? "处理中…" : "创建 Access Key"}</button>
|
||||||
|
{createdToken ? <div className="mt-3 break-all rounded-lg border border-amber-300/30 bg-amber-300/5 p-3 text-xs text-amber-100"><p>{createdToken}</p><button className="mt-2 underline" onClick={() => void navigator.clipboard.writeText(createdToken).then(() => toast.success("已复制"))}>复制密钥</button></div> : null}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<section className="mt-4 rounded-2xl border border-white/10 bg-[#222] p-5">
|
||||||
|
<h2 className="font-medium">3. 配置支持 STDIO MCP 的 Agent</h2>
|
||||||
|
<p className="mt-2 text-sm text-white/50">将安装包的绝对路径和密钥填入客户端配置。不同 Agent 的配置文件位置和外层字段可能不同,请以所用客户端的说明为准。</p>
|
||||||
|
<pre className="mt-4 overflow-x-auto rounded-lg bg-black/40 p-4 text-xs leading-6 text-cyan-100">{example}</pre>
|
||||||
|
<button className="mt-3 text-sm text-cyan-300 underline" onClick={() => void navigator.clipboard.writeText(example).then(() => toast.success("配置示例已复制"))}>复制配置示例</button>
|
||||||
|
</section>
|
||||||
|
<section className="mt-4 rounded-2xl border border-white/10 bg-[#222] p-5">
|
||||||
|
<h2 className="font-medium">已创建的 Access Key</h2>
|
||||||
|
<div className="mt-3 space-y-2">{keys.length ? keys.map(key => <div className="flex items-center justify-between gap-4 rounded-lg bg-black/20 p-3 text-sm" key={key.id}><span className="min-w-0 truncate">{key.name} · {key.tokenPrefix} · {key.revokedAt ? "已撤销" : "有效"}</span>{!key.revokedAt ? <button className="shrink-0 text-rose-300 disabled:opacity-40" disabled={busy} onClick={() => void revokeKey(key.id)}>撤销</button> : null}</div>) : <p className="text-sm text-white/40">暂无密钥</p>}</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</main>;
|
||||||
|
}
|
||||||
41
app/tvstar/share/[token]/page.tsx
Normal file
41
app/tvstar/share/[token]/page.tsx
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { tvstarSession } from "@/lib/db/schema";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
type SharedSnapshot = {
|
||||||
|
title: string;
|
||||||
|
goal: string;
|
||||||
|
createdAt: number;
|
||||||
|
messages: { role: "user" | "assistant"; content: string; createdAt: number }[];
|
||||||
|
plan: { summary: string; deliverables: string[] } | null;
|
||||||
|
shots: { shot: string; duration: string; sceneDescription: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function TVstarSharedConversation({ params }: { params: Promise<{ token: string }> }) {
|
||||||
|
const { token } = await params;
|
||||||
|
if (!/^[A-Za-z0-9_-]{32}$/.test(token || "")) notFound();
|
||||||
|
const row = (await db.select({ snapshot: tvstarSession.sharedSnapshot }).from(tvstarSession)
|
||||||
|
.where(eq(tvstarSession.shareToken, token)).limit(1))[0];
|
||||||
|
if (!row?.snapshot) notFound();
|
||||||
|
const shared = row.snapshot as SharedSnapshot;
|
||||||
|
return <main className="min-h-screen bg-[#141414] px-4 py-12 text-white">
|
||||||
|
<article className="mx-auto max-w-2xl rounded-2xl border border-white/10 bg-[#1d1d1d] p-6 shadow-2xl">
|
||||||
|
<p className="text-xs tracking-widest text-cyan-300">TVstar · 只读分享</p>
|
||||||
|
<h1 className="mt-3 text-2xl font-semibold">{shared.title}</h1>
|
||||||
|
<p className="mt-2 text-sm text-white/50">{new Date(shared.createdAt).toLocaleString("zh-CN")}</p>
|
||||||
|
<p className="mt-6 whitespace-pre-wrap border-l-2 border-cyan-400 pl-4 text-sm text-white/70">{shared.goal}</p>
|
||||||
|
<section aria-label="分享的对话" className="mt-8 space-y-3">
|
||||||
|
{(shared.messages || []).map((message, index) => <div className={`rounded-xl p-4 text-sm leading-6 ${message.role === "user" ? "ml-8 bg-[#303846]" : "mr-8 bg-[#282828]"}`} key={`${message.createdAt}-${index}`}>
|
||||||
|
<p className="mb-1 text-xs text-white/40">{message.role === "user" ? "用户" : "TVstar"}</p>
|
||||||
|
<p className="whitespace-pre-wrap">{message.content}</p>
|
||||||
|
</div>)}
|
||||||
|
</section>
|
||||||
|
{shared.plan ? <section className="mt-8 border-t border-white/10 pt-5"><h2 className="text-lg">创作规划</h2><p className="mt-2 whitespace-pre-wrap text-sm text-white/70">{shared.plan.summary}</p></section> : null}
|
||||||
|
{shared.shots?.length ? <section className="mt-8 border-t border-white/10 pt-5"><h2 className="text-lg">分镜</h2><ol className="mt-3 space-y-3">{shared.shots.map((shot, index) => <li className="rounded-lg bg-white/5 p-3 text-sm" key={`${shot.shot}-${index}`}><strong>{shot.shot} · {shot.duration}</strong><p className="mt-1 whitespace-pre-wrap text-white/65">{shot.sceneDescription}</p></li>)}</ol></section> : null}
|
||||||
|
<p className="mt-8 border-t border-white/10 pt-5 text-xs text-white/40">此页面是分享时的对话快照,无法编辑画布;对话正文中的文字和链接会原样显示。</p>
|
||||||
|
</article>
|
||||||
|
</main>;
|
||||||
|
}
|
||||||
309
auto-deploy.sh
309
auto-deploy.sh
@ -1,303 +1,6 @@
|
|||||||
#!/bin/bash
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
# 自动部署脚本 - 包含密码
|
printf '%s\n' 'Legacy deployment entry point disabled: it targets an obsolete host/runtime.' >&2
|
||||||
# 使用方法: ./auto-deploy.sh
|
printf '%s\n' 'Use: python scripts/production48.py status' >&2
|
||||||
|
printf '%s\n' 'Then follow docs/production-48.md for build, stage, activate and rollback.' >&2
|
||||||
set -e
|
exit 2
|
||||||
|
|
||||||
# 服务器配置
|
|
||||||
SERVER="156.225.27.52"
|
|
||||||
PORT="5204"
|
|
||||||
USER="root"
|
|
||||||
PASSWORD="${DEPLOY_SSH_PASSWORD:?set DEPLOY_SSH_PASSWORD}"
|
|
||||||
REMOTE_DIR="/var/www/ai-chatbot"
|
|
||||||
|
|
||||||
# 颜色输出
|
|
||||||
RED='\033[0;31m'
|
|
||||||
GREEN='\033[0;32m'
|
|
||||||
YELLOW='\033[1;33m'
|
|
||||||
NC='\033[0m'
|
|
||||||
|
|
||||||
echo -e "${GREEN}开始自动部署到服务器...${NC}"
|
|
||||||
|
|
||||||
# 检查是否安装了 sshpass
|
|
||||||
if ! command -v sshpass &> /dev/null; then
|
|
||||||
echo -e "${YELLOW}安装 sshpass...${NC}"
|
|
||||||
if [[ "$OSTYPE" == "darwin"* ]]; then
|
|
||||||
# macOS
|
|
||||||
if ! command -v brew &> /dev/null; then
|
|
||||||
echo -e "${RED}请先安装 Homebrew: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"${NC}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
brew install hudochenkov/sshpass/sshpass
|
|
||||||
else
|
|
||||||
# Linux
|
|
||||||
sudo apt-get update && sudo apt-get install -y sshpass
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# SSH 连接函数
|
|
||||||
ssh_cmd() {
|
|
||||||
sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no -p $PORT $USER@$SERVER "$1"
|
|
||||||
}
|
|
||||||
|
|
||||||
scp_cmd() {
|
|
||||||
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no -P $PORT "$1" $USER@$SERVER:"$2"
|
|
||||||
}
|
|
||||||
|
|
||||||
scp_dir() {
|
|
||||||
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no -P $PORT -r "$1" $USER@$SERVER:"$2"
|
|
||||||
}
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 1: 检查服务器连接...${NC}"
|
|
||||||
ssh_cmd "echo '连接成功' && uname -a"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 2: 检查并安装必要软件...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
# 检查 Node.js
|
|
||||||
if ! command -v node &> /dev/null; then
|
|
||||||
echo '安装 Node.js...'
|
|
||||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
|
|
||||||
export NVM_DIR=\"\$HOME/.nvm\"
|
|
||||||
[ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"
|
|
||||||
nvm install 20
|
|
||||||
nvm use 20
|
|
||||||
nvm alias default 20
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 检查 pnpm
|
|
||||||
if ! command -v pnpm &> /dev/null; then
|
|
||||||
echo '安装 pnpm...'
|
|
||||||
npm install -g pnpm
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 检查 PM2
|
|
||||||
if ! command -v pm2 &> /dev/null; then
|
|
||||||
echo '安装 PM2...'
|
|
||||||
npm install -g pm2
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 检查 PostgreSQL
|
|
||||||
if ! command -v psql &> /dev/null; then
|
|
||||||
echo '安装 PostgreSQL...'
|
|
||||||
apt-get update -y
|
|
||||||
apt-get install -y postgresql postgresql-contrib
|
|
||||||
systemctl start postgresql
|
|
||||||
systemctl enable postgresql
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 检查 Nginx
|
|
||||||
if ! command -v nginx &> /dev/null; then
|
|
||||||
echo '安装 Nginx...'
|
|
||||||
apt-get install -y nginx
|
|
||||||
systemctl start nginx
|
|
||||||
systemctl enable nginx
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 创建项目目录
|
|
||||||
mkdir -p $REMOTE_DIR
|
|
||||||
mkdir -p /var/log/pm2
|
|
||||||
mkdir -p /root/backups/ai-chatbot
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 3: 配置数据库...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
# 检查并创建/更新数据库用户
|
|
||||||
echo '配置数据库用户...'
|
|
||||||
sudo -u postgres psql << 'PSQL'
|
|
||||||
-- 删除已存在的用户(如果存在)
|
|
||||||
DROP USER IF EXISTS chatbot_user;
|
|
||||||
|
|
||||||
-- 创建新用户
|
|
||||||
CREATE USER chatbot_user WITH PASSWORD 'ChatBot@2024!Secure';
|
|
||||||
|
|
||||||
-- 检查数据库是否存在
|
|
||||||
SELECT 1 FROM pg_database WHERE datname='ai_chatbot'\\gexec
|
|
||||||
|
|
||||||
-- 如果不存在则创建
|
|
||||||
DO \\$\\$
|
|
||||||
BEGIN
|
|
||||||
IF NOT EXISTS (SELECT FROM pg_database WHERE datname = 'ai_chatbot') THEN
|
|
||||||
CREATE DATABASE ai_chatbot;
|
|
||||||
END IF;
|
|
||||||
END
|
|
||||||
\\$\\$;
|
|
||||||
|
|
||||||
-- 授予权限
|
|
||||||
GRANT ALL PRIVILEGES ON DATABASE ai_chatbot TO chatbot_user;
|
|
||||||
|
|
||||||
-- 连接到数据库并授予schema权限
|
|
||||||
\\c ai_chatbot
|
|
||||||
GRANT ALL ON SCHEMA public TO chatbot_user;
|
|
||||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO chatbot_user;
|
|
||||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO chatbot_user;
|
|
||||||
|
|
||||||
\\q
|
|
||||||
PSQL
|
|
||||||
echo '数据库配置完成'
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 4: 上传项目文件...${NC}"
|
|
||||||
# 创建临时部署包
|
|
||||||
echo "准备部署文件..."
|
|
||||||
tar --exclude='node_modules' \
|
|
||||||
--exclude='.next' \
|
|
||||||
--exclude='.git' \
|
|
||||||
--exclude='.env.local' \
|
|
||||||
--exclude='*.log' \
|
|
||||||
--exclude='deploy.tar.gz' \
|
|
||||||
-czf /tmp/deploy.tar.gz .
|
|
||||||
|
|
||||||
# 上传部署包
|
|
||||||
scp_cmd "/tmp/deploy.tar.gz" "/tmp/"
|
|
||||||
|
|
||||||
# 在服务器上解压
|
|
||||||
ssh_cmd "
|
|
||||||
cd $REMOTE_DIR
|
|
||||||
tar -xzf /tmp/deploy.tar.gz
|
|
||||||
rm /tmp/deploy.tar.gz
|
|
||||||
|
|
||||||
if [ -f \"$REMOTE_DIR/scripts/security/install-security-stack.sh\" ]; then
|
|
||||||
echo '安装 security-stack...'
|
|
||||||
bash \"$REMOTE_DIR/scripts/security/install-security-stack.sh\" || echo 'security-stack 安装失败,继续部署'
|
|
||||||
elif [ -f \"$REMOTE_DIR/scripts/security/install-perf-guard.sh\" ]; then
|
|
||||||
echo '安装 perf-guard...'
|
|
||||||
bash \"$REMOTE_DIR/scripts/security/install-perf-guard.sh\" || echo 'perf-guard 安装失败,继续部署'
|
|
||||||
fi
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 5: 配置环境变量...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
cd $REMOTE_DIR
|
|
||||||
|
|
||||||
# 生成 AUTH_SECRET
|
|
||||||
AUTH_SECRET=\$(openssl rand -base64 32)
|
|
||||||
|
|
||||||
# 创建 .env.local 文件
|
|
||||||
cat > .env.local << EOF
|
|
||||||
POSTGRES_URL=postgresql://chatbot_user:ChatBot@2024!Secure@localhost:5432/ai_chatbot
|
|
||||||
AUTH_SECRET=\$AUTH_SECRET
|
|
||||||
AUTH_URL=http://$SERVER
|
|
||||||
NODE_ENV=production
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo '环境变量文件已创建'
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 6: 安装依赖和构建...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
cd $REMOTE_DIR
|
|
||||||
export NVM_DIR=\"\$HOME/.nvm\"
|
|
||||||
[ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"
|
|
||||||
|
|
||||||
echo '安装依赖...'
|
|
||||||
pnpm install --production=false
|
|
||||||
|
|
||||||
echo '运行数据库迁移...'
|
|
||||||
pnpm db:migrate || echo '迁移可能已存在,继续...'
|
|
||||||
|
|
||||||
echo '构建项目...'
|
|
||||||
pnpm build
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 7: 配置 PM2...${NC}"
|
|
||||||
# 上传 PM2 配置文件
|
|
||||||
scp_cmd "ecosystem.config.js" "$REMOTE_DIR/"
|
|
||||||
|
|
||||||
ssh_cmd "
|
|
||||||
cd $REMOTE_DIR
|
|
||||||
export NVM_DIR=\"\$HOME/.nvm\"
|
|
||||||
[ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"
|
|
||||||
|
|
||||||
# 停止旧进程(如果存在)
|
|
||||||
pm2 delete ai-chatbot 2>/dev/null || true
|
|
||||||
|
|
||||||
# 启动应用
|
|
||||||
pm2 start ecosystem.config.js
|
|
||||||
pm2 save
|
|
||||||
|
|
||||||
# 设置开机自启
|
|
||||||
pm2 startup systemd -u root --hp /root 2>/dev/null || echo 'PM2 startup 已配置'
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 8: 配置 Nginx...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
# 创建 Nginx 配置
|
|
||||||
cat > /etc/nginx/sites-available/ai-chatbot << 'NGINX'
|
|
||||||
server {
|
|
||||||
listen 80;
|
|
||||||
server_name $SERVER;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
proxy_pass http://localhost:3000;
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade \$http_upgrade;
|
|
||||||
proxy_set_header Connection 'upgrade';
|
|
||||||
proxy_set_header Host \$host;
|
|
||||||
proxy_set_header X-Real-IP \$remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
|
||||||
proxy_cache_bypass \$http_upgrade;
|
|
||||||
proxy_read_timeout 300s;
|
|
||||||
proxy_connect_timeout 75s;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NGINX
|
|
||||||
|
|
||||||
# 启用站点
|
|
||||||
ln -sf /etc/nginx/sites-available/ai-chatbot /etc/nginx/sites-enabled/
|
|
||||||
|
|
||||||
# 删除默认配置(如果存在)
|
|
||||||
rm -f /etc/nginx/sites-enabled/default
|
|
||||||
|
|
||||||
# 测试配置
|
|
||||||
nginx -t
|
|
||||||
|
|
||||||
# 重启 Nginx
|
|
||||||
systemctl restart nginx
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 9: 配置防火墙...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
ufw --force enable
|
|
||||||
ufw allow 80/tcp
|
|
||||||
ufw allow 443/tcp
|
|
||||||
ufw allow 5204/tcp
|
|
||||||
ufw allow 3000/tcp
|
|
||||||
"
|
|
||||||
|
|
||||||
echo -e "${GREEN}步骤 10: 检查部署状态...${NC}"
|
|
||||||
ssh_cmd "
|
|
||||||
echo '=== PM2 状态 ==='
|
|
||||||
pm2 status
|
|
||||||
|
|
||||||
echo ''
|
|
||||||
echo '=== 应用日志(最后20行)==='
|
|
||||||
pm2 logs ai-chatbot --lines 20 --nostream
|
|
||||||
|
|
||||||
echo ''
|
|
||||||
echo '=== Nginx 状态 ==='
|
|
||||||
systemctl status nginx --no-pager -l
|
|
||||||
|
|
||||||
echo ''
|
|
||||||
echo '=== 端口监听 ==='
|
|
||||||
netstat -tulpn | grep -E ':(80|3000|5432)' || ss -tulpn | grep -E ':(80|3000|5432)'
|
|
||||||
"
|
|
||||||
|
|
||||||
# 清理本地临时文件
|
|
||||||
rm -f /tmp/deploy.tar.gz
|
|
||||||
|
|
||||||
echo -e "${GREEN}========================================${NC}"
|
|
||||||
echo -e "${GREEN}部署完成!${NC}"
|
|
||||||
echo -e "${GREEN}========================================${NC}"
|
|
||||||
echo -e "${YELLOW}访问地址: http://$SERVER${NC}"
|
|
||||||
echo -e "${YELLOW}管理员设置: http://$SERVER/admin/settings${NC}"
|
|
||||||
echo -e "${YELLOW}查看日志: ssh -p $PORT $USER@$SERVER 'pm2 logs ai-chatbot'${NC}"
|
|
||||||
echo -e "${YELLOW}查看状态: ssh -p $PORT $USER@$SERVER 'pm2 status'${NC}"
|
|
||||||
echo ""
|
|
||||||
echo -e "${YELLOW}数据库信息:${NC}"
|
|
||||||
echo -e " 数据库名: ai_chatbot"
|
|
||||||
echo -e " 用户名: chatbot_user"
|
|
||||||
echo -e " 密码: ChatBot@2024!Secure"
|
|
||||||
echo ""
|
|
||||||
echo -e "${YELLOW}注意: 请尽快修改数据库密码和服务器密码!${NC}"
|
|
||||||
|
|||||||
30
components/admin/admin-surface.tsx
Normal file
30
components/admin/admin-surface.tsx
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
603
components/admin/media-records-panel.tsx
Normal file
603
components/admin/media-records-panel.tsx
Normal file
@ -0,0 +1,603 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
150
components/admin/media-thumbnail.tsx
Normal file
150
components/admin/media-thumbnail.tsx
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
191
components/admin/model-health-panel.tsx
Normal file
191
components/admin/model-health-panel.tsx
Normal file
@ -0,0 +1,191 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
326
components/admin/model-management-list.tsx
Normal file
326
components/admin/model-management-list.tsx
Normal file
@ -0,0 +1,326 @@
|
|||||||
|
"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,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||||
|
|
||||||
import { useChat } from "@ai-sdk/react";
|
import { useChat } from "@ai-sdk/react";
|
||||||
import { DefaultChatTransport } from "ai";
|
import { DefaultChatTransport } from "ai";
|
||||||
@ -575,31 +576,11 @@ export function AgentGenerationWorkspace({
|
|||||||
toast.error("图片地址无效");
|
toast.error("图片地址无效");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filename = buildDownloadFilename(raw);
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(raw);
|
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||||
if (!response.ok) {
|
toast.success("原图已开始下载");
|
||||||
throw new Error(`download failed: ${response.status}`);
|
} catch (error) {
|
||||||
}
|
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||||
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,7 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||||
|
|
||||||
import { useChat } from "@ai-sdk/react";
|
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 { 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 type { DetailReplacementBatchCard } from "@/lib/agents/detail-replacement-batch";
|
||||||
import { DefaultChatTransport } from "ai";
|
import { DefaultChatTransport } from "ai";
|
||||||
import {
|
import {
|
||||||
@ -156,6 +159,7 @@ import type {
|
|||||||
} from "@/types/agent";
|
} from "@/types/agent";
|
||||||
import {
|
import {
|
||||||
createEmptyAgentModeWorkspaceState,
|
createEmptyAgentModeWorkspaceState,
|
||||||
|
MAX_DETAIL_REPLACEMENT_REFERENCES,
|
||||||
} from "@/lib/agents/mode-workspace-state";
|
} from "@/lib/agents/mode-workspace-state";
|
||||||
import {
|
import {
|
||||||
createEmptyAgentGenerationProjectWorkspaceState,
|
createEmptyAgentGenerationProjectWorkspaceState,
|
||||||
@ -173,6 +177,7 @@ export interface AgentGenerationWorkspaceDarkV2Props {
|
|||||||
workflowFeatureSettings?: AgentWorkflowPageFeatureSettings | null;
|
workflowFeatureSettings?: AgentWorkflowPageFeatureSettings | null;
|
||||||
workflowPromptOptimizationEnabled?: boolean;
|
workflowPromptOptimizationEnabled?: boolean;
|
||||||
getLatestWorkflowContext?: () => AgentWorkflowComposerContext | null;
|
getLatestWorkflowContext?: () => AgentWorkflowComposerContext | null;
|
||||||
|
getWorkflowPromptStatus?: () => "ready" | "loading" | "error";
|
||||||
onBack?: () => void;
|
onBack?: () => void;
|
||||||
brandStorePanel?: ReactNode;
|
brandStorePanel?: ReactNode;
|
||||||
materialSelectionPanel?: ReactNode;
|
materialSelectionPanel?: ReactNode;
|
||||||
@ -209,6 +214,7 @@ export interface AgentGenerationWorkspaceDarkV2Props {
|
|||||||
interface AgentWorkflowModelOption {
|
interface AgentWorkflowModelOption {
|
||||||
id: string;
|
id: string;
|
||||||
displayName: string;
|
displayName: string;
|
||||||
|
providerName?: string;
|
||||||
providerType: string;
|
providerType: string;
|
||||||
supportsImageGen?: boolean;
|
supportsImageGen?: boolean;
|
||||||
isMultimodal?: boolean;
|
isMultimodal?: boolean;
|
||||||
@ -2639,7 +2645,9 @@ function getStoredAgentPendingGenerations(): LocalGenerationPendingState[] {
|
|||||||
? record.requestedCardIds
|
? record.requestedCardIds
|
||||||
.map((entry) => String(entry || "").trim())
|
.map((entry) => String(entry || "").trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.slice(0, MAX_AGENT_MODE_REFERENCE_COUNT)
|
.slice(0, record.modeType === "detail_replacement"
|
||||||
|
? MAX_DETAIL_REPLACEMENT_REFERENCES
|
||||||
|
: MAX_AGENT_MODE_REFERENCE_COUNT)
|
||||||
: null,
|
: null,
|
||||||
} satisfies LocalGenerationPendingState;
|
} satisfies LocalGenerationPendingState;
|
||||||
});
|
});
|
||||||
@ -3082,6 +3090,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
workflowFeatureSettings = null,
|
workflowFeatureSettings = null,
|
||||||
workflowPromptOptimizationEnabled = true,
|
workflowPromptOptimizationEnabled = true,
|
||||||
getLatestWorkflowContext,
|
getLatestWorkflowContext,
|
||||||
|
getWorkflowPromptStatus,
|
||||||
onBack,
|
onBack,
|
||||||
brandStorePanel,
|
brandStorePanel,
|
||||||
materialSelectionPanel,
|
materialSelectionPanel,
|
||||||
@ -3379,12 +3388,13 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const { data: modelsData } = useSWR<{
|
const { data: modelsData, error: modelsError, mutate: refreshModels } = useSWR<{
|
||||||
models: AgentWorkflowModelOption[];
|
models: AgentWorkflowModelOption[];
|
||||||
defaultModelId?: string | null;
|
defaultModelId?: string | null;
|
||||||
agentWorkflowConfiguredDefaultModelId?: string | null;
|
agentWorkflowConfiguredDefaultModelId?: string | null;
|
||||||
agentWorkflowDefaultModelId?: string | null;
|
agentWorkflowDefaultModelId?: string | null;
|
||||||
agentWorkflowConfiguredModels?: AgentWorkflowModelOption[];
|
agentWorkflowConfiguredModels?: AgentWorkflowModelOption[];
|
||||||
|
detailReplacementModel?: AgentWorkflowModelOption | null;
|
||||||
agentModel?: any;
|
agentModel?: any;
|
||||||
}>("/api/models", fetcher);
|
}>("/api/models", fetcher);
|
||||||
|
|
||||||
@ -3430,17 +3440,6 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
const activeBusinessModeDefaultModelId = !requiresPresetSelection
|
const activeBusinessModeDefaultModelId = !requiresPresetSelection
|
||||||
? String(activeBusinessMode?.defaultModelId || "").trim() || null
|
? String(activeBusinessMode?.defaultModelId || "").trim() || null
|
||||||
: 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 =
|
const presetDrivenResultModeType: AgentGenerationResultModeType =
|
||||||
selectedAgentPreset?.type === "image" && presetModeConfig.modeType === "detail_replacement"
|
selectedAgentPreset?.type === "image" && presetModeConfig.modeType === "detail_replacement"
|
||||||
? detailReplacementMethod === "ai_detail_generate"
|
? detailReplacementMethod === "ai_detail_generate"
|
||||||
@ -3456,6 +3455,19 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
const currentResultModeType: AgentGenerationResultModeType = requiresPresetSelection
|
const currentResultModeType: AgentGenerationResultModeType = requiresPresetSelection
|
||||||
? presetDrivenResultModeType
|
? presetDrivenResultModeType
|
||||||
: businessModeResultModeType;
|
: 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 isSceneGenerationPreset = currentResultModeType === "scene_generation";
|
||||||
const isDetailReplacementPreset =
|
const isDetailReplacementPreset =
|
||||||
currentResultModeType === "detail_replacement" ||
|
currentResultModeType === "detail_replacement" ||
|
||||||
@ -4107,12 +4119,15 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
);
|
);
|
||||||
const executableModelOptions = useMemo(() => {
|
const executableModelOptions = useMemo(() => {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
return [...selectableModels, ...configuredWorkflowModels].filter((model) => {
|
const workflowModels = detailReplacementModel
|
||||||
|
? [detailReplacementModel, ...configuredWorkflowModels]
|
||||||
|
: configuredWorkflowModels;
|
||||||
|
return [...selectableModels, ...workflowModels].filter((model) => {
|
||||||
if (seen.has(model.id)) return false;
|
if (seen.has(model.id)) return false;
|
||||||
seen.add(model.id);
|
seen.add(model.id);
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
}, [configuredWorkflowModels, selectableModels]);
|
}, [configuredWorkflowModels, detailReplacementModel, selectableModels]);
|
||||||
const executableModelIdSet = useMemo(
|
const executableModelIdSet = useMemo(
|
||||||
() => new Set(executableModelOptions.map((model) => model.id)),
|
() => new Set(executableModelOptions.map((model) => model.id)),
|
||||||
[executableModelOptions]
|
[executableModelOptions]
|
||||||
@ -4131,8 +4146,9 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
selectableModels[0],
|
selectableModels[0],
|
||||||
[executableModelOptions, lockedWorkflowModel, selectableModels, selectedModelId]
|
[executableModelOptions, lockedWorkflowModel, selectableModels, selectedModelId]
|
||||||
);
|
);
|
||||||
const lockedWorkflowModelLabel =
|
const lockedWorkflowModelLabel = detailReplacementModel?.providerName
|
||||||
lockedWorkflowModel?.displayName ||
|
? `${detailReplacementModel.displayName} 「${detailReplacementModel.providerName}」`
|
||||||
|
: lockedWorkflowModel?.displayName ||
|
||||||
selectedAgentPreset?.defaultModel?.displayName ||
|
selectedAgentPreset?.defaultModel?.displayName ||
|
||||||
(lockedWorkflowModelId ? `配置模型不可用(${lockedWorkflowModelId})` : "未配置");
|
(lockedWorkflowModelId ? `配置模型不可用(${lockedWorkflowModelId})` : "未配置");
|
||||||
const [activeToolStep, setActiveToolStep] = useState<ToolStepKey>("settings");
|
const [activeToolStep, setActiveToolStep] = useState<ToolStepKey>("settings");
|
||||||
@ -4169,6 +4185,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
? "agent-anchor-materials"
|
? "agent-anchor-materials"
|
||||||
: "agent-anchor-generate";
|
: "agent-anchor-generate";
|
||||||
|
|
||||||
|
const [finishedSceneRequestId, setFinishedSceneRequestId] = useState<string | null>(null);
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
setMessages,
|
setMessages,
|
||||||
@ -4181,6 +4198,12 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
id: chatId,
|
id: chatId,
|
||||||
messages: historyMessages,
|
messages: historyMessages,
|
||||||
onData(part) {
|
onData(part) {
|
||||||
|
if (part.type === "data-imageGenerationNotice") {
|
||||||
|
if (typeof part.data === "string") {
|
||||||
|
toast.warning(part.data, { id: "image-generation-spec-notice" });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (part.type !== "data-appendMessage") return;
|
if (part.type !== "data-appendMessage") return;
|
||||||
try {
|
try {
|
||||||
const appended = parseAppendedGenerationMessage(part.data);
|
const appended = parseAppendedGenerationMessage(part.data);
|
||||||
@ -4189,7 +4212,11 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
void refreshHistory();
|
void refreshHistory();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onFinish() { void refreshHistory(); },
|
onFinish({ messages: finishedMessages }) {
|
||||||
|
const lastUser = finishedMessages.filter((message) => message.role === "user").at(-1);
|
||||||
|
setFinishedSceneRequestId(lastUser?.id || null);
|
||||||
|
void refreshHistory();
|
||||||
|
},
|
||||||
experimental_throttle: 100,
|
experimental_throttle: 100,
|
||||||
generateId: generateUUID,
|
generateId: generateUUID,
|
||||||
transport: new DefaultChatTransport({
|
transport: new DefaultChatTransport({
|
||||||
@ -4872,6 +4899,14 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
return recoverReplacementRun({ messages, ...pendingGeneration });
|
return recoverReplacementRun({ messages, ...pendingGeneration });
|
||||||
}, [messages, pendingGeneration]);
|
}, [messages, pendingGeneration]);
|
||||||
const transportIsGenerating = status === "streaming" || status === "submitted";
|
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(() => {
|
const pendingGenerationProgressCount = useMemo(() => {
|
||||||
if (!pendingGeneration) {
|
if (!pendingGeneration) {
|
||||||
return 0;
|
return 0;
|
||||||
@ -5482,6 +5517,17 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
setActiveResultModeType(currentResultModeType);
|
setActiveResultModeType(currentResultModeType);
|
||||||
}, [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(() => {
|
useEffect(() => {
|
||||||
if (!pendingGeneration || pendingGeneration.backendTaskId || !replacementRunRecovery.done) return;
|
if (!pendingGeneration || pendingGeneration.backendTaskId || !replacementRunRecovery.done) return;
|
||||||
// The backend has settled every requested card; an open SSE connection is no longer work.
|
// The backend has settled every requested card; an open SSE connection is no longer work.
|
||||||
@ -5852,6 +5898,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
|
scope: params.scope === "detail" ? "style-detail" : undefined,
|
||||||
folderName: params.zipName,
|
folderName: params.zipName,
|
||||||
files: normalizedUrls.map((imageUrl) => ({
|
files: normalizedUrls.map((imageUrl) => ({
|
||||||
url: imageUrl,
|
url: imageUrl,
|
||||||
@ -6287,10 +6334,24 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
toast.error(`请先查询并选择${detailReferenceSourceLabel}参考图`);
|
toast.error(`请先查询并选择${detailReferenceSourceLabel}参考图`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isDetailReplacementModelLoading) {
|
||||||
|
if (modelsError) {
|
||||||
|
toast.error("详情替换模型加载失败,正在重新读取");
|
||||||
|
void refreshModels().catch(() => {});
|
||||||
|
} else {
|
||||||
|
toast.info("正在读取详情替换模型,请稍候");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (isSkuReplacementPreset && skuReplacementReferenceCards.length === 0) {
|
if (isSkuReplacementPreset && skuReplacementReferenceCards.length === 0) {
|
||||||
toast.error(`请先查询并选择${skuReferenceSourceLabel}参考图`);
|
toast.error(`请先查询并选择${skuReferenceSourceLabel}参考图`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const promptStatus = getWorkflowPromptStatus?.();
|
||||||
|
if (promptStatus === "loading" || promptStatus === "error") {
|
||||||
|
toast.error(promptStatus === "error" ? "请先在风格模板区重试加载提示词" : "正在加载所选模板的提示词,请稍候");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const resolvedWorkflowContext = getLatestWorkflowContext?.() ?? workflowContext;
|
const resolvedWorkflowContext = getLatestWorkflowContext?.() ?? workflowContext;
|
||||||
if (
|
if (
|
||||||
isDetailReplacementPreset &&
|
isDetailReplacementPreset &&
|
||||||
@ -6349,6 +6410,10 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
}
|
}
|
||||||
if (replacementModeType === "detail_replacement") {
|
if (replacementModeType === "detail_replacement") {
|
||||||
if (detailBatchSubmittingRef.current) return;
|
if (detailBatchSubmittingRef.current) return;
|
||||||
|
if (replacementExecutionCards.length > MAX_DETAIL_REPLACEMENT_REFERENCES) {
|
||||||
|
toast.error(`本次选中了 ${replacementExecutionCards.length} 张详情参考图,一次最多替换 ${MAX_DETAIL_REPLACEMENT_REFERENCES} 张,请减少本次选择后重试`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!isValidChatUuid(projectId)) {
|
if (!isValidChatUuid(projectId)) {
|
||||||
toast.error("当前风格化项目尚未保存,请先保存项目后再执行详情替换");
|
toast.error("当前风格化项目尚未保存,请先保存项目后再执行详情替换");
|
||||||
return;
|
return;
|
||||||
@ -6369,13 +6434,14 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
const saved = await onPersistProject?.();
|
const saved = await onPersistProject?.();
|
||||||
if (saved === false) throw new Error("项目尚未保存,请重试");
|
if (saved === false) throw new Error("项目尚未保存,请重试");
|
||||||
const requestId = generateUUID();
|
const requestId = generateUUID();
|
||||||
const response = await fetchWithErrorHandlers("/api/agents/detail-replacement/batches", {
|
const response = await fetch("/api/agents/detail-replacement/batches", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
projectId,
|
projectId,
|
||||||
requestId,
|
requestId,
|
||||||
model: resolvedModelId,
|
model: resolvedModelId,
|
||||||
|
expectedModelId: resolvedModelId === "auto" ? undefined : resolvedModelId,
|
||||||
imageSize: imageParams.imageSize,
|
imageSize: imageParams.imageSize,
|
||||||
replacementStrategy: detailReplacementStrategy,
|
replacementStrategy: detailReplacementStrategy,
|
||||||
prompt: detailReplacementStrategy === "product_only"
|
prompt: detailReplacementStrategy === "product_only"
|
||||||
@ -6399,6 +6465,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
});
|
});
|
||||||
const payload = await response.json().catch(() => ({}));
|
const payload = await response.json().catch(() => ({}));
|
||||||
if (!response.ok || !payload?.task?.id) {
|
if (!response.ok || !payload?.task?.id) {
|
||||||
|
if (payload?.code === "DETAIL_REPLACEMENT_MODEL_CHANGED") void refreshModels().catch(() => {});
|
||||||
throw new Error(payload?.error || "详情替换任务提交失败");
|
throw new Error(payload?.error || "详情替换任务提交失败");
|
||||||
}
|
}
|
||||||
setPendingGeneration({
|
setPendingGeneration({
|
||||||
@ -6586,6 +6653,8 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
input,
|
input,
|
||||||
isDetailAiGenerationMethod,
|
isDetailAiGenerationMethod,
|
||||||
isDetailReplacementPreset,
|
isDetailReplacementPreset,
|
||||||
|
isDetailReplacementModelLoading,
|
||||||
|
modelsError,
|
||||||
isSelectedBusinessModeUnavailable,
|
isSelectedBusinessModeUnavailable,
|
||||||
isSkuReplacementPreset,
|
isSkuReplacementPreset,
|
||||||
effectiveDefaultModelId,
|
effectiveDefaultModelId,
|
||||||
@ -6602,6 +6671,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
skuResultCards,
|
skuResultCards,
|
||||||
userMessageCount,
|
userMessageCount,
|
||||||
getLatestWorkflowContext,
|
getLatestWorkflowContext,
|
||||||
|
getWorkflowPromptStatus,
|
||||||
isSceneGenerationPreset,
|
isSceneGenerationPreset,
|
||||||
workflowContext,
|
workflowContext,
|
||||||
sceneMessageAttachments,
|
sceneMessageAttachments,
|
||||||
@ -6612,6 +6682,7 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
onPersistProject,
|
onPersistProject,
|
||||||
projectId,
|
projectId,
|
||||||
refreshDetailBatch,
|
refreshDetailBatch,
|
||||||
|
refreshModels,
|
||||||
]);
|
]);
|
||||||
const handleStopGeneration = useCallback(() => {
|
const handleStopGeneration = useCallback(() => {
|
||||||
detailGenerationCancelRef.current = true;
|
detailGenerationCancelRef.current = true;
|
||||||
@ -6776,31 +6847,11 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
toast.error("图片地址无效");
|
toast.error("图片地址无效");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filename = buildDownloadFilename(raw);
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(raw);
|
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||||
if (!response.ok) {
|
toast.success("原图已开始下载");
|
||||||
throw new Error(`download failed: ${response.status}`);
|
} catch (error) {
|
||||||
}
|
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||||
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) => {
|
const uploadBase64ResultToStorage = useCallback(async (base64Url: string) => {
|
||||||
@ -7795,6 +7846,11 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
toast.error(detailGenerationValidationIssues[0] || "请先补齐 AI详情生成参数");
|
toast.error(detailGenerationValidationIssues[0] || "请先补齐 AI详情生成参数");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const promptStatus = getWorkflowPromptStatus?.();
|
||||||
|
if (promptStatus === "loading" || promptStatus === "error") {
|
||||||
|
toast.error(promptStatus === "error" ? "请先在风格模板区重试加载提示词" : "正在加载所选模板的提示词,请稍候");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const productAttachments = detailGenerationProductSlotIndexes.map((index) =>
|
const productAttachments = detailGenerationProductSlotIndexes.map((index) =>
|
||||||
detailGenerationSlots[index]
|
detailGenerationSlots[index]
|
||||||
@ -9399,9 +9455,11 @@ export function AgentGenerationWorkspaceDarkV2({
|
|||||||
</Select>
|
</Select>
|
||||||
) : (
|
) : (
|
||||||
<div className="rounded-[24px] border border-white/10 bg-black/30 px-4 py-3 text-sm text-white/70">
|
<div className="rounded-[24px] border border-white/10 bg-black/30 px-4 py-3 text-sm text-white/70">
|
||||||
{isWorkflowModelLocked ? "后台已锁定生图模型:" : "当前生图模式使用默认模型:"}
|
{isDetailReplacementModelLoading
|
||||||
|
? modelsError ? "详情替换模型加载失败,点击批量替换可重试" : "正在读取详情替换模型"
|
||||||
|
: isWorkflowModelLocked ? "后台已锁定生图模型:" : "当前生图模式使用默认模型:"}
|
||||||
<span className="ml-2 font-medium text-white">
|
<span className="ml-2 font-medium text-white">
|
||||||
{isWorkflowModelLocked
|
{isDetailReplacementModelLoading ? null : isWorkflowModelLocked
|
||||||
? lockedWorkflowModelLabel
|
? lockedWorkflowModelLabel
|
||||||
: currentModel?.displayName || "自动选择"}
|
: currentModel?.displayName || "自动选择"}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { downloadOriginalImage, getCanvasImageDownloadErrorMessage } from "@/lib/client/canvas-image-download";
|
||||||
|
|
||||||
import { useChat } from "@ai-sdk/react";
|
import { useChat } from "@ai-sdk/react";
|
||||||
import { DefaultChatTransport } from "ai";
|
import { DefaultChatTransport } from "ai";
|
||||||
@ -725,30 +726,11 @@ export function AgentGenerationWorkspaceNew({
|
|||||||
toast.error("图片地址无效");
|
toast.error("图片地址无效");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const filename = buildDownloadFilename(raw);
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(raw);
|
await downloadOriginalImage({ url: raw, name: buildDownloadFilename(raw) });
|
||||||
if (!response.ok) {
|
toast.success("原图已开始下载");
|
||||||
throw new Error(`download failed: ${response.status}`);
|
} catch (error) {
|
||||||
}
|
toast.error(getCanvasImageDownloadErrorMessage(error));
|
||||||
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,6 +3,7 @@
|
|||||||
import { useMemo } from "react";
|
import { useMemo } from "react";
|
||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
import { Check, ImageIcon, Loader2, UserRound } from "lucide-react";
|
import { Check, ImageIcon, Loader2, UserRound } from "lucide-react";
|
||||||
|
import { AgentPreviewImage } from "@/components/agents/AgentPreviewImage";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { cn, fetcher } from "@/lib/utils";
|
import { cn, fetcher } from "@/lib/utils";
|
||||||
import { normalizeAgentWorkflowBrandModelConfig } from "@/lib/agents/workflow-brand-model-config";
|
import { normalizeAgentWorkflowBrandModelConfig } from "@/lib/agents/workflow-brand-model-config";
|
||||||
@ -229,12 +230,11 @@ export function AgentWorkflowBrandModelPicker({
|
|||||||
isDark ? "bg-white/[0.04]" : "bg-muted/40"
|
isDark ? "bg-white/[0.04]" : "bg-muted/40"
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<img
|
<AgentPreviewImage
|
||||||
src={image.imageUrl}
|
src={image.imageUrl}
|
||||||
alt={image.displayName || `${normalizedBrand} 模特图`}
|
alt={image.displayName || `${normalizedBrand} 模特图`}
|
||||||
className="h-full w-full object-cover"
|
className="h-full w-full object-cover"
|
||||||
loading="lazy"
|
previewWidth={360}
|
||||||
decoding="async"
|
|
||||||
/>
|
/>
|
||||||
<div className="absolute inset-x-0 top-0 flex items-center justify-between px-2 py-2">
|
<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">
|
<span className="rounded-full bg-black/60 px-2 py-1 text-[11px] text-white">
|
||||||
|
|||||||
@ -112,6 +112,8 @@ const PREVIEW_DIMENSION_HANDLE_RADIUS = 3.2;
|
|||||||
const PREVIEW_DIMENSION_HANDLE_STROKE_WIDTH = 1.2;
|
const PREVIEW_DIMENSION_HANDLE_STROKE_WIDTH = 1.2;
|
||||||
const PREVIEW_DIMENSION_TEXT_HALO_WIDTH = 2.2;
|
const PREVIEW_DIMENSION_TEXT_HALO_WIDTH = 2.2;
|
||||||
const PREVIEW_DIMENSION_TEXT_OUTLINE_WIDTH = 0.85;
|
const PREVIEW_DIMENSION_TEXT_OUTLINE_WIDTH = 0.85;
|
||||||
|
const DIMENSION_FONT_FAMILY =
|
||||||
|
'"PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif';
|
||||||
const SIZE_INFO_LINE_REGEX = /尺寸信息[::]\s*([^\n]+)/i;
|
const SIZE_INFO_LINE_REGEX = /尺寸信息[::]\s*([^\n]+)/i;
|
||||||
const NUMBER_REGEX = /\d+(?:\.\d+)?/g;
|
const NUMBER_REGEX = /\d+(?:\.\d+)?/g;
|
||||||
const HEX_COLOR_REGEX = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
|
const HEX_COLOR_REGEX = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
|
||||||
@ -568,87 +570,54 @@ function drawAnnotationToCanvas(params: {
|
|||||||
context: CanvasRenderingContext2D;
|
context: CanvasRenderingContext2D;
|
||||||
annotation: DimensionAnnotation;
|
annotation: DimensionAnnotation;
|
||||||
imageSize: ImageSize;
|
imageSize: ImageSize;
|
||||||
|
previewRect: PreviewRect;
|
||||||
annotations: DimensionAnnotation[];
|
annotations: DimensionAnnotation[];
|
||||||
autoDimensionValues?: AutoDimensionValues | null;
|
autoDimensionValues?: AutoDimensionValues | null;
|
||||||
}) {
|
}) {
|
||||||
const { context, annotation, imageSize, annotations, autoDimensionValues } =
|
const { context, annotation } = params;
|
||||||
params;
|
|
||||||
const annotationColor = getAnnotationColor(annotation);
|
const annotationColor = getAnnotationColor(annotation);
|
||||||
const label = getDimensionLabel({
|
const geometry = getPreviewAnnotationGeometry(params);
|
||||||
annotation,
|
|
||||||
annotations,
|
|
||||||
autoDimensionValues,
|
|
||||||
});
|
|
||||||
const vector = getAnnotationVector(
|
|
||||||
annotation.x1,
|
|
||||||
annotation.y1,
|
|
||||||
annotation.x2,
|
|
||||||
annotation.y2
|
|
||||||
);
|
|
||||||
const rawAngleRadians = Math.atan2(vector.dy, vector.dx);
|
|
||||||
const angleRadians =
|
|
||||||
rawAngleRadians > Math.PI / 2
|
|
||||||
? rawAngleRadians - Math.PI
|
|
||||||
: rawAngleRadians < -Math.PI / 2
|
|
||||||
? rawAngleRadians + Math.PI
|
|
||||||
: rawAngleRadians;
|
|
||||||
const strokeWidth = clamp(
|
|
||||||
Math.min(imageSize.width, imageSize.height) * 0.001_35,
|
|
||||||
1,
|
|
||||||
2.4
|
|
||||||
);
|
|
||||||
const capLength = strokeWidth * 5.3;
|
|
||||||
const fontSize = clamp(
|
|
||||||
Math.round(Math.min(imageSize.width, imageSize.height) * 0.0176),
|
|
||||||
11,
|
|
||||||
27
|
|
||||||
);
|
|
||||||
const labelOffset = fontSize * 0.95;
|
|
||||||
const centerX = (annotation.x1 + annotation.x2) / 2 + vector.nx * labelOffset;
|
|
||||||
const centerY = (annotation.y1 + annotation.y2) / 2 + vector.ny * labelOffset;
|
|
||||||
const textOutlineColor = getAnnotationTextOutlineColor(annotation);
|
const textOutlineColor = getAnnotationTextOutlineColor(annotation);
|
||||||
const textOutlineWidth = annotation.glow
|
|
||||||
? Math.max(1.5, fontSize * 0.18)
|
|
||||||
: Math.max(0.85, fontSize * 0.08);
|
|
||||||
|
|
||||||
context.save();
|
context.save();
|
||||||
context.strokeStyle = annotationColor;
|
context.strokeStyle = annotationColor;
|
||||||
context.lineWidth = strokeWidth;
|
context.lineWidth = PREVIEW_DIMENSION_STROKE_WIDTH;
|
||||||
context.lineCap = "round";
|
context.lineCap = "round";
|
||||||
context.lineJoin = "round";
|
context.lineJoin = "round";
|
||||||
context.shadowColor = annotation.glow
|
context.shadowColor = annotation.glow
|
||||||
? colorWithAlpha(annotationColor, 0.52)
|
? colorWithAlpha(annotationColor, 0.42)
|
||||||
: "transparent";
|
: "transparent";
|
||||||
context.shadowBlur = annotation.glow ? Math.max(8, fontSize * 0.7) : 0;
|
context.shadowBlur = annotation.glow ? 4 : 0;
|
||||||
|
|
||||||
context.beginPath();
|
context.beginPath();
|
||||||
context.moveTo(annotation.x1, annotation.y1);
|
context.moveTo(geometry.start.x, geometry.start.y);
|
||||||
context.lineTo(annotation.x2, annotation.y2);
|
context.lineTo(geometry.end.x, geometry.end.y);
|
||||||
context.stroke();
|
context.stroke();
|
||||||
|
|
||||||
|
context.lineWidth = PREVIEW_DIMENSION_CAP_STROKE_WIDTH;
|
||||||
drawDimensionCap({
|
drawDimensionCap({
|
||||||
context,
|
context,
|
||||||
point: { x: annotation.x1, y: annotation.y1 },
|
point: geometry.start,
|
||||||
size: capLength,
|
size: PREVIEW_DIMENSION_TICK_LENGTH,
|
||||||
vector,
|
vector: geometry.vector,
|
||||||
});
|
});
|
||||||
drawDimensionCap({
|
drawDimensionCap({
|
||||||
context,
|
context,
|
||||||
point: { x: annotation.x2, y: annotation.y2 },
|
point: geometry.end,
|
||||||
size: capLength,
|
size: PREVIEW_DIMENSION_TICK_LENGTH,
|
||||||
vector,
|
vector: geometry.vector,
|
||||||
});
|
});
|
||||||
|
|
||||||
context.translate(centerX, centerY);
|
context.translate(geometry.labelCenterX, geometry.labelCenterY);
|
||||||
context.rotate(angleRadians);
|
context.rotate((geometry.angleDegrees * Math.PI) / 180);
|
||||||
context.font = `500 ${fontSize}px "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif`;
|
context.font = `500 ${PREVIEW_DIMENSION_FONT_SIZE}px ${DIMENSION_FONT_FAMILY}`;
|
||||||
context.textAlign = "center";
|
context.textAlign = "center";
|
||||||
context.textBaseline = "middle";
|
context.textBaseline = "middle";
|
||||||
context.lineWidth = textOutlineWidth;
|
context.lineWidth = getAnnotationTextOutlineWidth(annotation);
|
||||||
context.strokeStyle = textOutlineColor;
|
context.strokeStyle = textOutlineColor;
|
||||||
context.strokeText(label, 0, 0);
|
context.strokeText(geometry.label, 0, 0.5);
|
||||||
context.fillStyle = annotationColor;
|
context.fillStyle = annotationColor;
|
||||||
context.fillText(label, 0, 0);
|
context.fillText(geometry.label, 0, 0.5);
|
||||||
context.restore();
|
context.restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1067,6 +1036,10 @@ export function AgentPsdTemplateExportPreview({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!imageSize || !previewRect) {
|
||||||
|
throw new Error("请等待预览图片加载完成后再下载");
|
||||||
|
}
|
||||||
|
|
||||||
const { image, dispose } = await loadImageFromCandidates([
|
const { image, dispose } = await loadImageFromCandidates([
|
||||||
buildImageProxyUrl(imageUrl, { delivery: "proxy" }),
|
buildImageProxyUrl(imageUrl, { delivery: "proxy" }),
|
||||||
imageUrl,
|
imageUrl,
|
||||||
@ -1082,18 +1055,25 @@ export function AgentPsdTemplateExportPreview({
|
|||||||
}
|
}
|
||||||
|
|
||||||
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
||||||
|
// Draw in the same coordinates as the SVG, then map its image area to
|
||||||
|
// the original bitmap. The preview can use a smaller image variant.
|
||||||
|
context.save();
|
||||||
|
context.scale(
|
||||||
|
canvas.width / previewRect.width,
|
||||||
|
canvas.height / previewRect.height
|
||||||
|
);
|
||||||
|
context.translate(-previewRect.left, -previewRect.top);
|
||||||
for (const annotation of annotations) {
|
for (const annotation of annotations) {
|
||||||
drawAnnotationToCanvas({
|
drawAnnotationToCanvas({
|
||||||
annotation,
|
annotation,
|
||||||
annotations,
|
annotations,
|
||||||
autoDimensionValues,
|
autoDimensionValues,
|
||||||
context,
|
context,
|
||||||
imageSize: {
|
imageSize,
|
||||||
width: canvas.width,
|
previewRect,
|
||||||
height: canvas.height,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
context.restore();
|
||||||
|
|
||||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||||
canvas.toBlob(
|
canvas.toBlob(
|
||||||
@ -1125,6 +1105,8 @@ export function AgentPsdTemplateExportPreview({
|
|||||||
downloadName,
|
downloadName,
|
||||||
enableDimensionAnnotations,
|
enableDimensionAnnotations,
|
||||||
imageUrl,
|
imageUrl,
|
||||||
|
imageSize,
|
||||||
|
previewRect,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -1305,6 +1287,7 @@ export function AgentPsdTemplateExportPreview({
|
|||||||
<text
|
<text
|
||||||
dominantBaseline="middle"
|
dominantBaseline="middle"
|
||||||
fill={annotationColor}
|
fill={annotationColor}
|
||||||
|
fontFamily={DIMENSION_FONT_FAMILY}
|
||||||
fontSize={PREVIEW_DIMENSION_FONT_SIZE}
|
fontSize={PREVIEW_DIMENSION_FONT_SIZE}
|
||||||
fontWeight={500}
|
fontWeight={500}
|
||||||
paintOrder="stroke"
|
paintOrder="stroke"
|
||||||
|
|||||||
@ -107,6 +107,7 @@ export function AngleEditDialog({
|
|||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
image_url: imageUrl,
|
image_url: imageUrl,
|
||||||
|
includeBase64: false,
|
||||||
horizontal_angle: cameraState.azimuth, // 0-360 度
|
horizontal_angle: cameraState.azimuth, // 0-360 度
|
||||||
vertical_angle: cameraState.elevation, // -30 到 90 度
|
vertical_angle: cameraState.elevation, // -30 到 90 度
|
||||||
zoom: cameraState.distance, // 0-10
|
zoom: cameraState.distance, // 0-10
|
||||||
|
|||||||
77
components/app-update-notice.tsx
Normal file
77
components/app-update-notice.tsx
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
"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("");
|
setError("");
|
||||||
setSending(true);
|
setSending(true);
|
||||||
try {
|
try {
|
||||||
if (!model) throw Error("当前模式没有已启用的官方模型");
|
if (!model) throw Error("当前模式没有已启用的模型");
|
||||||
const params = audioRequestSchema.parse({
|
const params = audioRequestSchema.parse({
|
||||||
...draft,
|
...draft,
|
||||||
text: [draft.text, connectedText].filter(Boolean).join("\n\n"),
|
text: [draft.text, connectedText].filter(Boolean).join("\n\n"),
|
||||||
modelRef: model.id,
|
modelRef: model.id,
|
||||||
voice,
|
voice,
|
||||||
format,
|
format: format || "wav",
|
||||||
...(!contract?.controls ? { rate: 1, pitch: 1, volume: 50 } : {}),
|
...(!contract?.controls ? { rate: 1, pitch: 1, volume: 50 } : {}),
|
||||||
...(!contract?.instructions ? { instructions: "" } : {}),
|
...(!contract?.instructions ? { instructions: "" } : {}),
|
||||||
});
|
});
|
||||||
@ -96,9 +96,9 @@ export function AudioGenerationComposer({
|
|||||||
<section
|
<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"
|
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"
|
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">
|
<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>}
|
{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">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
@ -112,6 +112,9 @@ export function AudioGenerationComposer({
|
|||||||
>
|
>
|
||||||
<option value="tts">文字配音</option>
|
<option value="tts">文字配音</option>
|
||||||
<option value="music">音乐 / 歌曲</option>
|
<option value="music">音乐 / 歌曲</option>
|
||||||
|
<option value="asr">语音转文字</option>
|
||||||
|
<option value="voiceclone">声音克隆配音</option>
|
||||||
|
<option value="voicedesign">声音设计配音</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
@ -134,20 +137,40 @@ export function AudioGenerationComposer({
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<label className="block">
|
{["asr", "voiceclone"].includes(draft.mode) && (
|
||||||
{draft.mode === "tts" ? "配音文本(最多 600 字)" : "音乐描述"}
|
<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} 字)`}
|
||||||
<textarea
|
<textarea
|
||||||
aria-label="音频内容"
|
aria-label="音频内容"
|
||||||
className={input}
|
className={input}
|
||||||
rows={4}
|
rows={4}
|
||||||
maxLength={draft.mode === "tts" ? 600 : 2000}
|
maxLength={draft.mode !== "music" ? 600 : contract?.descriptionLimit || 2000}
|
||||||
value={draft.text}
|
value={draft.text}
|
||||||
onChange={(e) => patch({ text: e.target.value })}
|
onChange={(e) => patch({ text: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>}
|
||||||
{draft.mode === "tts" ? (
|
{!["music", "asr"].includes(draft.mode) ? (
|
||||||
<>
|
<>
|
||||||
<div className="grid grid-cols-2 gap-3">
|
{!!contract?.voices.length && <div className="grid grid-cols-2 gap-3">
|
||||||
<label>
|
<label>
|
||||||
音色
|
音色
|
||||||
<select
|
<select
|
||||||
@ -163,7 +186,7 @@ export function AudioGenerationComposer({
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
{contract?.supportsLanguageControl !== false && <label>
|
||||||
语言
|
语言
|
||||||
<select
|
<select
|
||||||
aria-label="配音语言"
|
aria-label="配音语言"
|
||||||
@ -175,8 +198,8 @@ export function AudioGenerationComposer({
|
|||||||
<option value="English">英文</option>
|
<option value="English">英文</option>
|
||||||
<option value="Auto">自动 / 中英混合</option>
|
<option value="Auto">自动 / 中英混合</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>}
|
||||||
</div>
|
</div>}
|
||||||
{contract?.instructions ? (
|
{contract?.instructions ? (
|
||||||
<label className="block">
|
<label className="block">
|
||||||
声音风格指令
|
声音风格指令
|
||||||
@ -210,7 +233,7 @@ export function AudioGenerationComposer({
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : draft.mode === "music" ? (
|
||||||
<>
|
<>
|
||||||
<label className="flex gap-2">
|
<label className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
@ -233,7 +256,7 @@ export function AudioGenerationComposer({
|
|||||||
onChange={(e) => patch({ lyrics: e.target.value })}
|
onChange={(e) => patch({ lyrics: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label>
|
{contract?.supportsGender !== false && (!contract?.genderRequiresLyrics || draft.lyrics?.trim()) && <label>
|
||||||
演唱声音
|
演唱声音
|
||||||
<select
|
<select
|
||||||
className={input}
|
className={input}
|
||||||
@ -244,18 +267,18 @@ export function AudioGenerationComposer({
|
|||||||
<option value="female">女声</option>
|
<option value="female">女声</option>
|
||||||
<option value="male">男声</option>
|
<option value="male">男声</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>}
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{!options.length ? (
|
{!options.length ? (
|
||||||
<p className="text-sm text-amber-200">
|
<p className="text-sm text-amber-200">
|
||||||
Fun-Music 需要阿里云邀测权限,开通并启用模型后即可生成。
|
当前没有可用的音乐模型,请在模型设置中启用。
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
</>
|
</>
|
||||||
)}
|
) : null}
|
||||||
<div className="flex items-end gap-3">
|
<div className="flex items-end gap-3">
|
||||||
<label>
|
{draft.mode !== "asr" && <label>
|
||||||
格式
|
格式
|
||||||
<select
|
<select
|
||||||
aria-label="音频格式"
|
aria-label="音频格式"
|
||||||
@ -269,14 +292,14 @@ export function AudioGenerationComposer({
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={!model || loading}
|
disabled={!model || loading}
|
||||||
className="rounded-lg bg-white px-4 py-2 text-black disabled:opacity-40"
|
className="rounded-lg bg-white px-4 py-2 text-black disabled:opacity-40"
|
||||||
onClick={() => void run()}
|
onClick={() => void run()}
|
||||||
>
|
>
|
||||||
{busy || sending ? "处理中…" : "生成音频"}
|
{busy || sending ? "处理中…" : draft.mode === "asr" ? "识别文字" : "生成音频"}
|
||||||
</button>
|
</button>
|
||||||
<label className="cursor-pointer rounded-lg border border-white/20 px-3 py-2">
|
<label className="cursor-pointer rounded-lg border border-white/20 px-3 py-2">
|
||||||
上传音频
|
上传音频
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Check, ImageIcon, ImagePlus, Loader2, Search, X } from "lucide-react";
|
import { Check, ImageIcon, ImagePlus, Loader2, Search, Upload, X } from "lucide-react";
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useMemo, useRef, useState } from "react";
|
||||||
import { AgentPreviewImage } from "@/components/agents/AgentPreviewImage";
|
import { AgentPreviewImage } from "@/components/agents/AgentPreviewImage";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@ -21,6 +21,8 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { IMAGE_UPLOAD_MAX_BYTES, IMAGE_UPLOAD_TOO_LARGE_MESSAGE } from "@/lib/image-upload-limits";
|
||||||
|
import { imageGenerationService } from "@/services/canvas";
|
||||||
import type {
|
import type {
|
||||||
AgentWorkflowMaterialImage,
|
AgentWorkflowMaterialImage,
|
||||||
AgentWorkflowMaterialQueryType,
|
AgentWorkflowMaterialQueryType,
|
||||||
@ -163,6 +165,8 @@ export function CanvasAddImageDialog({
|
|||||||
const [selectedImageIds, setSelectedImageIds] = useState<string[]>([]);
|
const [selectedImageIds, setSelectedImageIds] = useState<string[]>([]);
|
||||||
const [isSearching, setIsSearching] = useState(false);
|
const [isSearching, setIsSearching] = useState(false);
|
||||||
const [isAdding, setIsAdding] = useState(false);
|
const [isAdding, setIsAdding] = useState(false);
|
||||||
|
const [isUploading, setIsUploading] = useState(false);
|
||||||
|
const localUploadInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [errorText, setErrorText] = useState<string | null>(null);
|
const [errorText, setErrorText] = useState<string | null>(null);
|
||||||
|
|
||||||
const images = useMemo(() => normalizeImages(result), [result]);
|
const images = useMemo(() => normalizeImages(result), [result]);
|
||||||
@ -182,12 +186,13 @@ export function CanvasAddImageDialog({
|
|||||||
|
|
||||||
const handleDialogOpenChange = useCallback(
|
const handleDialogOpenChange = useCallback(
|
||||||
(nextOpen: boolean) => {
|
(nextOpen: boolean) => {
|
||||||
|
if (!nextOpen && (isUploading || isAdding)) return;
|
||||||
if (!nextOpen) {
|
if (!nextOpen) {
|
||||||
resetDialogState();
|
resetDialogState();
|
||||||
}
|
}
|
||||||
onOpenChange(nextOpen);
|
onOpenChange(nextOpen);
|
||||||
},
|
},
|
||||||
[onOpenChange, resetDialogState]
|
[isAdding, isUploading, onOpenChange, resetDialogState]
|
||||||
);
|
);
|
||||||
|
|
||||||
const closeDialog = useCallback(() => {
|
const closeDialog = useCallback(() => {
|
||||||
@ -263,6 +268,51 @@ export function CanvasAddImageDialog({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleLocalUpload = async (files: File[]) => {
|
||||||
|
if (!files.length || isUploading || isAdding) return;
|
||||||
|
if (files.some((file) => !file.type.startsWith("image/"))) {
|
||||||
|
setErrorText("请选择图片文件");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (files.some((file) => file.size > IMAGE_UPLOAD_MAX_BYTES)) {
|
||||||
|
setErrorText(IMAGE_UPLOAD_TOO_LARGE_MESSAGE);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsUploading(true);
|
||||||
|
setErrorText(null);
|
||||||
|
try {
|
||||||
|
const uploadedImages: CanvasAddImageDialogImage[] = [];
|
||||||
|
const failures: string[] = [];
|
||||||
|
for (const [index, file] of files.entries()) {
|
||||||
|
const upload = await imageGenerationService.uploadImage(file);
|
||||||
|
if (!upload.success || !upload.data?.url) {
|
||||||
|
failures.push(`${file.name}:${upload.error || "图片上传失败"}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
uploadedImages.push({
|
||||||
|
id: upload.data.assetId || crypto.randomUUID(),
|
||||||
|
key: upload.data.pathname || file.name,
|
||||||
|
label: file.name.replace(/\.[^.]+$/, "") || file.name,
|
||||||
|
fileName: file.name,
|
||||||
|
imageUrl: upload.data.url,
|
||||||
|
assetId: upload.data.assetId,
|
||||||
|
mimeType: file.type,
|
||||||
|
sourceType: "upload",
|
||||||
|
group: "other",
|
||||||
|
sortOrder: index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (uploadedImages.length) await onAddImages(uploadedImages);
|
||||||
|
if (failures.length) setErrorText(failures.join(";"));
|
||||||
|
else closeDialog();
|
||||||
|
} catch (error) {
|
||||||
|
setErrorText(error instanceof Error ? error.message : "图片上传失败,请重试");
|
||||||
|
} finally {
|
||||||
|
setIsUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog onOpenChange={handleDialogOpenChange} open={open}>
|
<Dialog onOpenChange={handleDialogOpenChange} open={open}>
|
||||||
<DialogContent className="max-h-[86vh] max-w-4xl overflow-hidden p-0">
|
<DialogContent className="max-h-[86vh] max-w-4xl overflow-hidden p-0">
|
||||||
@ -272,15 +322,38 @@ export function CanvasAddImageDialog({
|
|||||||
添加图片
|
添加图片
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription>
|
<DialogDescription>
|
||||||
添加空白图片节点,或从风格化素材库检索 SPU / SKU 白底图。
|
从本地上传图片、添加空白图片节点,或检索 SPU / SKU 白底图。
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="max-h-[62vh] overflow-y-auto px-5 py-4">
|
<div className="max-h-[62vh] overflow-y-auto px-5 py-4">
|
||||||
<div className="rounded-[var(--ui-radius-panel)] border bg-muted/20 p-3">
|
<div className="rounded-[var(--ui-radius-panel)] border bg-muted/20 p-3">
|
||||||
<div className="flex flex-col gap-2.5 sm:flex-row">
|
<div className="flex flex-col gap-2.5 sm:flex-row">
|
||||||
|
<input
|
||||||
|
accept="image/*"
|
||||||
|
className="hidden"
|
||||||
|
multiple
|
||||||
|
onChange={(event) => {
|
||||||
|
const files = Array.from(event.target.files || []);
|
||||||
|
event.target.value = "";
|
||||||
|
void handleLocalUpload(files);
|
||||||
|
}}
|
||||||
|
ref={localUploadInputRef}
|
||||||
|
type="file"
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
className="h-9 justify-start gap-2"
|
className="h-9 shrink-0 justify-start gap-2"
|
||||||
|
disabled={isUploading || isAdding}
|
||||||
|
onClick={() => localUploadInputRef.current?.click()}
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
>
|
||||||
|
{isUploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
|
||||||
|
{isUploading ? "上传中…" : "本地上传"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="h-9 shrink-0 justify-start gap-2"
|
||||||
|
disabled={isUploading || isAdding}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
onCreateBlankImage();
|
onCreateBlankImage();
|
||||||
closeDialog();
|
closeDialog();
|
||||||
@ -355,13 +428,13 @@ export function CanvasAddImageDialog({
|
|||||||
</div>
|
</div>
|
||||||
{!materialSearchEnabled ? (
|
{!materialSearchEnabled ? (
|
||||||
<div className="mt-2.5 rounded-[var(--ui-radius-control)] border border-dashed bg-background/70 px-3 py-2 text-[12px] text-muted-foreground">
|
<div className="mt-2.5 rounded-[var(--ui-radius-control)] border border-dashed bg-background/70 px-3 py-2 text-[12px] text-muted-foreground">
|
||||||
风格化功能或素材搜索步骤未开启,当前只显示空白图片入口。
|
风格化功能或素材搜索步骤未开启,可从本地上传或添加空白图片。
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{errorText ? (
|
{errorText ? (
|
||||||
<div className="mt-3 rounded-[var(--ui-radius-control)] border border-destructive/20 bg-destructive/5 px-3 py-2 text-[13px] text-destructive">
|
<div role="alert" className="mt-3 rounded-[var(--ui-radius-control)] border border-destructive/20 bg-destructive/5 px-3 py-2 text-[13px] text-destructive">
|
||||||
{errorText}
|
{errorText}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
@ -440,6 +513,7 @@ export function CanvasAddImageDialog({
|
|||||||
|
|
||||||
<DialogFooter className="border-t px-5 py-3">
|
<DialogFooter className="border-t px-5 py-3">
|
||||||
<Button
|
<Button
|
||||||
|
disabled={isUploading || isAdding}
|
||||||
onClick={closeDialog}
|
onClick={closeDialog}
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
@ -448,7 +522,7 @@ export function CanvasAddImageDialog({
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
className="gap-2"
|
className="gap-2"
|
||||||
disabled={!selectedImages.length || isAdding}
|
disabled={!selectedImages.length || isAdding || isUploading}
|
||||||
onClick={() => void handleAddSelected()}
|
onClick={() => void handleAddSelected()}
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
|
|||||||
115
components/canvas/CanvasBlankContextMenu.tsx
Normal file
115
components/canvas/CanvasBlankContextMenu.tsx
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import type { Position } from "@/types/canvas";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
position: Position | null;
|
||||||
|
isMac: boolean;
|
||||||
|
videoUploading: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onUploadImage: () => void;
|
||||||
|
onUploadVideo: () => void;
|
||||||
|
onPaste: () => void;
|
||||||
|
onZoomIn: () => void;
|
||||||
|
onZoomOut: () => void;
|
||||||
|
onFitAll: () => void;
|
||||||
|
onResetZoom: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CanvasBlankContextMenu({
|
||||||
|
position,
|
||||||
|
isMac,
|
||||||
|
videoUploading,
|
||||||
|
onClose,
|
||||||
|
onUploadImage,
|
||||||
|
onUploadVideo,
|
||||||
|
onPaste,
|
||||||
|
onZoomIn,
|
||||||
|
onZoomOut,
|
||||||
|
onFitAll,
|
||||||
|
onResetZoom,
|
||||||
|
}: Props) {
|
||||||
|
const modifier = isMac ? "⌘" : "Ctrl+";
|
||||||
|
const itemClass =
|
||||||
|
"h-8 cursor-pointer justify-between whitespace-nowrap rounded-[5px] px-0 text-[14px] font-normal focus:bg-[#f5f5f5] dark:focus:bg-white/10";
|
||||||
|
const shortcut = (label: string) => (
|
||||||
|
<span className="ml-2 whitespace-nowrap text-[13px] text-[#aaa]">
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<DropdownMenu
|
||||||
|
modal={false}
|
||||||
|
open={position !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<button
|
||||||
|
aria-hidden="true"
|
||||||
|
tabIndex={-1}
|
||||||
|
data-canvas-no-drag="true"
|
||||||
|
className="pointer-events-none fixed h-px w-px opacity-0"
|
||||||
|
style={{ left: position?.x ?? 0, top: position?.y ?? 0 }}
|
||||||
|
type="button"
|
||||||
|
/>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent
|
||||||
|
aria-label="画布右键菜单"
|
||||||
|
align="start"
|
||||||
|
sideOffset={0}
|
||||||
|
collisionPadding={8}
|
||||||
|
data-canvas-blank-menu="true"
|
||||||
|
data-canvas-no-drag="true"
|
||||||
|
className="z-[10005] w-[200px] rounded-[12px] border-[#ededed] bg-white px-3 py-[5px] text-[#242424] shadow-[0_8px_20px_rgba(0,0,0,0.06)] ring-0 dark:border-white/10 dark:bg-zinc-900 dark:text-white"
|
||||||
|
style={{
|
||||||
|
fontFamily:
|
||||||
|
'Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif',
|
||||||
|
}}
|
||||||
|
onCloseAutoFocus={(event) => event.preventDefault()}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
onMouseDown={(event) => event.stopPropagation()}
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onUploadImage}>
|
||||||
|
上传图片
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
className={itemClass}
|
||||||
|
disabled={videoUploading}
|
||||||
|
onSelect={onUploadVideo}
|
||||||
|
>
|
||||||
|
上传视频
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator className="mx-0 my-[6.5px] bg-[#ededed] dark:bg-white/10" />
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onPaste}>
|
||||||
|
粘贴{shortcut(`${modifier}V`)}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuSeparator className="mx-0 my-[6.5px] bg-[#ededed] dark:bg-white/10" />
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onZoomIn}>
|
||||||
|
放大{shortcut(`${modifier}+`)}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onZoomOut}>
|
||||||
|
缩小{shortcut(`${modifier}-`)}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onFitAll}>
|
||||||
|
显示画布所有元素{shortcut(isMac ? "⇧1" : "Shift+1")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem className={itemClass} onSelect={onResetZoom}>
|
||||||
|
缩放至100%{shortcut(`${modifier}0`)}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
54
components/canvas/CanvasComposerPromo.tsx
Normal file
54
components/canvas/CanvasComposerPromo.tsx
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ReferenceIcon } from "@/components/lovart/reference-icon";
|
||||||
|
|
||||||
|
type CanvasComposerPromoProps = {
|
||||||
|
text: string;
|
||||||
|
onDismiss: () => void;
|
||||||
|
onActivate?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CanvasComposerPromo({
|
||||||
|
text,
|
||||||
|
onDismiss,
|
||||||
|
onActivate,
|
||||||
|
}: CanvasComposerPromoProps) {
|
||||||
|
return (
|
||||||
|
<div className="lovart-chat-promo lovart-chat-promo-connected">
|
||||||
|
<div className="lovart-chat-promo-surface">
|
||||||
|
<div className="lovart-chat-promo-row">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="lovart-chat-promo-message"
|
||||||
|
onClick={onActivate}
|
||||||
|
disabled={!onActivate}
|
||||||
|
title={text}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
aria-hidden="true"
|
||||||
|
width="16"
|
||||||
|
height="18"
|
||||||
|
viewBox="0 0 24 28"
|
||||||
|
className="lovart-chat-promo-badge"
|
||||||
|
>
|
||||||
|
<path d="M10 1.15a4 4 0 0 1 4 0l8 4.6a4 4 0 0 1 2 3.46v9.58a4 4 0 0 1-2 3.46l-8 4.6a4 4 0 0 1-4 0l-8-4.6A4 4 0 0 1 0 18.79V9.21a4 4 0 0 1 2-3.46Z" fill="#ddef65" />
|
||||||
|
<path
|
||||||
|
d="M12 5.5c1.2 5.3 2.2 6.3 7.5 7.5-5.3 1.2-6.3 2.2-7.5 7.5C10.8 15.2 9.8 14.2 4.5 13c5.3-1.2 6.3-2.2 7.5-7.5Z"
|
||||||
|
fill="#111"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
<span>{text}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="lovart-chat-promo-close"
|
||||||
|
aria-label="关闭优惠广告"
|
||||||
|
onClick={onDismiss}
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="close" size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
383
components/canvas/CanvasFeedbackDialog.tsx
Normal file
383
components/canvas/CanvasFeedbackDialog.tsx
Normal file
@ -0,0 +1,383 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Bug } from "lucide-react";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { captureFeedbackChat } from "@/lib/canvas/feedback-client";
|
||||||
|
import { useCanvasStore } from "@/store/canvas";
|
||||||
|
import {
|
||||||
|
feedbackCommandSchema,
|
||||||
|
formatFeedbackTime,
|
||||||
|
type FeedbackClient,
|
||||||
|
type FeedbackContext,
|
||||||
|
type FeedbackReceipt,
|
||||||
|
} from "@/lib/canvas/feedback-contract";
|
||||||
|
|
||||||
|
type Submission = Extract<ReturnType<typeof feedbackCommandSchema.parse>, { action: "submit" }>;
|
||||||
|
const terminal = (value: string) => ["sent", "unread", "read", "failed"].includes(value);
|
||||||
|
const fieldClass =
|
||||||
|
"w-full rounded-lg border border-input bg-background px-3 py-2 text-sm text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring";
|
||||||
|
|
||||||
|
export function CanvasFeedbackDialog({
|
||||||
|
projectId,
|
||||||
|
pagePath,
|
||||||
|
floating = false,
|
||||||
|
}: {
|
||||||
|
projectId?: string;
|
||||||
|
pagePath?: string;
|
||||||
|
floating?: boolean;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [context, setContext] = useState<FeedbackContext | null>(null);
|
||||||
|
const [selection, setSelection] = useState<string | null>(null);
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [sealed, setSealed] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [receipt, setReceipt] = useState<FeedbackReceipt | null>(null);
|
||||||
|
const captured = useRef<FeedbackClient | null>(null);
|
||||||
|
const submission = useRef<Submission | null>(null);
|
||||||
|
const errors = useRef<string[]>([]);
|
||||||
|
const submitLock = useRef(false);
|
||||||
|
const endpoint = projectId ? "/api/canvas/" + projectId + "/feedback" : "/api/feedback";
|
||||||
|
const storageKey = projectId ? "canvas-feedback:" + projectId : "page-feedback:" + pagePath;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const rememberError = (event: ErrorEvent) => {
|
||||||
|
errors.current = [
|
||||||
|
...errors.current,
|
||||||
|
String(event.message || "页面脚本错误").slice(0, 2000),
|
||||||
|
].slice(-5);
|
||||||
|
};
|
||||||
|
window.addEventListener("error", rememberError);
|
||||||
|
return () => window.removeEventListener("error", rememberError);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || receipt) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(storageKey);
|
||||||
|
if (raw && !submission.current) {
|
||||||
|
const command = feedbackCommandSchema.parse(JSON.parse(raw));
|
||||||
|
if (command.action === "submit") {
|
||||||
|
submission.current = command;
|
||||||
|
captured.current = command.client;
|
||||||
|
setSealed(true);
|
||||||
|
setDescription(command.description);
|
||||||
|
setSelection(command.selection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* An unavailable local draft does not prevent a new feedback report. */
|
||||||
|
}
|
||||||
|
if (submission.current) {
|
||||||
|
void fetch(`${endpoint}?feedbackId=${submission.current.id}`, {
|
||||||
|
cache: "no-store",
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
.then(async (response) => {
|
||||||
|
const data = await response.json();
|
||||||
|
if (response.ok) setReceipt(data.feedback);
|
||||||
|
else if (response.status !== 404)
|
||||||
|
setError(data.error || "暂时无法确认反馈状态,请重试提交同一条反馈。");
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!controller.signal.aborted) setError("暂时无法确认反馈状态,可重试提交同一条反馈。");
|
||||||
|
});
|
||||||
|
return () => controller.abort();
|
||||||
|
}
|
||||||
|
const canvas = useCanvasStore.getState();
|
||||||
|
const selectedIds = new Set(canvas.selectedNodeIds);
|
||||||
|
const nodes = projectId ? [...canvas.nodes]
|
||||||
|
.sort((a, b) => Number(selectedIds.has(b.id)) - Number(selectedIds.has(a.id)))
|
||||||
|
.slice(0, 20) : [];
|
||||||
|
const client: FeedbackClient = {
|
||||||
|
...(projectId ? captureFeedbackChat(projectId) : { chatId: null, messages: [] }),
|
||||||
|
pagePath,
|
||||||
|
capturedAt: new Date().toISOString(),
|
||||||
|
pageVersion: process.env.NEXT_PUBLIC_APP_RELEASE || "development",
|
||||||
|
viewport: { width: window.innerWidth, height: window.innerHeight },
|
||||||
|
online: navigator.onLine,
|
||||||
|
errors: [...errors.current],
|
||||||
|
nodes: nodes.map((node) => {
|
||||||
|
const data = node.data as unknown as Record<string, unknown>;
|
||||||
|
const metadata = data.metadata as Record<string, unknown> | undefined;
|
||||||
|
return {
|
||||||
|
id: node.id.slice(0, 180),
|
||||||
|
type: node.type.slice(0, 64),
|
||||||
|
title: String(data.title || "").slice(0, 256),
|
||||||
|
status: String(data.status || "").slice(0, 64),
|
||||||
|
taskId: String(metadata?.taskId || "").slice(0, 180),
|
||||||
|
width: node.size?.width,
|
||||||
|
height: node.size?.height,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
captured.current = client;
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
void fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ action: "context", client }),
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
.then(async (response) => {
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.error || "排查资料暂时加载失败,请重新打开反馈。");
|
||||||
|
setContext(data.context);
|
||||||
|
setSelection(data.context.requests[0]?.key || null);
|
||||||
|
})
|
||||||
|
.catch((failure) => {
|
||||||
|
if (!controller.signal.aborted)
|
||||||
|
setError(failure.message || "排查资料暂时加载失败,请重新打开反馈。");
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!controller.signal.aborted) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => controller.abort();
|
||||||
|
}, [open, endpoint, projectId, pagePath, receipt, storageKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !receipt || terminal(receipt.status)) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${endpoint}?feedbackId=${receipt.id}`, {
|
||||||
|
cache: "no-store",
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (response.ok && !controller.signal.aborted) {
|
||||||
|
setReceipt(data.feedback);
|
||||||
|
setError("");
|
||||||
|
} else if (!controller.signal.aborted)
|
||||||
|
setError(data.error || "暂时无法刷新通知状态,已保存的反馈会继续处理。");
|
||||||
|
} catch {
|
||||||
|
if (!controller.signal.aborted)
|
||||||
|
setError("网络暂时不可用,已保存的反馈会继续处理,请勿重复提交。");
|
||||||
|
}
|
||||||
|
if (!controller.signal.aborted) timer = setTimeout(poll, 4000);
|
||||||
|
};
|
||||||
|
timer = setTimeout(poll, 1500);
|
||||||
|
return () => {
|
||||||
|
controller.abort();
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [open, receipt?.id, receipt?.status, endpoint]);
|
||||||
|
|
||||||
|
const send = async () => {
|
||||||
|
if (submitLock.current || receipt) return;
|
||||||
|
if (!submission.current) {
|
||||||
|
if (!captured.current || !context || (!projectId && !description.trim())) return;
|
||||||
|
submission.current = {
|
||||||
|
action: "submit",
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
description,
|
||||||
|
selection,
|
||||||
|
client: captured.current,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(storageKey, JSON.stringify(submission.current));
|
||||||
|
} catch {
|
||||||
|
/* In-memory retries still retain this report's id. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
submitLock.current = true;
|
||||||
|
setSending(true);
|
||||||
|
setSealed(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
const response = await fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(submission.current),
|
||||||
|
signal: AbortSignal.timeout(20000),
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 400 || response.status === 409 || response.status === 413) {
|
||||||
|
submission.current = null;
|
||||||
|
sessionStorage.removeItem(storageKey);
|
||||||
|
setSealed(false);
|
||||||
|
}
|
||||||
|
throw new Error(data.error || "暂时无法确认反馈是否保存,请重试提交同一条反馈。");
|
||||||
|
}
|
||||||
|
setReceipt(data.feedback);
|
||||||
|
} catch (failure) {
|
||||||
|
setError(
|
||||||
|
failure instanceof Error && failure.name !== "TimeoutError"
|
||||||
|
? failure.message
|
||||||
|
: "提交连接超时。请重试提交同一条反馈,系统会核对原编号,避免重复通知。",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
submitLock.current = false;
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startAnother = () => {
|
||||||
|
submission.current = null;
|
||||||
|
captured.current = null;
|
||||||
|
sessionStorage.removeItem(storageKey);
|
||||||
|
setContext(null);
|
||||||
|
setDescription("");
|
||||||
|
setSelection(null);
|
||||||
|
setError("");
|
||||||
|
setSealed(false);
|
||||||
|
setReceipt(null);
|
||||||
|
};
|
||||||
|
const selected = context?.requests.find((item) => item.key === selection);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
"inline-flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
|
||||||
|
floating ? "fixed bottom-20 right-4 z-40 min-h-10 border bg-background shadow-sm" : "ml-2",
|
||||||
|
)}
|
||||||
|
aria-label="问题反馈"
|
||||||
|
>
|
||||||
|
<Bug className="size-4 text-red-600 dark:text-red-400" aria-hidden="true" />
|
||||||
|
<span className="hidden sm:inline">问题反馈</span>
|
||||||
|
</button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent
|
||||||
|
className="max-h-[85dvh] overflow-y-auto sm:max-w-xl"
|
||||||
|
aria-busy={loading || sending}
|
||||||
|
>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>问题反馈</DialogTitle>
|
||||||
|
<DialogDescription className="text-pretty">
|
||||||
|
{projectId
|
||||||
|
? "自动附上当前画布、用户和相关请求资料。你可以补充问题现象,发送给魔礼红。"
|
||||||
|
: "自动附上当前页面和浏览器信息。请说明遇到的问题,发送给魔礼红。"}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
{receipt ? (
|
||||||
|
<div className="space-y-3 py-2" role="status" aria-live="polite">
|
||||||
|
<p className="text-sm">{receipt.message}</p>
|
||||||
|
<p className="break-all text-sm text-muted-foreground">反馈编号:{receipt.id}</p>
|
||||||
|
<a
|
||||||
|
href={`/feedback/${receipt.id}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="inline-block text-sm underline underline-offset-4"
|
||||||
|
>
|
||||||
|
查看已保存的完整反馈
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{loading ? (
|
||||||
|
<p role="status" className="py-4 text-sm text-muted-foreground">
|
||||||
|
正在整理排查资料…
|
||||||
|
</p>
|
||||||
|
) : context ? (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{context.reporter.name} · {context.project.title}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{projectId && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="canvas-feedback-request" className="text-sm font-medium">
|
||||||
|
关联请求
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="canvas-feedback-request"
|
||||||
|
className={fieldClass}
|
||||||
|
value={selection || ""}
|
||||||
|
disabled={sealed || loading}
|
||||||
|
onChange={(event) => setSelection(event.target.value || null)}
|
||||||
|
>
|
||||||
|
<option value="">页面或画布问题,不关联具体请求</option>
|
||||||
|
{context?.requests.map((item) => (
|
||||||
|
<option key={item.key} value={item.key}>
|
||||||
|
{item.createdAt ? formatFeedbackTime(item.createdAt) : "时间未记录"} ·{" "}
|
||||||
|
{item.prompt.slice(0, 45)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{selected && (
|
||||||
|
<div className="space-y-2 rounded-lg bg-muted p-3 text-sm">
|
||||||
|
<p>
|
||||||
|
请求号:
|
||||||
|
<span className="break-all">
|
||||||
|
{selected.requestId || "尚未获取,将附上消息编号"}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<p className="max-h-28 overflow-y-auto whitespace-pre-wrap break-words text-muted-foreground">
|
||||||
|
{selected.prompt}
|
||||||
|
</p>
|
||||||
|
{selected.error && (
|
||||||
|
<p className="whitespace-pre-wrap break-words">{selected.error}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="canvas-feedback-description" className="text-sm font-medium">
|
||||||
|
{projectId ? "补充说明" : "问题说明"}{" "}
|
||||||
|
{projectId && <span className="font-normal text-muted-foreground">(选填)</span>}
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="canvas-feedback-description"
|
||||||
|
rows={4}
|
||||||
|
maxLength={2000}
|
||||||
|
className={`${fieldClass} resize-y`}
|
||||||
|
value={description}
|
||||||
|
disabled={sealed}
|
||||||
|
onChange={(event) => setDescription(event.target.value)}
|
||||||
|
placeholder="例如:点击预览后一直加载,等待约 30 秒仍无法查看。"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{projectId && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
将附上相关请求内容、任务状态、页面版本及已记录的错误;本次反馈不会重新执行任务。
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p role="alert" className="whitespace-pre-wrap text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<DialogFooter className="gap-2 sm:space-x-0">
|
||||||
|
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||||||
|
{receipt ? "关闭" : "取消"}
|
||||||
|
</Button>
|
||||||
|
{receipt ? (
|
||||||
|
<Button type="button" variant="outline" onClick={startAnother}>
|
||||||
|
反馈另一个问题
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void send()}
|
||||||
|
disabled={sending || loading || (!submission.current && (!context || (!projectId && !description.trim())))}
|
||||||
|
>
|
||||||
|
{sending ? "正在发送…" : sealed ? "重试提交同一反馈" : "发送给魔礼红"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -19,6 +19,7 @@ const PROJECT_LIST_PAGE_SIZE = 24;
|
|||||||
interface CanvasFileListPanelProps {
|
interface CanvasFileListPanelProps {
|
||||||
currentId: string;
|
currentId: string;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
onNavigate?: (url: string) => void;
|
||||||
workspaceType?: CanvasWorkspaceType;
|
workspaceType?: CanvasWorkspaceType;
|
||||||
workspaceLabel?: string;
|
workspaceLabel?: string;
|
||||||
createUrl?: string;
|
createUrl?: string;
|
||||||
@ -28,6 +29,7 @@ interface CanvasFileListPanelProps {
|
|||||||
export function CanvasFileListPanel({
|
export function CanvasFileListPanel({
|
||||||
currentId,
|
currentId,
|
||||||
onClose,
|
onClose,
|
||||||
|
onNavigate,
|
||||||
workspaceType = "canvas",
|
workspaceType = "canvas",
|
||||||
workspaceLabel = "画布",
|
workspaceLabel = "画布",
|
||||||
createUrl = "/canvas?new=1",
|
createUrl = "/canvas?new=1",
|
||||||
@ -88,6 +90,10 @@ export function CanvasFileListPanel({
|
|||||||
|
|
||||||
// 创建新画布
|
// 创建新画布
|
||||||
const handleCreateNew = async () => {
|
const handleCreateNew = async () => {
|
||||||
|
if (onNavigate) {
|
||||||
|
onNavigate(createUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
router.push(createUrl);
|
router.push(createUrl);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -100,6 +106,10 @@ export function CanvasFileListPanel({
|
|||||||
}
|
}
|
||||||
const targetUrl = buildProjectUrl(id);
|
const targetUrl = buildProjectUrl(id);
|
||||||
onClose(); // 关闭文件列表面板
|
onClose(); // 关闭文件列表面板
|
||||||
|
if (onNavigate) {
|
||||||
|
onNavigate(targetUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 强制整页跳转,避免仅更新 URL 不刷新
|
// 强制整页跳转,避免仅更新 URL 不刷新
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
window.location.assign(targetUrl);
|
window.location.assign(targetUrl);
|
||||||
|
|||||||
@ -28,6 +28,7 @@ export function CanvasImageDownloadProgressDialog({
|
|||||||
: null;
|
: null;
|
||||||
const loadedLabel = formatBytes(progress.loadedBytes);
|
const loadedLabel = formatBytes(progress.loadedBytes);
|
||||||
const totalLabel = formatBytes(progress.totalBytes);
|
const totalLabel = formatBytes(progress.totalBytes);
|
||||||
|
const converting = progress.phase === "converting";
|
||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
<div
|
<div
|
||||||
@ -41,12 +42,12 @@ export function CanvasImageDownloadProgressDialog({
|
|||||||
{progress.phase === "saving" ? (
|
{progress.phase === "saving" ? (
|
||||||
<Download className="h-4 w-4" />
|
<Download className="h-4 w-4" />
|
||||||
) : (
|
) : (
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
<Loader2 className="h-4 w-4 motion-safe:animate-spin" />
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-[14px] font-semibold">下载原图</div>
|
<div className="text-[14px] font-semibold">下载原图</div>
|
||||||
<div className="mt-0.5 text-[12px] text-white/58">{progress.message}</div>
|
<div className="mt-0.5 text-[12px] text-white/58" role="status">{progress.message}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{onCancel ? (
|
{onCancel ? (
|
||||||
@ -63,14 +64,19 @@ export function CanvasImageDownloadProgressDialog({
|
|||||||
|
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
<div className="mb-2 flex items-center justify-between text-[12px] text-white/55">
|
<div className="mb-2 flex items-center justify-between text-[12px] text-white/55">
|
||||||
<span>{loadedLabel && totalLabel ? `${loadedLabel} / ${totalLabel}` : "正在处理文件"}</span>
|
<span>{loadedLabel && totalLabel ? `${loadedLabel} / ${totalLabel}` : converting ? "格式转换中" : "正在处理文件"}</span>
|
||||||
<span>{percent !== null ? `${percent}%` : "..."}</span>
|
<span>{percent !== null ? `${percent}%` : "..."}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="relative h-2 overflow-hidden rounded-full bg-white/10">
|
<div
|
||||||
|
className="relative h-2 overflow-hidden rounded-full bg-white/10"
|
||||||
|
role="progressbar"
|
||||||
|
aria-label={converting ? "图片格式转换" : "图片下载"}
|
||||||
|
aria-valuenow={percent ?? undefined}
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
"absolute inset-y-0 left-0 rounded-full bg-gradient-to-r from-cyan-300 via-sky-400 to-emerald-300",
|
"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 animate-[download-indeterminate_1.15s_ease-in-out_infinite]"
|
percent === null && "w-1/3 motion-safe:animate-[download-indeterminate_1.15s_ease-in-out_infinite]"
|
||||||
)}
|
)}
|
||||||
style={percent !== null ? { width: `${percent}%` } : undefined}
|
style={percent !== null ? { width: `${percent}%` } : undefined}
|
||||||
/>
|
/>
|
||||||
|
|||||||
26
components/canvas/CanvasRemoteOperationContext.tsx
Normal file
26
components/canvas/CanvasRemoteOperationContext.tsx
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"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;
|
||||||
|
}
|
||||||
80
components/canvas/CanvasSurfaceHeader.tsx
Normal file
80
components/canvas/CanvasSurfaceHeader.tsx
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ReferenceIcon } from "@/components/lovart/reference-icon";
|
||||||
|
import { CanvasFeedbackDialog } from "./CanvasFeedbackDialog";
|
||||||
|
|
||||||
|
type CanvasSurfaceHeaderProps = {
|
||||||
|
onAddImage: () => void;
|
||||||
|
onHome: () => void;
|
||||||
|
onOpenFiles: () => void;
|
||||||
|
projectTitle: string;
|
||||||
|
projectId: string;
|
||||||
|
rightInset: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
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({
|
||||||
|
onAddImage,
|
||||||
|
onHome,
|
||||||
|
onOpenFiles,
|
||||||
|
projectTitle,
|
||||||
|
projectId,
|
||||||
|
rightInset,
|
||||||
|
}: CanvasSurfaceHeaderProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="absolute left-0 top-0 z-20 flex h-[40px] items-center justify-between border-b border-[#ededed] bg-white px-3 dark:border-white/10 dark:bg-zinc-950"
|
||||||
|
data-canvas-topbar="true"
|
||||||
|
style={{ right: rightInset }}
|
||||||
|
>
|
||||||
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
|
<button
|
||||||
|
aria-label="返回首页"
|
||||||
|
className={iconButtonClass}
|
||||||
|
onClick={onHome}
|
||||||
|
title="返回首页"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="branding" size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label="添加参考素材"
|
||||||
|
className={iconButtonClass}
|
||||||
|
onClick={onAddImage}
|
||||||
|
title="添加参考素材"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="reference" size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
aria-label="查看项目文件"
|
||||||
|
className={iconButtonClass}
|
||||||
|
onClick={onOpenFiles}
|
||||||
|
title="查看项目文件"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="brand" size={16} />
|
||||||
|
</button>
|
||||||
|
<div className="mx-1 h-4 w-px bg-[#ededed] dark:bg-white/10" />
|
||||||
|
<span className="inline-flex h-7 min-w-0 items-center gap-2 rounded-[8px] bg-[#ededed] px-3 text-[13px] text-[#333333] dark:bg-white/10 dark:text-white">
|
||||||
|
<ReferenceIcon name="page" size={16} />
|
||||||
|
<span className="max-w-[160px] truncate">
|
||||||
|
{projectTitle || "页面 1"}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
aria-label="添加到画布"
|
||||||
|
className={iconButtonClass}
|
||||||
|
onClick={onAddImage}
|
||||||
|
title="添加到画布"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="plus" size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<CanvasFeedbackDialog projectId={projectId} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1,6 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { CSSProperties } from "react";
|
import type { CSSProperties } from "react";
|
||||||
|
import {
|
||||||
|
ReferenceIcon,
|
||||||
|
type ReferenceIconName,
|
||||||
|
} from "@/components/lovart/reference-icon";
|
||||||
import type { LucideIcon } from "lucide-react";
|
import type { LucideIcon } from "lucide-react";
|
||||||
import type { CanvasToolbarItemConfig } from "@/lib/canvas-toolbar-config";
|
import type { CanvasToolbarItemConfig } from "@/lib/canvas-toolbar-config";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@ -12,13 +16,12 @@ type CanvasToolbarIconProps = {
|
|||||||
className?: string;
|
className?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
|
referenceName?: ReferenceIconName;
|
||||||
|
referenceSize?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function isSvgIconUrl(url: string) {
|
function isSvgIconUrl(url: string) {
|
||||||
return (
|
return /^data:image\/svg\+xml/i.test(url) || /\.svg(?:[?#].*)?$/i.test(url);
|
||||||
/^data:image\/svg\+xml/i.test(url) ||
|
|
||||||
/\.svg(?:[?#].*)?$/i.test(url)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function stripImageFilterClasses(className?: string) {
|
function stripImageFilterClasses(className?: string) {
|
||||||
@ -42,6 +45,8 @@ export function CanvasToolbarIcon({
|
|||||||
className,
|
className,
|
||||||
style,
|
style,
|
||||||
active = false,
|
active = false,
|
||||||
|
referenceName,
|
||||||
|
referenceSize = 18,
|
||||||
}: CanvasToolbarIconProps) {
|
}: CanvasToolbarIconProps) {
|
||||||
const resolvedIconUrl = String(iconUrl || item?.iconUrl || "").trim();
|
const resolvedIconUrl = String(iconUrl || item?.iconUrl || "").trim();
|
||||||
|
|
||||||
@ -75,7 +80,9 @@ export function CanvasToolbarIcon({
|
|||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
className={cn(
|
className={cn(
|
||||||
"object-contain",
|
"object-contain",
|
||||||
active ? "brightness-0 invert opacity-95" : "brightness-0 opacity-80 dark:invert",
|
active
|
||||||
|
? "brightness-0 invert opacity-95"
|
||||||
|
: "brightness-0 opacity-80 dark:invert",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
src={resolvedIconUrl}
|
src={resolvedIconUrl}
|
||||||
@ -84,5 +91,15 @@ export function CanvasToolbarIcon({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (referenceName) {
|
||||||
|
return (
|
||||||
|
<ReferenceIcon
|
||||||
|
name={referenceName}
|
||||||
|
size={referenceSize}
|
||||||
|
className={className}
|
||||||
|
style={style}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
return <FallbackIcon className={className} style={style} />;
|
return <FallbackIcon className={className} style={style} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,8 +12,13 @@ import { UiScreenNode } from "./nodes/UiScreenNode";
|
|||||||
import { VideoNode } from "./nodes/VideoNode";
|
import { VideoNode } from "./nodes/VideoNode";
|
||||||
import { WorkflowNode } from "./nodes/WorkflowNode";
|
import { WorkflowNode } from "./nodes/WorkflowNode";
|
||||||
import { CanvasToolbarIcon } from "./CanvasToolbarIcon";
|
import { CanvasToolbarIcon } from "./CanvasToolbarIcon";
|
||||||
|
import { CanvasBlankContextMenu } from "./CanvasBlankContextMenu";
|
||||||
|
import { getCanvasFitViewport } from "@/lib/canvas/viewport-fit";
|
||||||
|
import { downloadCanvasSelectionZip } from "@/lib/client/canvas-zip-download";
|
||||||
|
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { imageGenerationService } from "@/services/canvas";
|
import { imageGenerationService } from "@/services/canvas";
|
||||||
import {
|
import {
|
||||||
@ -28,6 +33,7 @@ import {
|
|||||||
LayoutTemplate,
|
LayoutTemplate,
|
||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
Lightbulb,
|
Lightbulb,
|
||||||
|
Loader2,
|
||||||
Minus,
|
Minus,
|
||||||
Pin,
|
Pin,
|
||||||
Plus,
|
Plus,
|
||||||
@ -390,6 +396,11 @@ export function CanvasWorkspace({
|
|||||||
} | null;
|
} | null;
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const contentLayerRef = useRef<HTMLDivElement>(null);
|
const contentLayerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const contextImageInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const contextVideoInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const contextCanvasPointRef = useRef<Position>({ x: 0, y: 0 });
|
||||||
|
const [blankContextPosition, setBlankContextPosition] = useState<Position | null>(null);
|
||||||
|
const [isContextVideoUploading, setIsContextVideoUploading] = useState(false);
|
||||||
const [isPanning, setIsPanning] = useState(false);
|
const [isPanning, setIsPanning] = useState(false);
|
||||||
const [panStart, setPanStart] = useState<Position>({ x: 0, y: 0 });
|
const [panStart, setPanStart] = useState<Position>({ x: 0, y: 0 });
|
||||||
const [isMarqueeSelecting, setIsMarqueeSelecting] = useState(false);
|
const [isMarqueeSelecting, setIsMarqueeSelecting] = useState(false);
|
||||||
@ -727,10 +738,6 @@ export function CanvasWorkspace({
|
|||||||
canvasToolbarConfig,
|
canvasToolbarConfig,
|
||||||
"imageLayoutReplace"
|
"imageLayoutReplace"
|
||||||
);
|
);
|
||||||
// 局部编辑属于主无限画布图片的固定能力,旧配置缺少该 key 时也保持可见。
|
|
||||||
const selectedImageLocalEditEnabled = true;
|
|
||||||
// 排版替换同样是主无限画布图片的核心 AI 入口,旧配置缺少该 key 时也保持可见。
|
|
||||||
const selectedImageLayoutReplaceEnabled = true;
|
|
||||||
|
|
||||||
// Store actions
|
// Store actions
|
||||||
const selectNode = useCanvasStore((state) => state.selectNode);
|
const selectNode = useCanvasStore((state) => state.selectNode);
|
||||||
@ -1106,42 +1113,61 @@ export function CanvasWorkspace({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const fitAllImageNodesIntoViewport = useCallback(() => {
|
const fitAllImageNodesIntoViewport = useCallback(() => {
|
||||||
const imageNodes = nodes.filter(
|
const fit = getCanvasFitViewport(
|
||||||
(node) => node.type === "image" && Boolean((node.data as any)?.src)
|
nodes.filter((node) => node.type === "image" && Boolean((node.data as any)?.src)),
|
||||||
|
containerSize, occlusionRight
|
||||||
);
|
);
|
||||||
if (imageNodes.length === 0) return;
|
if (fit) setViewport(fit);
|
||||||
if (containerSize.width <= 0 || containerSize.height <= 0) return;
|
}, [containerSize, nodes, occlusionRight, setViewport]);
|
||||||
|
|
||||||
const padding = 80;
|
const fitAllCanvasNodesIntoViewport = useCallback(() => {
|
||||||
const minX = Math.min(...imageNodes.map((node) => node.position.x));
|
const fit = getCanvasFitViewport(nodes, containerSize, occlusionRight);
|
||||||
const minY = Math.min(...imageNodes.map((node) => node.position.y));
|
if (fit) setViewport(fit);
|
||||||
const maxX = Math.max(
|
}, [containerSize, nodes, occlusionRight, setViewport]);
|
||||||
...imageNodes.map((node) => node.position.x + node.size.width)
|
|
||||||
);
|
|
||||||
const maxY = Math.max(
|
|
||||||
...imageNodes.map((node) => node.position.y + node.size.height)
|
|
||||||
);
|
|
||||||
|
|
||||||
const contentWidth = Math.max(1, maxX - minX + padding * 2);
|
const handleBlankCanvasContextMenu = useCallback((event: React.MouseEvent) => {
|
||||||
const contentHeight = Math.max(1, maxY - minY + padding * 2);
|
if (isWorkflowCanvas || hasBlockingDialogOpen() || canvasImageSelectionSession) return;
|
||||||
|
if (!(event.target instanceof Element) || event.target.closest(
|
||||||
|
'[data-canvas-node-id], [data-canvas-overlay], [data-canvas-no-drag="true"], button, input, textarea, select, a, [contenteditable="true"]'
|
||||||
|
)) return;
|
||||||
|
const rect = containerRef.current?.getBoundingClientRect();
|
||||||
|
if (!rect) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
contextCanvasPointRef.current = {
|
||||||
|
x: (event.clientX - rect.left - viewportRef.current.x) / viewportRef.current.zoom,
|
||||||
|
y: (event.clientY - rect.top - viewportRef.current.y) / viewportRef.current.zoom,
|
||||||
|
};
|
||||||
|
setBlankContextPosition({ x: event.clientX, y: event.clientY });
|
||||||
|
setAgentSlotContextMenu(null);
|
||||||
|
}, [canvasImageSelectionSession, hasBlockingDialogOpen, isWorkflowCanvas]);
|
||||||
|
|
||||||
const visibleWidth = Math.max(240, containerSize.width - Math.max(0, occlusionRight));
|
const zoomCanvasFromContextMenu = useCallback((factor: number) => {
|
||||||
const fitZoomX = visibleWidth / contentWidth;
|
const current = useCanvasStore.getState().viewport;
|
||||||
const fitZoomY = containerSize.height / contentHeight;
|
const zoom = Math.max(0.1, Math.min(4, current.zoom * factor));
|
||||||
const targetZoom = Math.max(0.05, Math.min(4, Math.min(fitZoomX, fitZoomY)));
|
const centerX = Math.max(1, containerSize.width - occlusionRight) / 2;
|
||||||
|
const centerY = containerSize.height / 2;
|
||||||
|
const ratio = zoom / current.zoom;
|
||||||
|
setViewport({ x: centerX - (centerX - current.x) * ratio, y: centerY - (centerY - current.y) * ratio, zoom });
|
||||||
|
}, [containerSize, occlusionRight, setViewport]);
|
||||||
|
|
||||||
const centerX = (minX + maxX) / 2;
|
React.useEffect(() => {
|
||||||
const centerY = (minY + maxY) / 2;
|
if (isWorkflowCanvas) return;
|
||||||
const visibleCenterX = visibleWidth / 2;
|
const handleFitShortcut = (event: KeyboardEvent) => {
|
||||||
const nextViewportX = visibleCenterX - centerX * targetZoom;
|
if (!event.shiftKey || event.metaKey || event.ctrlKey || event.altKey || event.code !== "Digit1") return;
|
||||||
const nextViewportY = containerSize.height / 2 - centerY * targetZoom;
|
if (hasBlockingDialogOpen() || (event.target instanceof Element && event.target.closest(
|
||||||
|
'input, textarea, [contenteditable="true"], [role="textbox"]'
|
||||||
setViewport({
|
))) return;
|
||||||
x: nextViewportX,
|
const active = document.activeElement;
|
||||||
y: nextViewportY,
|
if (active && active !== document.body && !containerRef.current?.contains(active)
|
||||||
zoom: targetZoom,
|
&& !active.closest('[data-canvas-floating-toolbar], [data-canvas-blank-menu="true"]')) return;
|
||||||
});
|
event.preventDefault();
|
||||||
}, [containerSize.height, containerSize.width, nodes, occlusionRight, setViewport]);
|
fitAllCanvasNodesIntoViewport();
|
||||||
|
setBlankContextPosition(null);
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", handleFitShortcut);
|
||||||
|
return () => window.removeEventListener("keydown", handleFitShortcut);
|
||||||
|
}, [fitAllCanvasNodesIntoViewport, hasBlockingDialogOpen, isWorkflowCanvas]);
|
||||||
|
|
||||||
const getNodeInputAnchor = useCallback(
|
const getNodeInputAnchor = useCallback(
|
||||||
(node: CanvasNode): Position => ({
|
(node: CanvasNode): Position => ({
|
||||||
@ -1258,6 +1284,7 @@ export function CanvasWorkspace({
|
|||||||
if (canvasImageSelectionSession) return;
|
if (canvasImageSelectionSession) return;
|
||||||
if (hasBlockingDialogOpen()) return;
|
if (hasBlockingDialogOpen()) return;
|
||||||
setAgentSlotContextMenu(null);
|
setAgentSlotContextMenu(null);
|
||||||
|
setBlankContextPosition(null);
|
||||||
if (!isEventFromCanvasContainer(e.target)) return;
|
if (!isEventFromCanvasContainer(e.target)) return;
|
||||||
if (suppressCanvasClickRef.current) {
|
if (suppressCanvasClickRef.current) {
|
||||||
suppressCanvasClickRef.current = false;
|
suppressCanvasClickRef.current = false;
|
||||||
@ -1294,7 +1321,7 @@ export function CanvasWorkspace({
|
|||||||
!isPointOnNodeElement(e.target);
|
!isPointOnNodeElement(e.target);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
tool === 'pan' ||
|
(tool === 'pan' && e.button === 0) ||
|
||||||
e.button === 1 ||
|
e.button === 1 ||
|
||||||
(e.button === 0 && e.altKey) ||
|
(e.button === 0 && e.altKey) ||
|
||||||
shouldPanBlankWorkflowCanvas
|
shouldPanBlankWorkflowCanvas
|
||||||
@ -1657,6 +1684,105 @@ export function CanvasWorkspace({
|
|||||||
}
|
}
|
||||||
}, [addNode, clearLatestGeneratedImageHighlights, getImageDimensionsFromFile, updateNode, viewport.x, viewport.y, viewport.zoom]);
|
}, [addNode, clearLatestGeneratedImageHighlights, getImageDimensionsFromFile, updateNode, viewport.x, viewport.y, viewport.zoom]);
|
||||||
|
|
||||||
|
const getContextUploadClientPoint = useCallback(() => {
|
||||||
|
const rect = containerRef.current?.getBoundingClientRect();
|
||||||
|
const current = viewportRef.current;
|
||||||
|
return {
|
||||||
|
x: (rect?.left ?? 0) + current.x + contextCanvasPointRef.current.x * current.zoom,
|
||||||
|
y: (rect?.top ?? 0) + current.y + contextCanvasPointRef.current.y * current.zoom,
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const pasteCanvasText = useCallback((text: string, point: Position) => {
|
||||||
|
if (!text.trim()) return;
|
||||||
|
addNode({
|
||||||
|
type: "text", position: point, size: { width: 320, height: 160 },
|
||||||
|
data: { content: text, color: "#111827" }, connections: [],
|
||||||
|
});
|
||||||
|
}, [addNode]);
|
||||||
|
|
||||||
|
const uploadContextVideos = useCallback(async (files: File[]) => {
|
||||||
|
if (!files.length || isContextVideoUploading) return;
|
||||||
|
const position = { ...contextCanvasPointRef.current };
|
||||||
|
setIsContextVideoUploading(true);
|
||||||
|
try {
|
||||||
|
for (const [index, file] of files.entries()) {
|
||||||
|
if (!["video/mp4", "video/quicktime", "video/webm"].includes(file.type)) {
|
||||||
|
toast.error("请选择 MP4、MOV 或 WebM 视频");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (file.size > 50 * 1024 * 1024) {
|
||||||
|
toast.error("视频文件不能超过 50MB");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const loadingToast = toast.loading(`正在上传 ${file.name}`);
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
formData.append("purpose", "canvas-video-process");
|
||||||
|
const response = await fetchUploadWithRetry(formData);
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || !result.url) throw new Error(result.error || "视频上传失败");
|
||||||
|
addNode({
|
||||||
|
type: "video", position: { x: position.x + index * 24, y: position.y + index * 24 },
|
||||||
|
size: { width: 320, height: 180 },
|
||||||
|
data: { src: result.url, assetId: result.assetId, status: "completed", prompt: file.name,
|
||||||
|
metadata: { source: "local-upload", fileName: file.name, contentType: file.type } },
|
||||||
|
connections: [],
|
||||||
|
});
|
||||||
|
toast.success("视频已添加到画布");
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : "视频上传失败,请重试");
|
||||||
|
} finally {
|
||||||
|
toast.dismiss(loadingToast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setIsContextVideoUploading(false);
|
||||||
|
}
|
||||||
|
}, [addNode, isContextVideoUploading]);
|
||||||
|
|
||||||
|
const pasteFromContextMenu = useCallback(async () => {
|
||||||
|
const pastePoint = { ...contextCanvasPointRef.current };
|
||||||
|
const clientPoint = getContextUploadClientPoint();
|
||||||
|
try {
|
||||||
|
const files: File[] = [];
|
||||||
|
let text = "";
|
||||||
|
if (typeof navigator.clipboard?.read === "function") {
|
||||||
|
const items = await navigator.clipboard.read();
|
||||||
|
for (const [index, item] of items.entries()) {
|
||||||
|
const imageType = item.types.find((type) => type.startsWith("image/"));
|
||||||
|
if (imageType) {
|
||||||
|
const blob = await item.getType(imageType);
|
||||||
|
files.push(new File([blob], `粘贴图片-${Date.now()}-${index}.${imageType.split("/")[1]}`, { type: imageType }));
|
||||||
|
} else if (item.types.includes("text/plain")) {
|
||||||
|
text += await (await item.getType("text/plain")).text();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (typeof navigator.clipboard?.readText === "function") {
|
||||||
|
text = await navigator.clipboard.readText();
|
||||||
|
} else {
|
||||||
|
throw new Error("Clipboard unavailable");
|
||||||
|
}
|
||||||
|
if (files.length) {
|
||||||
|
await processDroppedFiles(files, clientPoint.x, clientPoint.y);
|
||||||
|
} else if (text.trim()) {
|
||||||
|
pasteCanvasText(text, pastePoint);
|
||||||
|
} else {
|
||||||
|
toast.info("剪贴板中没有可粘贴的图片或文字");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.info(`无法读取剪贴板,请使用 ${isMacPlatform ? "⌘V" : "Ctrl+V"} 粘贴`);
|
||||||
|
}
|
||||||
|
}, [getContextUploadClientPoint, isMacPlatform, pasteCanvasText, processDroppedFiles]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!blankContextPosition) return;
|
||||||
|
const close = () => setBlankContextPosition(null);
|
||||||
|
window.addEventListener("resize", close);
|
||||||
|
return () => window.removeEventListener("resize", close);
|
||||||
|
}, [blankContextPosition]);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const handleWindowDrop = async (e: DragEvent) => {
|
const handleWindowDrop = async (e: DragEvent) => {
|
||||||
if (!isFileDrag(e.dataTransfer)) return;
|
if (!isFileDrag(e.dataTransfer)) return;
|
||||||
@ -1719,24 +1845,44 @@ export function CanvasWorkspace({
|
|||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const handlePaste = async (e: ClipboardEvent) => {
|
const handlePaste = async (e: ClipboardEvent) => {
|
||||||
if (hasBlockingDialogOpen() || isEditablePasteTarget(e.target)) return;
|
const activeElement = document.activeElement;
|
||||||
|
const fromContextMenu = Boolean(activeElement?.closest('[data-canvas-blank-menu="true"]'));
|
||||||
|
if (hasBlockingDialogOpen() || (!fromContextMenu && isEditablePasteTarget(e.target))) return;
|
||||||
|
|
||||||
const container = containerRef.current;
|
const container = containerRef.current;
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
const activeElement = document.activeElement;
|
|
||||||
if (
|
if (
|
||||||
activeElement instanceof HTMLElement &&
|
activeElement instanceof HTMLElement &&
|
||||||
activeElement !== document.body &&
|
activeElement !== document.body &&
|
||||||
!container.contains(activeElement)
|
!container.contains(activeElement) && !fromContextMenu
|
||||||
) {
|
) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const files = extractImageFilesFromDataTransfer(e.clipboardData);
|
const files = extractImageFilesFromDataTransfer(e.clipboardData);
|
||||||
if (files.length === 0) return;
|
const text = e.clipboardData?.getData("text/plain") || "";
|
||||||
|
if (files.length === 0 && (isWorkflowCanvas || !text.trim())) return;
|
||||||
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const rect = container.getBoundingClientRect();
|
const rect = container.getBoundingClientRect();
|
||||||
|
if (fromContextMenu) {
|
||||||
|
setBlankContextPosition(null);
|
||||||
|
if (files.length) {
|
||||||
|
const point = getContextUploadClientPoint();
|
||||||
|
await processDroppedFiles(files, point.x, point.y);
|
||||||
|
} else {
|
||||||
|
pasteCanvasText(text, { ...contextCanvasPointRef.current });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (files.length === 0) {
|
||||||
|
const current = viewportRef.current;
|
||||||
|
pasteCanvasText(text, {
|
||||||
|
x: (rect.width / 2 - current.x) / current.zoom,
|
||||||
|
y: (rect.height / 2 - current.y) / current.zoom,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
await processDroppedFiles(
|
await processDroppedFiles(
|
||||||
files,
|
files,
|
||||||
rect.left + rect.width / 2,
|
rect.left + rect.width / 2,
|
||||||
@ -1746,7 +1892,7 @@ export function CanvasWorkspace({
|
|||||||
|
|
||||||
window.addEventListener("paste", handlePaste);
|
window.addEventListener("paste", handlePaste);
|
||||||
return () => window.removeEventListener("paste", handlePaste);
|
return () => window.removeEventListener("paste", handlePaste);
|
||||||
}, [hasBlockingDialogOpen, processDroppedFiles]);
|
}, [getContextUploadClientPoint, hasBlockingDialogOpen, isWorkflowCanvas, pasteCanvasText, processDroppedFiles]);
|
||||||
|
|
||||||
const handleDownloadSelectedImages = useCallback(async () => {
|
const handleDownloadSelectedImages = useCallback(async () => {
|
||||||
if (selectedImageNodes.length === 0) {
|
if (selectedImageNodes.length === 0) {
|
||||||
@ -1769,10 +1915,10 @@ export function CanvasWorkspace({
|
|||||||
const rawImageUrl = String(nodeData?.src || "").trim();
|
const rawImageUrl = String(nodeData?.src || "").trim();
|
||||||
if (!rawImageUrl) return null;
|
if (!rawImageUrl) return null;
|
||||||
let imageUrl = inferOriginalImageUrl(rawImageUrl) || rawImageUrl;
|
let imageUrl = inferOriginalImageUrl(rawImageUrl) || rawImageUrl;
|
||||||
if (browserOrigin && rawImageUrl.startsWith("/")) {
|
if (browserOrigin && rawImageUrl.startsWith("//")) {
|
||||||
imageUrl = `${browserOrigin}${rawImageUrl}`;
|
|
||||||
} else if (browserOrigin && rawImageUrl.startsWith("//")) {
|
|
||||||
imageUrl = `${window.location.protocol}${rawImageUrl}`;
|
imageUrl = `${window.location.protocol}${rawImageUrl}`;
|
||||||
|
} else if (browserOrigin && rawImageUrl.startsWith("/")) {
|
||||||
|
imageUrl = `${browserOrigin}${rawImageUrl}`;
|
||||||
}
|
}
|
||||||
const name =
|
const name =
|
||||||
String(nodeData?.title || "").trim() ||
|
String(nodeData?.title || "").trim() ||
|
||||||
@ -1788,32 +1934,19 @@ export function CanvasWorkspace({
|
|||||||
}
|
}
|
||||||
|
|
||||||
setIsDownloadSubmitting(true);
|
setIsDownloadSubmitting(true);
|
||||||
|
const toastId = toast.loading("正在准备所选图片...");
|
||||||
try {
|
try {
|
||||||
const form = document.createElement("form");
|
const result = await downloadCanvasSelectionZip({ folderName, files,
|
||||||
form.method = "POST";
|
scope: "canvas-selection",
|
||||||
form.action = "/api/canvas/download-zip";
|
selectionKey: `${useCanvasStore.getState().projectId}:${selectedImageNodes.map(node => node.id).sort().join(",")}`,
|
||||||
form.style.display = "none";
|
onProgress: task => toast.loading(`${task.stage}(${task.progress}%)`, { id: toastId }),
|
||||||
|
|
||||||
const payloadInput = document.createElement("input");
|
|
||||||
payloadInput.type = "hidden";
|
|
||||||
payloadInput.name = "payload";
|
|
||||||
payloadInput.value = JSON.stringify({
|
|
||||||
folderName,
|
|
||||||
files,
|
|
||||||
});
|
});
|
||||||
form.appendChild(payloadInput);
|
if (result.failedCount) toast.warning(`已开始下载 ${result.successCount} 张图片,${result.failedCount} 张未能读取;ZIP 内附失败清单`, { id: toastId, duration: 10000 });
|
||||||
|
else toast.success(`ZIP 已准备完成,正在下载 ${result.successCount} 张图片`, { id: toastId });
|
||||||
document.body.appendChild(form);
|
} catch (error) {
|
||||||
form.submit();
|
toast.error(error instanceof Error ? error.message : "打包下载失败,请稍后重试", { id: toastId });
|
||||||
form.remove();
|
|
||||||
|
|
||||||
toast.success("已开始打包下载,请留意浏览器下载栏");
|
|
||||||
} catch (_error) {
|
|
||||||
toast.error("下载失败,请稍后重试");
|
|
||||||
} finally {
|
} finally {
|
||||||
window.setTimeout(() => {
|
setIsDownloadSubmitting(false);
|
||||||
setIsDownloadSubmitting(false);
|
|
||||||
}, 800);
|
|
||||||
}
|
}
|
||||||
}, [isDownloadSubmitting, selectedImageNodes]);
|
}, [isDownloadSubmitting, selectedImageNodes]);
|
||||||
|
|
||||||
@ -2269,12 +2402,47 @@ export function CanvasWorkspace({
|
|||||||
onMouseUp={handleMouseUp}
|
onMouseUp={handleMouseUp}
|
||||||
onMouseLeave={handleMouseUp}
|
onMouseLeave={handleMouseUp}
|
||||||
onDoubleClick={handleBlankCanvasDoubleClick}
|
onDoubleClick={handleBlankCanvasDoubleClick}
|
||||||
|
onContextMenu={handleBlankCanvasContextMenu}
|
||||||
onWheel={handleWheel}
|
onWheel={handleWheel}
|
||||||
onDragEnter={handleDragEnter}
|
onDragEnter={handleDragEnter}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
>
|
>
|
||||||
|
{!isWorkflowCanvas && (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
ref={contextImageInputRef} type="file" accept="image/*" multiple className="hidden"
|
||||||
|
aria-label="从右键菜单上传图片"
|
||||||
|
onChange={(event) => {
|
||||||
|
const files = Array.from(event.target.files || []);
|
||||||
|
event.target.value = "";
|
||||||
|
const point = getContextUploadClientPoint();
|
||||||
|
void processDroppedFiles(files, point.x, point.y);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
ref={contextVideoInputRef} type="file" accept="video/mp4,video/quicktime,video/webm,.mp4,.mov,.webm" multiple className="hidden"
|
||||||
|
aria-label="从右键菜单上传视频"
|
||||||
|
onChange={(event) => {
|
||||||
|
const files = Array.from(event.target.files || []);
|
||||||
|
event.target.value = "";
|
||||||
|
void uploadContextVideos(files);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<CanvasBlankContextMenu
|
||||||
|
position={blankContextPosition} isMac={isMacPlatform} videoUploading={isContextVideoUploading}
|
||||||
|
onClose={() => setBlankContextPosition(null)}
|
||||||
|
onUploadImage={() => contextImageInputRef.current?.click()}
|
||||||
|
onUploadVideo={() => contextVideoInputRef.current?.click()}
|
||||||
|
onPaste={() => { void pasteFromContextMenu(); }}
|
||||||
|
onZoomIn={() => zoomCanvasFromContextMenu(1.2)}
|
||||||
|
onZoomOut={() => zoomCanvasFromContextMenu(1 / 1.2)}
|
||||||
|
onFitAll={fitAllCanvasNodesIntoViewport}
|
||||||
|
onResetZoom={() => setViewport({ x: 0, y: 0, zoom: 1 })}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
{isWorkflowCanvas ? (
|
{isWorkflowCanvas ? (
|
||||||
<>
|
<>
|
||||||
<div className="pointer-events-none absolute inset-0 pattern-grid-lg text-white opacity-[0.065]" />
|
<div className="pointer-events-none absolute inset-0 pattern-grid-lg text-white opacity-[0.065]" />
|
||||||
@ -2566,10 +2734,14 @@ export function CanvasWorkspace({
|
|||||||
)}
|
)}
|
||||||
{!canvasImageSelectionSession && selectedImageNodes.length > 0 && (
|
{!canvasImageSelectionSession && selectedImageNodes.length > 0 && (
|
||||||
<div
|
<div
|
||||||
className="absolute bottom-16 left-4 z-30 flex items-center gap-2"
|
className={cn(
|
||||||
|
"absolute left-4 z-30 flex items-center gap-2",
|
||||||
|
isWorkflowCanvas ? "bottom-16" : "bottom-[20px]"
|
||||||
|
)}
|
||||||
data-canvas-overlay
|
data-canvas-overlay
|
||||||
|
data-canvas-selection-actions="true"
|
||||||
>
|
>
|
||||||
{selectedImageLocalEditEnabled && selectedImageNodes.length === 1 ? (
|
{isWorkflowCanvas && selectedImageNodes.length === 1 ? (
|
||||||
<Button
|
<Button
|
||||||
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
||||||
size="sm"
|
size="sm"
|
||||||
@ -2591,7 +2763,7 @@ export function CanvasWorkspace({
|
|||||||
{selectedImageLocalEditItem.label}
|
{selectedImageLocalEditItem.label}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{selectedImageLayoutReplaceEnabled &&
|
{isWorkflowCanvas &&
|
||||||
selectedImageNodes.length >= 1 ? (
|
selectedImageNodes.length >= 1 ? (
|
||||||
<Button
|
<Button
|
||||||
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
||||||
@ -2620,27 +2792,48 @@ export function CanvasWorkspace({
|
|||||||
{selectedImageLayoutReplaceItem.label}
|
{selectedImageLayoutReplaceItem.label}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<Button
|
<Tooltip>
|
||||||
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
<TooltipTrigger asChild>
|
||||||
size="sm"
|
<Button
|
||||||
className={cn(
|
variant={isWorkflowCanvas ? "outline" : "secondary"}
|
||||||
"h-8 gap-1.5 px-3 text-xs shadow-sm border border-border/60",
|
size={isWorkflowCanvas ? "sm" : "icon"}
|
||||||
isWorkflowCanvas &&
|
className={cn(
|
||||||
"rounded-full border-[#dbe2ee] bg-white text-[#3b4860] shadow-[0_0_0_1px_rgba(219,226,238,0.26)] hover:bg-[#f7f9ff]"
|
isWorkflowCanvas
|
||||||
)}
|
? "h-8 gap-1.5 rounded-full border border-[#dbe2ee] bg-white px-3 text-xs text-[#3b4860] shadow-[0_0_0_1px_rgba(219,226,238,0.26)] hover:bg-[#f7f9ff]"
|
||||||
onClick={handleDownloadSelectedImages}
|
: "h-[32px] w-[32px] rounded-[8px] border border-[#e9e9e9] bg-white p-0 text-[#333333] shadow-[0_1px_3px_rgba(0,0,0,0.035)] hover:bg-[#f5f5f5] dark:border-white/10 dark:bg-zinc-950 dark:text-white dark:hover:bg-white/10"
|
||||||
disabled={isDownloadSubmitting}
|
)}
|
||||||
title={getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder").label}
|
onClick={handleDownloadSelectedImages}
|
||||||
>
|
disabled={isDownloadSubmitting}
|
||||||
<CanvasToolbarIcon
|
aria-label={
|
||||||
className="h-3.5 w-3.5"
|
isDownloadSubmitting
|
||||||
fallback={Download}
|
? "打包中..."
|
||||||
item={getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder")}
|
: `${getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder").label}(${selectedImageNodes.length})`
|
||||||
/>
|
}
|
||||||
{isDownloadSubmitting
|
>
|
||||||
? "打包中..."
|
{!isWorkflowCanvas && isDownloadSubmitting ? (
|
||||||
: `${getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder").label}(${selectedImageNodes.length})`}
|
<Loader2 className="h-5 w-5 animate-spin" />
|
||||||
</Button>
|
) : (
|
||||||
|
<CanvasToolbarIcon
|
||||||
|
className={isWorkflowCanvas ? "h-3.5 w-3.5" : "h-5 w-5"}
|
||||||
|
fallback={Download}
|
||||||
|
referenceName={isWorkflowCanvas ? undefined : "image-download"}
|
||||||
|
referenceSize={20}
|
||||||
|
item={getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{isWorkflowCanvas
|
||||||
|
? isDownloadSubmitting
|
||||||
|
? "打包中..."
|
||||||
|
: `${getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder").label}(${selectedImageNodes.length})`
|
||||||
|
: null}
|
||||||
|
</Button>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="top">
|
||||||
|
{isDownloadSubmitting
|
||||||
|
? "打包中..."
|
||||||
|
: `${getCanvasToolbarItem(canvasToolbarConfig, "downloadFolder").label}(${selectedImageNodes.length})`}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { fetchUploadWithRetry } from "@/lib/client/upload-with-retry";
|
||||||
import { useCanvasGroupRuns } from "@/hooks/use-canvas-group-runs";
|
import { useCanvasGroupRuns } from "@/hooks/use-canvas-group-runs";
|
||||||
import { hasRecoverableCanvasTask } from "@/lib/video-canvas/task-recovery";
|
import { hasRecoverableCanvasTask } from "@/lib/video-canvas/task-recovery";
|
||||||
|
import { restoreTextResourceContent } from "@/lib/video-canvas/text-resource";
|
||||||
import { GroupStoryboardPreview } from "./GroupStoryboardPreview";
|
import { GroupStoryboardPreview } from "./GroupStoryboardPreview";
|
||||||
import { CanvasGroupToolbar } from "./CanvasGroupToolbar";
|
import { CanvasGroupToolbar } from "./CanvasGroupToolbar";
|
||||||
import { isCanvasGroup, groupMembers, makeCanvasGroup, ungroupCanvasNodes, moveCanvasSelection, layoutCanvasGroup, migrateLegacyGroups, exportCanvasGroup, instantiateCanvasGroup, groupBounds, assignGroupMembers } from "@/lib/video-canvas/groups";
|
import { isCanvasGroup, groupMembers, makeCanvasGroup, ungroupCanvasNodes, moveCanvasSelection, layoutCanvasGroup, migrateLegacyGroups, exportCanvasGroup, instantiateCanvasGroup, groupBounds, assignGroupMembers } from "@/lib/video-canvas/groups";
|
||||||
@ -12,6 +14,12 @@ import { SmartEditDialog } from "./smart-edit/SmartEditDialog";
|
|||||||
import { SmartEditNodeCard, SmartEditNodeComposer, type SmartEditMode } from "./smart-edit/SmartEditNode";
|
import { SmartEditNodeCard, SmartEditNodeComposer, type SmartEditMode } from "./smart-edit/SmartEditNode";
|
||||||
import { smartEditRequestSchema, type EditPlan } from "@/lib/video-canvas/smart-edit/contract";
|
import { smartEditRequestSchema, type EditPlan } from "@/lib/video-canvas/smart-edit/contract";
|
||||||
import { AudioGenerationComposer } from "./AudioGenerationComposer";
|
import { AudioGenerationComposer } from "./AudioGenerationComposer";
|
||||||
|
import { TVstarPanel, type TVstarGenerationModel, type TVstarGenerationSelection, type TVstarModel, type TVstarNodeContext, type TVstarReference, type TVstarShot } from "./tvstar/TVstarPanel";
|
||||||
|
import { resolveTVstarGenerationReferences } from "./tvstar/generation-references";
|
||||||
|
import { tvstarTiming } from "@/lib/video-canvas/tvstar-timing";
|
||||||
|
import { tvstarOutputRequirements } from "@/lib/video-canvas/tvstar-output";
|
||||||
|
import { CharacterStudioPanel, type StudioCharacter, type StudioView } from "./tvstar/CharacterStudioPanel";
|
||||||
|
import { tvstarShotComposition } from "@/lib/video-canvas/tvstar-shot-input";
|
||||||
import { VideoCanvasConflictNotice } from "./VideoCanvasConflictNotice";
|
import { VideoCanvasConflictNotice } from "./VideoCanvasConflictNotice";
|
||||||
import { normalizeVideoAnalysisRows } from "@/lib/video-canvas/video-story";
|
import { normalizeVideoAnalysisRows } from "@/lib/video-canvas/video-story";
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
@ -25,7 +33,7 @@ const DirectorStudioDialog = dynamic(
|
|||||||
);
|
);
|
||||||
import { directorMotionPrompt, resizeDirectorMotion } from "@/lib/video-canvas/director-motion";
|
import { directorMotionPrompt, resizeDirectorMotion } from "@/lib/video-canvas/director-motion";
|
||||||
import type { DirectorSnapshot } from "@/lib/video-canvas/director-scene";
|
import type { DirectorSnapshot } from "@/lib/video-canvas/director-scene";
|
||||||
import { chooseStoryVideoSettings, filterCanvasModels, getCanvasVideoModes, getCanvasVideoParameters, type CanvasModelKind } from "@/lib/video-canvas/model-matching";
|
import { chooseStoryVideoSettings, filterCanvasModels, getCanvasVideoModes, getCanvasVideoParameters, isCanvasLanguageModel, isCanvasVisionModel, type CanvasModelKind } from "@/lib/video-canvas/model-matching";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ScanText,
|
ScanText,
|
||||||
@ -67,6 +75,7 @@ import {
|
|||||||
Scissors,
|
Scissors,
|
||||||
Settings2,
|
Settings2,
|
||||||
SlidersHorizontal,
|
SlidersHorizontal,
|
||||||
|
Smile,
|
||||||
Sparkles,
|
Sparkles,
|
||||||
Star,
|
Star,
|
||||||
Trash2,
|
Trash2,
|
||||||
@ -97,6 +106,11 @@ import {
|
|||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
import { ZCODE_VIDEO_CANVAS_AUTHORIZED } from "@/lib/ai/canvas-agent-runtime/authorization";
|
||||||
|
import { CanvasAgentUiListener } from "./chat-panel/canvas-agent-ui-listener";
|
||||||
|
import type { CanvasAgentUiCommand } from "@/lib/ai/canvas-agent-runtime/ui-command";
|
||||||
|
import { VideoCanvasAgentPanel } from "./chat-panel/video-canvas-agent-panel";
|
||||||
|
import { mergeVideoAgentResults } from "@/lib/ai/canvas-agent-runtime/video-protocol";
|
||||||
import useSWR from "swr";
|
import useSWR from "swr";
|
||||||
import {
|
import {
|
||||||
getGenerationCreditCostFromImageGenConfig,
|
getGenerationCreditCostFromImageGenConfig,
|
||||||
@ -153,6 +167,8 @@ type ActivePanel =
|
|||||||
| "historyPicker"
|
| "historyPicker"
|
||||||
| "help"
|
| "help"
|
||||||
| "roleLibrary"
|
| "roleLibrary"
|
||||||
|
| "characterStudio"
|
||||||
|
| "tvstar"
|
||||||
| "videoRoleLibrary"
|
| "videoRoleLibrary"
|
||||||
| "shortcuts"
|
| "shortcuts"
|
||||||
| "styleLibrary"
|
| "styleLibrary"
|
||||||
@ -807,28 +823,28 @@ const STARTER_CARDS = [
|
|||||||
title: "故事脚本生成",
|
title: "故事脚本生成",
|
||||||
subtitle: "脚本到分镜",
|
subtitle: "脚本到分镜",
|
||||||
coverUrl:
|
coverUrl:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-story-script-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-story-script-cover.png",
|
||||||
steps: ["故事脚本", "多模态文本模型Pro", "可灵 3.0", "预览"],
|
steps: ["故事脚本", "多模态文本模型Pro", "可灵 3.0", "预览"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "角色三视图",
|
title: "角色三视图",
|
||||||
subtitle: "角色资产沉淀",
|
subtitle: "角色资产沉淀",
|
||||||
coverUrl:
|
coverUrl:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-character-three-view-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-character-three-view-cover.png",
|
||||||
steps: ["角色描述", "角色三视图", "全能图片模型V2", "保存"],
|
steps: ["角色描述", "角色三视图", "全能图片模型V2", "保存"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "全能参考生视频",
|
title: "全能参考生视频",
|
||||||
subtitle: "参考图到成片",
|
subtitle: "参考图到成片",
|
||||||
coverUrl:
|
coverUrl:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-first-frame-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-first-frame-video-cover.png",
|
||||||
steps: ["上传图片", "首帧图", "可灵 3.0", "预览"],
|
steps: ["上传图片", "首帧图", "可灵 3.0", "预览"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "音频生视频",
|
title: "音频生视频",
|
||||||
subtitle: "音频驱动画面",
|
subtitle: "音频驱动画面",
|
||||||
coverUrl:
|
coverUrl:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-audio-to-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-audio-to-video-cover.png",
|
||||||
icon: "music",
|
icon: "music",
|
||||||
steps: ["上传音频", "音频主视频", "Wan 2.6", "预览"],
|
steps: ["上传音频", "音频主视频", "Wan 2.6", "预览"],
|
||||||
},
|
},
|
||||||
@ -851,7 +867,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "预设",
|
badge: "预设",
|
||||||
category: "周星驰经典名场面",
|
category: "周星驰经典名场面",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-first-frame-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-first-frame-video-cover.png",
|
||||||
description: "左弧滑行,镜头从人物左侧弧线推进,带轻微喜剧节奏和夸张表情停顿。",
|
description: "左弧滑行,镜头从人物左侧弧线推进,带轻微喜剧节奏和夸张表情停顿。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "left-arc-slide",
|
id: "left-arc-slide",
|
||||||
@ -866,7 +882,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "商用",
|
badge: "商用",
|
||||||
category: "电商展示",
|
category: "电商展示",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-character-three-view-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-character-three-view-cover.png",
|
||||||
description: "电商手机弹出效果,产品从画面中心弹出并旋转定格,适合主图视频开场。",
|
description: "电商手机弹出效果,产品从画面中心弹出并旋转定格,适合主图视频开场。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "phone-pop-product",
|
id: "phone-pop-product",
|
||||||
@ -881,7 +897,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "商用",
|
badge: "商用",
|
||||||
category: "电商展示",
|
category: "电商展示",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-story-script-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-story-script-cover.png",
|
||||||
description: "咖啡杯出场,杯身从桌面滑入,蒸汽和柔光形成温暖的品牌氛围。",
|
description: "咖啡杯出场,杯身从桌面滑入,蒸汽和柔光形成温暖的品牌氛围。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "coffee-cup-entry",
|
id: "coffee-cup-entry",
|
||||||
@ -896,7 +912,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "热门",
|
badge: "热门",
|
||||||
category: "镜头运动",
|
category: "镜头运动",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-audio-to-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-audio-to-video-cover.png",
|
||||||
description: "360旋转展示,围绕主体做一圈稳定环绕,适合产品、人物和空间展示。",
|
description: "360旋转展示,围绕主体做一圈稳定环绕,适合产品、人物和空间展示。",
|
||||||
duration: "6s",
|
duration: "6s",
|
||||||
id: "orbit-360-showcase",
|
id: "orbit-360-showcase",
|
||||||
@ -910,7 +926,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
author: "工业镜头",
|
author: "工业镜头",
|
||||||
category: "镜头运动",
|
category: "镜头运动",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/character-image.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/character-image.png",
|
||||||
description: "机械臂视角,以第一视角穿过机械臂与产品线,增强科技感和空间纵深。",
|
description: "机械臂视角,以第一视角穿过机械臂与产品线,增强科技感和空间纵深。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "robot-arm-pov",
|
id: "robot-arm-pov",
|
||||||
@ -925,7 +941,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "NEW",
|
badge: "NEW",
|
||||||
category: "人物动画",
|
category: "人物动画",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/character-three-view.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/character-three-view.png",
|
||||||
description: "Live 2D,让单张角色图产生眨眼、微笑和轻微身体摆动,适合口播开场。",
|
description: "Live 2D,让单张角色图产生眨眼、微笑和轻微身体摆动,适合口播开场。",
|
||||||
duration: "4s",
|
duration: "4s",
|
||||||
id: "live-2d-character",
|
id: "live-2d-character",
|
||||||
@ -939,7 +955,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
author: "电影运镜",
|
author: "电影运镜",
|
||||||
category: "镜头运动",
|
category: "镜头运动",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-first-frame-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-first-frame-video-cover.png",
|
||||||
description: "瞳孔拉近,镜头快速推向眼部并在反光里展示下一场景,适合悬疑转场。",
|
description: "瞳孔拉近,镜头快速推向眼部并在反光里展示下一场景,适合悬疑转场。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "pupil-zoom",
|
id: "pupil-zoom",
|
||||||
@ -954,7 +970,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "热门",
|
badge: "热门",
|
||||||
category: "人物动画",
|
category: "人物动画",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-story-script-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-story-script-cover.png",
|
||||||
description: "飞鸟解体,主体由细碎羽片散开再重组,适合视觉冲击强的短视频片头。",
|
description: "飞鸟解体,主体由细碎羽片散开再重组,适合视觉冲击强的短视频片头。",
|
||||||
duration: "6s",
|
duration: "6s",
|
||||||
id: "bird-dissolve",
|
id: "bird-dissolve",
|
||||||
@ -969,7 +985,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
badge: "商用",
|
badge: "商用",
|
||||||
category: "电商展示",
|
category: "电商展示",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-character-three-view-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-character-three-view-cover.png",
|
||||||
description: "商品震撼登场,产品带冲击波与局部高光进入画面,适合活动主推款。",
|
description: "商品震撼登场,产品带冲击波与局部高光进入画面,适合活动主推款。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "product-hero-entry",
|
id: "product-hero-entry",
|
||||||
@ -983,7 +999,7 @@ const TOOLBOX_TEMPLATE_PRESETS: ToolboxTemplatePreset[] = [
|
|||||||
author: "旅拍模板",
|
author: "旅拍模板",
|
||||||
category: "镜头运动",
|
category: "镜头运动",
|
||||||
cover:
|
cover:
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-audio-to-video-cover.png",
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-audio-to-video-cover.png",
|
||||||
description: "旅拍转场,前景遮挡切换到新地点,带自然手持感和轻微速度变化。",
|
description: "旅拍转场,前景遮挡切换到新地点,带自然手持感和轻微速度变化。",
|
||||||
duration: "5s",
|
duration: "5s",
|
||||||
id: "travel-whip-transition",
|
id: "travel-whip-transition",
|
||||||
@ -1045,7 +1061,7 @@ const TOOLBAR_ITEMS: Array<{ id: Exclude<ActivePanel, null>; label: string; icon
|
|||||||
{ id: "add", label: "添加节点", icon: Plus },
|
{ id: "add", label: "添加节点", icon: Plus },
|
||||||
{ id: "workflow", label: "工具箱", icon: GitBranch },
|
{ id: "workflow", label: "工具箱", icon: GitBranch },
|
||||||
{ id: "assets", label: "素材库", icon: Layers },
|
{ id: "assets", label: "素材库", icon: Layers },
|
||||||
{ id: "roleLibrary", label: "角色库", icon: UserRound },
|
{ id: "characterStudio", label: "角色造型室", icon: Smile },
|
||||||
{ id: "history", label: "历史记录", icon: Clock3 },
|
{ id: "history", label: "历史记录", icon: Clock3 },
|
||||||
{ id: "shortcuts", label: "快捷键", icon: Keyboard },
|
{ id: "shortcuts", label: "快捷键", icon: Keyboard },
|
||||||
{ id: "tutorial", label: "教程", icon: BookOpen },
|
{ id: "tutorial", label: "教程", icon: BookOpen },
|
||||||
@ -1146,9 +1162,9 @@ const NINE_GRID_CELL_VISUALS: GridCellVisual[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const TARGET_AVATAR =
|
const TARGET_AVATAR =
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/target-avatar.jpg";
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/target-avatar.jpg";
|
||||||
const PUBLISH_MODAL_BG_URL =
|
const PUBLISH_MODAL_BG_URL =
|
||||||
"https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/publish-modal-bg.png";
|
"https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/publish-modal-bg.png";
|
||||||
const STORY_SCRIPT_PROMPT = "根据我上传的剧本生成一个完整的故事脚本";
|
const STORY_SCRIPT_PROMPT = "根据我上传的剧本生成一个完整的故事脚本";
|
||||||
const AUDIO_TO_VIDEO_PROMPT =
|
const AUDIO_TO_VIDEO_PROMPT =
|
||||||
"根据上传的音频生成对应场景画面,镜头语言、节奏、音乐匹配情绪变化,电影级质感。";
|
"根据上传的音频生成对应场景画面,镜头语言、节奏、音乐匹配情绪变化,电影级质感。";
|
||||||
@ -4130,7 +4146,7 @@ function normalizeTextResourceNode(node: CloneNode, fallbackIndex: number): Clon
|
|||||||
draftValues: {
|
draftValues: {
|
||||||
...(node.draftValues || {}),
|
...(node.draftValues || {}),
|
||||||
action: "TEXT_RESOURCE",
|
action: "TEXT_RESOURCE",
|
||||||
content: Array.isArray(node.draftValues?.content) ? node.draftValues?.content : [],
|
content: restoreTextResourceContent(node.draftValues),
|
||||||
nodeType: "text",
|
nodeType: "text",
|
||||||
scriptRole: "resource",
|
scriptRole: "resource",
|
||||||
viewMode: undefined,
|
viewMode: undefined,
|
||||||
@ -4559,6 +4575,8 @@ export function LiblibVideoCanvasReplica({
|
|||||||
);
|
);
|
||||||
const [nodes, setNodes] = useState<CloneNode[]>([]);
|
const [nodes, setNodes] = useState<CloneNode[]>([]);
|
||||||
const activeGenerationSubmissions = useRef(new Set<string>());
|
const activeGenerationSubmissions = useRef(new Set<string>());
|
||||||
|
const [isVideoAgentOpen, setIsVideoAgentOpen] = useState(false);
|
||||||
|
const receivedAgentNodeIds = useRef(new Set<string>());
|
||||||
const [edges, setEdges] = useState<CloneEdge[]>([]);
|
const [edges, setEdges] = useState<CloneEdge[]>([]);
|
||||||
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
|
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -4605,6 +4623,30 @@ export function LiblibVideoCanvasReplica({
|
|||||||
const [draftTitle, setDraftTitle] = useState("未命名");
|
const [draftTitle, setDraftTitle] = useState("未命名");
|
||||||
const [isTitleEditing, setIsTitleEditing] = useState(false);
|
const [isTitleEditing, setIsTitleEditing] = useState(false);
|
||||||
const [activePanel, setActivePanel] = useState<ActivePanel>(null);
|
const [activePanel, setActivePanel] = useState<ActivePanel>(null);
|
||||||
|
const [tvstarDocked, setTvstarDocked] = useState(false);
|
||||||
|
const [tvstarDockWidth, setTvstarDockWidth] = useState(360);
|
||||||
|
useEffect(() => {
|
||||||
|
try {
|
||||||
|
setTvstarDocked(localStorage.getItem(`tvstar:docked:${canvasId}`) === "1");
|
||||||
|
const savedWidth = Number(localStorage.getItem(`tvstar:dock-width:${canvasId}`));
|
||||||
|
setTvstarDockWidth(Number.isFinite(savedWidth) && savedWidth >= 320 && savedWidth <= 560 ? savedWidth : 360);
|
||||||
|
} catch { /* storage is optional */ }
|
||||||
|
}, [canvasId]);
|
||||||
|
const tvstarPanelRestoreRef = useRef<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
tvstarPanelRestoreRef.current = canvasId;
|
||||||
|
try {
|
||||||
|
setActivePanel(localStorage.getItem(`tvstar:panel:${canvasId}`) === "open" ? "tvstar" : null);
|
||||||
|
} catch { /* storage is optional */ }
|
||||||
|
}, [canvasId]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (tvstarPanelRestoreRef.current === canvasId) {
|
||||||
|
tvstarPanelRestoreRef.current = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try { localStorage.setItem(`tvstar:panel:${canvasId}`, activePanel === "tvstar" ? "open" : "closed"); }
|
||||||
|
catch { /* storage is optional */ }
|
||||||
|
}, [activePanel, canvasId]);
|
||||||
const [canvasViewMode, setCanvasViewMode] = useState<CanvasViewMode>("workflow");
|
const [canvasViewMode, setCanvasViewMode] = useState<CanvasViewMode>("workflow");
|
||||||
const [assetManagerWidth, setAssetManagerWidth] = useState(ASSET_MANAGER_DEFAULT_WIDTH);
|
const [assetManagerWidth, setAssetManagerWidth] = useState(ASSET_MANAGER_DEFAULT_WIDTH);
|
||||||
const [historyListDownloadPendingId, setHistoryListDownloadPendingId] = useState<string | null>(null);
|
const [historyListDownloadPendingId, setHistoryListDownloadPendingId] = useState<string | null>(null);
|
||||||
@ -4727,6 +4769,7 @@ export function LiblibVideoCanvasReplica({
|
|||||||
setNodes(migrateLegacyGroups(restored));
|
setNodes(migrateLegacyGroups(restored));
|
||||||
setMultiSelection([]);
|
setMultiSelection([]);
|
||||||
setGroupTemplates((project.canvasData as any)?.groupTemplates||[]);
|
setGroupTemplates((project.canvasData as any)?.groupTemplates||[]);
|
||||||
|
receivedAgentNodeIds.current = new Set(restored.map((node) => node.id));
|
||||||
setEdges(restoreEdges(project.canvasData));
|
setEdges(restoreEdges(project.canvasData));
|
||||||
const storedViewport = data?.viewport;
|
const storedViewport = data?.viewport;
|
||||||
setViewport(storedViewport && [storedViewport.x, storedViewport.y, storedViewport.zoom].every(Number.isFinite)
|
setViewport(storedViewport && [storedViewport.x, storedViewport.y, storedViewport.zoom].every(Number.isFinite)
|
||||||
@ -4832,6 +4875,66 @@ export function LiblibVideoCanvasReplica({
|
|||||||
applyMergedSnapshot,
|
applyMergedSnapshot,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const refreshVideoAgentResults = useCallback(async (projectId: string, resultNodeIds: string[]) => {
|
||||||
|
if (projectId !== canvasId) return;
|
||||||
|
const result = await canvasService.getProject(canvasId);
|
||||||
|
if (!result.success || !result.data) return;
|
||||||
|
const incoming = restoreNodes(result.data.canvasData).filter((node) => resultNodeIds.includes(node.id));
|
||||||
|
const unseen = incoming.filter((node) => !receivedAgentNodeIds.current.has(node.id));
|
||||||
|
for (const node of incoming) receivedAgentNodeIds.current.add(node.id);
|
||||||
|
setNodes((current) => mergeVideoAgentResults(current.map((node) => {
|
||||||
|
const remote = incoming.find((item) => item.id === node.id);
|
||||||
|
return remote && remote.draftValues?.temporaryVideoUrl === node.draftValues?.mediaUrl && remote.draftValues?.mediaUrl !== node.draftValues?.mediaUrl ? { ...node, draftValues: { ...node.draftValues, mediaUrl: remote.draftValues?.mediaUrl, url: remote.draftValues?.url } } : node;
|
||||||
|
}), unseen));
|
||||||
|
setEdges((current) => mergeVideoAgentResults(current, restoreEdges(result.data!.canvasData).filter((edge) => unseen.some((node) => node.id === edge.target))));
|
||||||
|
}, [canvasId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = async (event: Event) => {
|
||||||
|
const change = (event as CustomEvent<{ projectId: string; createdNodeIds?: string[]; updatedNodeIds?: string[]; deletedNodeIds?: string[]; action?: string; nodeIds?: string[]; viewportChanged?: boolean }>).detail;
|
||||||
|
if (change?.projectId !== canvasId) return;
|
||||||
|
const response = await canvasService.getProject(canvasId);
|
||||||
|
if (!response.success || !response.data) return;
|
||||||
|
const remote = restoreNodes(response.data.canvasData);
|
||||||
|
const changed = new Set([...(change.createdNodeIds || []), ...(change.updatedNodeIds || [])]);
|
||||||
|
const deleted = new Set(change.deletedNodeIds || []);
|
||||||
|
setNodes((current) => mergeVideoAgentResults(current.filter((node) => !deleted.has(node.id)).map((node) => changed.has(node.id) ? remote.find((item) => item.id === node.id) || node : node), remote.filter((node) => changed.has(node.id))));
|
||||||
|
setEdges((current) => {
|
||||||
|
const kept = current.filter((edge) => !deleted.has(edge.source) && !deleted.has(edge.target) && !(change.action === "disconnect" && edge.source === change.nodeIds?.[0] && edge.target === change.nodeIds?.[1]));
|
||||||
|
return change.action === "connect" ? mergeVideoAgentResults(kept, restoreEdges(response.data!.canvasData).filter((edge) => edge.source === change.nodeIds?.[0] && edge.target === change.nodeIds?.[1])) : kept;
|
||||||
|
});
|
||||||
|
if (change.viewportChanged && response.data.canvasData?.viewport) setViewport(response.data.canvasData.viewport);
|
||||||
|
};
|
||||||
|
window.addEventListener("video-canvas-agent-mutation", handler);
|
||||||
|
return () => window.removeEventListener("video-canvas-agent-mutation", handler);
|
||||||
|
}, [canvasId]);
|
||||||
|
|
||||||
|
const saveBeforeVideoAgent = useCallback(async () => {
|
||||||
|
const statusResponse = await fetch(`/api/canvas/agent-runs?${new URLSearchParams({ chatId: canvasId, projectId: canvasId })}`, { cache: "no-store" });
|
||||||
|
if (statusResponse.ok && (await statusResponse.json()).run?.status === "running") throw new Error("当前视频任务还在执行,请使用补充要求。");
|
||||||
|
const remote = await canvasService.getProject(canvasId);
|
||||||
|
if (!remote.success || !remote.data) throw new Error("无法读取视频画布,请稍后重试");
|
||||||
|
const remoteNodes = restoreNodes(remote.data.canvasData);
|
||||||
|
const unseen = remoteNodes.filter((node) => node.draftValues?.canvasAgentRunId && !receivedAgentNodeIds.current.has(node.id));
|
||||||
|
const syncedNodes = nodes.map((node) => {
|
||||||
|
const archived = remoteNodes.find((item) => item.id === node.id && item.draftValues?.temporaryVideoUrl === node.draftValues?.mediaUrl);
|
||||||
|
return archived ? { ...node, draftValues: { ...node.draftValues, mediaUrl: archived.draftValues?.mediaUrl, url: archived.draftValues?.url, temporaryVideoUrl: archived.draftValues?.temporaryVideoUrl } } : node;
|
||||||
|
});
|
||||||
|
const mergedNodes = mergeVideoAgentResults(syncedNodes, unseen);
|
||||||
|
const mergedEdges = mergeVideoAgentResults(edges, restoreEdges(remote.data.canvasData).filter((edge) => unseen.some((node) => node.id === edge.target)));
|
||||||
|
const response = await fetch("/api/canvas/video-agent", {
|
||||||
|
method: "POST", headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ projectId: canvasId, baseRevision: remote.data.updatedAt, canvasData: {
|
||||||
|
nodes: serializeNodes(mergedNodes), edges: serializeEdges(mergedEdges),
|
||||||
|
selectedNodeIds: selectedNodeId ? [selectedNodeId] : [], viewport, tool: "select",
|
||||||
|
} }),
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) throw new Error(result.error || "画布保存失败,请稍后重试");
|
||||||
|
if (result.success) { setNodes(mergedNodes); setEdges(mergedEdges); for (const node of unseen) receivedAgentNodeIds.current.add(node.id); }
|
||||||
|
if (!result.success) throw new Error(result.error || "画布保存失败,请稍后重试");
|
||||||
|
}, [canvasId, nodes, edges, selectedNodeId, viewport]);
|
||||||
|
|
||||||
const commitTitle = useCallback(() => {
|
const commitTitle = useCallback(() => {
|
||||||
const nextTitle = draftTitle.trim() || "未命名";
|
const nextTitle = draftTitle.trim() || "未命名";
|
||||||
setProjectTitle(nextTitle);
|
setProjectTitle(nextTitle);
|
||||||
@ -5484,6 +5587,361 @@ export function LiblibVideoCanvasReplica({
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const tvstarReferences = useMemo<TVstarReference[]>(() => nodes.flatMap((node) => {
|
||||||
|
const url = getNodeReferenceMediaUrl(node);
|
||||||
|
if (!url || (node.inputType !== "image" && node.inputType !== "video")) return [];
|
||||||
|
return [{ id: node.id, title: node.title, url, type: node.inputType,
|
||||||
|
duration: Number(node.draftValues?.duration) || undefined }];
|
||||||
|
}), [nodes]);
|
||||||
|
const tvstarCanvasNodes = useMemo<TVstarNodeContext[]>(() => nodes.filter(node => !isCanvasGroup(node)).map(node => {
|
||||||
|
const draft = node.draftValues || {};
|
||||||
|
const content = Array.isArray(draft.content) ? draft.content.filter((value): value is string => typeof value === "string").join("\n") : "";
|
||||||
|
const description = [draft.prompt, content, draft.sceneDescription].filter((value): value is string => typeof value === "string" && Boolean(value.trim())).join("\n");
|
||||||
|
return { id: node.id, title: node.title, type: node.inputType || node.kind, description: description.slice(0, 1500) };
|
||||||
|
}), [nodes]);
|
||||||
|
const tvstarModels = useMemo<TVstarModel[]>(() => canvasModelOptions
|
||||||
|
.filter(model => !model.isSubModel && isCanvasLanguageModel(model))
|
||||||
|
.map(model => ({ id: model.id, label: model.displayName || model.modelId || model.id, modelId: model.modelId || "", providerType: model.providerType || "", supportsVision: isCanvasVisionModel(model) })), [canvasModelOptions]);
|
||||||
|
const tvstarGenerationModels = useMemo<TVstarGenerationModel[]>(() => canvasModelOptions
|
||||||
|
.filter(model => !model.isSubModel)
|
||||||
|
.flatMap(model => {
|
||||||
|
const label = model.displayName || model.modelId || model.id;
|
||||||
|
return [
|
||||||
|
...(filterCanvasModels([model], "image").length ? [{ id: model.id, label, kind: "image" as const,
|
||||||
|
supportsReference: filterCanvasModels([model], "image-edit").length > 0 }] : []),
|
||||||
|
...(filterCanvasModels([model], "video", "first-frame").length ? [{ id: model.id, label, kind: "video" as const }] : []),
|
||||||
|
];
|
||||||
|
}), [canvasModelOptions]);
|
||||||
|
|
||||||
|
const compileCanvasGroupRun = useCallback((sourceNodes: CloneNode[], sourceEdges: CloneEdge[], groupId: string) =>
|
||||||
|
compileGroupRun(sourceNodes, sourceEdges, groupId, canvasId, n => {
|
||||||
|
const node = n as CloneNode, d = node.draftValues || {}, p = getNodeParams(node), settings = (p.settings || {}) as Record<string, any>;
|
||||||
|
if (d.action === "VIDEO_HD_UPSCALE") return { kind: "video-upscale", params: { resolution: d.hdResolution || "1080P" } };
|
||||||
|
if (d.audioParams) return { kind: "audio", params: d.audioParams as Record<string, unknown> };
|
||||||
|
if (getTargetModuleKind(node) === "smart-edit" || d.nodeType === "smart-edit") {
|
||||||
|
const draft = (d.smartEditDraft || {}) as any, plan = draft.plans?.[draft.selectedPlanIndex || 0] || d.editPlan;
|
||||||
|
const changes = sourceEdges.some(e => e.target === node.id && groupMembers(sourceNodes, groupId).some(m => m.id === e.source && (/GENERATE|UPSCALE/.test(String(m.draftValues?.action)) || m.draftValues?.generationTaskId)));
|
||||||
|
if (plan && !changes) return { kind: "smart-edit", params: { operation: "render", plan } };
|
||||||
|
return { kind: "smart-edit", params: { operation: "plan", autoRender: true, mode: draft.mode || "sequence", targetDuration: draft.targetDuration || 300, shotDurations: draft.shotDurations, shotDescriptions: draft.shotDescriptions, ratio: draft.ratio || "16:9", resolution: draft.resolution || "720p", semantic: draft.semantic ?? false, muteAudio: draft.muteAudio === true, preferredModelRef: draft.preferredModelRef, prompt: draft.prompt || "", removeSilence: draft.removeSilence || false, transcribe: draft.transcribe || false, music: draft.music, beatSync: draft.beatSync || false, variants: 1 } };
|
||||||
|
}
|
||||||
|
const key = String(p.functionKey || d.functionKey || (node.inputType === "video" ? "text-to-video" : node.inputType === "image" ? "" : "story-script"));
|
||||||
|
const definition = key ? getConfiguredFunction(videoCanvasFunctionConfig, key) : { key: "image-generate", kind: "image-edit" as const, route: "canvas-generate-image" as const, enabled: true, label: "图片生成", prompt: "", description: "" };
|
||||||
|
if (!definition?.enabled || !videoCanvasFunctionConfig.enabled) throw new Error(`${node.title}:功能未启用或未配置`);
|
||||||
|
const model = getFunctionModel(videoCanvasFunctionConfig, definition, normalizeModelRef(settings.model || p.model));
|
||||||
|
const prompt = composeFunctionPrompt(definition, String(p.prompt || d.prompt || ""));
|
||||||
|
if (node.inputType === "video") return { kind: "video", params: { prompt, preferredModelRef: model, mode: p.mode || settings.mode || (sourceEdges.some(e => e.target === node.id && sourceNodes.find(n => n.id === e.source)?.inputType === "image") ? "first-frame" : "text-to-video"), duration: Number(String(settings.duration || p.duration || 5).replace(/s$/, "")), ratio: settings.ratio || p.ratio || "16:9", resolution: settings.resolution || p.resolution || "720p", generateAudio: settings.audio ? settings.audio !== "关闭" : p.generateAudio === true } };
|
||||||
|
if (node.inputType === "image") {
|
||||||
|
if (["enhance", "extend", "remove-bg"].includes(definition.route || "")) return { kind: "image-operation", params: { operation: definition.route, prompt } };
|
||||||
|
return { kind: "image", params: { prompt, model, allowFailover: false, imageCount: 1, imageSize: settings.resolution || p.imageSize || "1K", aspectRatio: settings.ratio || p.ratio || p.aspectRatio || "auto", referenceImages: p.referenceImages || [], billingFeature: getImageGenerationBillingFeature(key), promptExtend: true } };
|
||||||
|
}
|
||||||
|
if (node.inputType === "text" || node.kind === "script" || node.kind === "text") return { kind: "analysis", params: { prompt, preferredModelRef: model, mode: key === "story-script" ? "story-script" : key === "video-analysis" ? "video-analysis" : "agent-plan", nodeTitle: node.title } };
|
||||||
|
throw new Error(`${node.title}:尚未配置可执行动作`);
|
||||||
|
}, () => crypto.randomUUID()), [canvasId, videoCanvasFunctionConfig]);
|
||||||
|
|
||||||
|
const applyTVstarShots = useCallback(async (shots: TVstarShot[], goal: string, references: TVstarReference[] = [], selection: TVstarGenerationSelection = {}, runMode: "submit" | "prepare" = "submit") => {
|
||||||
|
if (!shots.length) return false;
|
||||||
|
let output: ReturnType<typeof tvstarOutputRequirements>;
|
||||||
|
let timing: ReturnType<typeof tvstarTiming>;
|
||||||
|
try { output = tvstarOutputRequirements(goal); timing = tvstarTiming(goal, shots); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "成片要求无效"); return false; }
|
||||||
|
const videoDefinition = getConfiguredFunction(videoCanvasFunctionConfig, "first-frame-video");
|
||||||
|
if (runMode === "submit" && (!videoCanvasFunctionConfig.enabled || !videoDefinition.enabled)) {
|
||||||
|
toast.error("首帧生视频功能尚未启用,无法创建可执行分镜");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let videoSettings: ReturnType<typeof chooseStoryVideoSettings>[];
|
||||||
|
let availableModels: CanvasModelOption[] = [];
|
||||||
|
try {
|
||||||
|
const preferredModel = selection.videoModelRef || getFunctionModel(videoCanvasFunctionConfig, videoDefinition);
|
||||||
|
availableModels = canvasModelOptions.length ? canvasModelOptions :
|
||||||
|
((await fetch("/api/models", { cache: "no-store" }).then(response => response.json()))?.models || [])
|
||||||
|
.filter((model: CanvasModelOption) => getCanvasModelRef(model));
|
||||||
|
if (selection.videoModelRef && !filterCanvasModels(availableModels, "video", "first-frame")
|
||||||
|
.some(model => model.id === selection.videoModelRef || model.modelId === selection.videoModelRef))
|
||||||
|
throw new Error("所选视频模型不支持首帧生视频,请换一个模型");
|
||||||
|
videoSettings = shots.map((_shot, index) => chooseStoryVideoSettings(
|
||||||
|
availableModels, true, timing.shotDurations[index], preferredModel,
|
||||||
|
{ ...output, minimumDuration: true, minimumResolution: true, strictModel: Boolean(selection.videoModelRef) },
|
||||||
|
));
|
||||||
|
} catch (error) {
|
||||||
|
if (runMode === "submit") {
|
||||||
|
toast.error(error instanceof Error ? error.message : "没有可执行的首帧生视频模型");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
videoSettings = shots.map(shot => ({
|
||||||
|
mode: "first-frame" as const, model: selection.videoModelRef || "",
|
||||||
|
duration: Math.max(1, Math.min(10, Math.ceil(Number.parseFloat(shot.duration) || 5))),
|
||||||
|
ratio: output.ratio, resolution: output.resolution, generateAudio: output.generateAudio ?? false,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let referenceImages: string[];
|
||||||
|
try {
|
||||||
|
referenceImages = await resolveTVstarGenerationReferences(references);
|
||||||
|
if (runMode === "submit" && selection.imageModelRef && !filterCanvasModels(availableModels, referenceImages.length ? "image-edit" : "image")
|
||||||
|
.some(model => model.id === selection.imageModelRef || model.modelId === selection.imageModelRef))
|
||||||
|
throw new Error(referenceImages.length ? "所选图片模型不支持参考图生成,请换一个模型" : "所选图片模型不可用,请换一个模型");
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : "参考视频处理失败");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const referenceCapableImageModels = referenceImages.length ? filterCanvasModels(availableModels, "image-edit") : [];
|
||||||
|
if (runMode === "submit" && referenceImages.length && !referenceCapableImageModels.length) {
|
||||||
|
toast.error("没有支持参考图的图片模型,无法按引用素材生成关键帧");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const imageModelRef = selection.imageModelRef || (referenceImages.length
|
||||||
|
? (referenceCapableImageModels.find(model => model.id === videoCanvasFunctionConfig.defaultImageModel || model.modelId === videoCanvasFunctionConfig.defaultImageModel)
|
||||||
|
|| referenceCapableImageModels[0])?.id : undefined);
|
||||||
|
const center = toCanvasPoint(window.innerWidth / 2, window.innerHeight / 2);
|
||||||
|
const x = Math.round(center.x - 500);
|
||||||
|
const y = Math.round(center.y - 180);
|
||||||
|
const script = createTextResourceNode({
|
||||||
|
content: [goal, ...shots.map((shot, index) => `镜头 ${shot.shot}(目标 ${shot.duration},生成 ${videoSettings[index].duration}s)${shot.sceneDescription}。运镜:${shot.cameraMovement}`)].join("\n\n"),
|
||||||
|
title: "TVstar · 创作分镜",
|
||||||
|
x, y,
|
||||||
|
});
|
||||||
|
script.draftValues = { ...script.draftValues, tvstarShots: shots, tvstarReferences: references, source: "tvstar" };
|
||||||
|
const nextNodes: CloneNode[] = [script];
|
||||||
|
const nextEdges: CloneEdge[] = [];
|
||||||
|
const videoNodeIds: string[] = [];
|
||||||
|
shots.forEach((shot, index) => {
|
||||||
|
const settings = videoSettings[index];
|
||||||
|
const rowY = y + index * 450;
|
||||||
|
const imagePrompt = [`仅生成镜头 ${shot.shot} 的一张电影关键帧。`, shot.imagePrompt || shot.sceneDescription, tvstarShotComposition(goal)].join("\n");
|
||||||
|
const image = createTargetModuleNode("image", x + 560, rowY, nodes.length + index * 2 + 1);
|
||||||
|
image.title = `镜头 ${shot.shot} · 关键帧`;
|
||||||
|
image.draftValues = {
|
||||||
|
...image.draftValues,
|
||||||
|
prompt: imagePrompt,
|
||||||
|
params: { prompt: imagePrompt, aspectRatio: output.ratio, referenceImages, ...(imageModelRef ? { model: imageModelRef } : {}) },
|
||||||
|
tvstarShot: shot.shot,
|
||||||
|
source: "tvstar",
|
||||||
|
};
|
||||||
|
const video = createTargetModuleNode("video", x + 1020, rowY, nodes.length + index * 2 + 2);
|
||||||
|
video.title = `镜头 ${shot.shot} · 视频`;
|
||||||
|
const videoPrompt = [shot.sceneDescription, shot.motionPrompt, shot.cameraMovement,
|
||||||
|
...(settings.generateAudio ? [shot.dialogue, shot.backgroundMusic, shot.voiceAndSfx] : []),
|
||||||
|
`整片背景要求(当前只拍镜头 ${shot.shot},不执行其他镜头):${goal}`,
|
||||||
|
tvstarShotComposition(goal), "保持当前镜头连续运动,不生成片中片,不切换到其他分镜。",
|
||||||
|
].filter(Boolean).join("。");
|
||||||
|
video.draftValues = {
|
||||||
|
...video.draftValues,
|
||||||
|
prompt: videoPrompt,
|
||||||
|
params: {
|
||||||
|
mode: "first-frame",
|
||||||
|
prompt: videoPrompt,
|
||||||
|
model: settings.model,
|
||||||
|
duration: settings.duration,
|
||||||
|
ratio: settings.ratio,
|
||||||
|
resolution: settings.resolution,
|
||||||
|
generateAudio: settings.generateAudio,
|
||||||
|
},
|
||||||
|
tvstarShot: shot.shot,
|
||||||
|
source: "tvstar",
|
||||||
|
};
|
||||||
|
nextNodes.push(image, video);
|
||||||
|
videoNodeIds.push(video.id);
|
||||||
|
nextEdges.push(
|
||||||
|
{ id: makeId("edge"), source: script.id, target: image.id },
|
||||||
|
{ id: makeId("edge"), source: image.id, target: video.id },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const finalVideo = createTargetModuleNode("smart-edit", x + 1510, y + 140, nodes.length + shots.length * 2 + 1);
|
||||||
|
finalVideo.title = `TVstar · ${timing.targetDuration} 秒成片`;
|
||||||
|
finalVideo.draftValues = {
|
||||||
|
...finalVideo.draftValues,
|
||||||
|
source: "tvstar",
|
||||||
|
smartEditDraft: {
|
||||||
|
mode: "sequence",
|
||||||
|
ratio: output.ratio,
|
||||||
|
resolution: output.resolution,
|
||||||
|
muteAudio: output.generateAudio === false,
|
||||||
|
targetDuration: timing.targetDuration,
|
||||||
|
shotDurations: timing.shotDurations,
|
||||||
|
shotDescriptions: shots.map(shot => [shot.sceneDescription, shot.motionPrompt, shot.cameraMovement].filter(Boolean).join("。").slice(0, 600)),
|
||||||
|
semantic: true,
|
||||||
|
preferredModelRef: videoCanvasFunctionConfig.defaultMultimodalModel || undefined,
|
||||||
|
prompt: goal,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
nextNodes.push(finalVideo);
|
||||||
|
nextEdges.push(...videoNodeIds.map(id => ({ id: makeId("edge"), source: id, target: finalVideo.id })));
|
||||||
|
const groupId = makeId("tvstar-group");
|
||||||
|
const groupNodes = makeCanvasGroup(nextNodes, nextNodes.map(node => node.id), groupId, runMode === "prepare" ? "TVstar · 待运行工作流" : "TVstar · 自动制作");
|
||||||
|
let requests: ReturnType<typeof compileCanvasGroupRun> | undefined;
|
||||||
|
if (runMode === "submit") {
|
||||||
|
try { requests = compileCanvasGroupRun([...nodes, ...groupNodes], [...edges, ...nextEdges], groupId); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "无法创建视频制作任务"); return false; }
|
||||||
|
}
|
||||||
|
addNodes(groupNodes, nextEdges);
|
||||||
|
setSelectedNodeId(groupId);
|
||||||
|
setViewport(current => ({ ...current, x: Math.round((window.innerWidth - (window.innerWidth > 800 ? 540 : 0)) / 2 - (x + 700) * current.zoom), y: Math.round(window.innerHeight / 2 - (y + 180) * current.zoom) }));
|
||||||
|
if (runMode === "prepare") {
|
||||||
|
toast.success(`已创建 ${shots.length} 个待运行镜头及成片节点,可在画布检查后开始制作`);
|
||||||
|
return groupId;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await groupRuns.submit(requests!);
|
||||||
|
generationTasks.refresh();
|
||||||
|
toast.success(`已开始制作 ${shots.length} 个镜头,完成后自动生成 ${timing.targetDuration} 秒成片`);
|
||||||
|
return groupId;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`${error instanceof Error ? error.message : "提交失败"};节点已保留,可选中编组重试`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [addNodes, canvasModelOptions, compileCanvasGroupRun, edges, generationTasks, groupRuns, nodes, toCanvasPoint, videoCanvasFunctionConfig]);
|
||||||
|
|
||||||
|
const runPreparedTVstarGroup = useCallback(async (groupId: string) => {
|
||||||
|
let requests: ReturnType<typeof compileCanvasGroupRun>;
|
||||||
|
try { requests = compileCanvasGroupRun(nodes, edges, groupId); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "待运行工作流已变化,无法开始制作"); return false; }
|
||||||
|
try {
|
||||||
|
await groupRuns.submit(requests);
|
||||||
|
generationTasks.refresh();
|
||||||
|
toast.success("已开始执行画布中的 TVstar 工作流");
|
||||||
|
return groupId;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : "工作流提交失败");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [compileCanvasGroupRun, edges, generationTasks, groupRuns, nodes]);
|
||||||
|
|
||||||
|
const applyTVstarEdit = useCallback(async (references: TVstarReference[], goal: string) => {
|
||||||
|
const videos = references.filter(item => item.type === "video").slice(0, 12);
|
||||||
|
if (!videos.length) { toast.error("请先引用至少一个视频片段"); return false; }
|
||||||
|
let output: ReturnType<typeof tvstarOutputRequirements>;
|
||||||
|
try { output = tvstarOutputRequirements(goal); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "成片要求无效"); return false; }
|
||||||
|
const timing = tvstarTiming(goal, videos.map(item => ({ duration: `${Math.min(item.duration || 5, 5)}s` })));
|
||||||
|
const center = toCanvasPoint(window.innerWidth / 2, window.innerHeight / 2);
|
||||||
|
const x = Math.round(center.x - 380);
|
||||||
|
const y = Math.round(center.y - 180);
|
||||||
|
const brief = createTextResourceNode({ content: goal, title: "TVstar · 剪辑要求", x, y });
|
||||||
|
brief.draftValues = { ...brief.draftValues, source: "tvstar", tvstarReferences: videos };
|
||||||
|
const nextNodes: CloneNode[] = [brief];
|
||||||
|
const nextEdges: CloneEdge[] = [];
|
||||||
|
const sources = videos.map((item, index) => {
|
||||||
|
const source = createMediaResourceNode({
|
||||||
|
mediaType: "video", mediaUrl: item.url, title: `素材 ${index + 1} · ${item.title}`,
|
||||||
|
x: x + 480, y: y + index * 375,
|
||||||
|
});
|
||||||
|
source.draftValues = { ...source.draftValues, source: "tvstar", originalReferenceId: item.id };
|
||||||
|
nextNodes.push(source);
|
||||||
|
return source;
|
||||||
|
});
|
||||||
|
const result = createTargetModuleNode("smart-edit", x + 1140, y + 90, nodes.length + videos.length + 1);
|
||||||
|
result.title = `TVstar · ${timing.targetDuration} 秒智能成片`;
|
||||||
|
result.draftValues = { ...result.draftValues, source: "tvstar", smartEditDraft: {
|
||||||
|
mode: "sequence", ratio: output.ratio, resolution: output.resolution, muteAudio: output.generateAudio === false,
|
||||||
|
targetDuration: timing.targetDuration, shotDurations: timing.shotDurations,
|
||||||
|
shotDescriptions: videos.map(item => `从《${item.title}》选取符合用户要求的真实高光画面:${goal}`.slice(0, 600)),
|
||||||
|
semantic: true, preferredModelRef: videoCanvasFunctionConfig.defaultMultimodalModel || undefined,
|
||||||
|
prompt: goal,
|
||||||
|
} };
|
||||||
|
nextNodes.push(result);
|
||||||
|
nextEdges.push(...sources.map(source => ({ id: makeId("edge"), source: source.id, target: result.id })));
|
||||||
|
const groupId = makeId("tvstar-edit-group");
|
||||||
|
const groupNodes = makeCanvasGroup(nextNodes, nextNodes.map(node => node.id), groupId, "TVstar · 素材智能剪辑");
|
||||||
|
let requests: ReturnType<typeof compileCanvasGroupRun>;
|
||||||
|
try { requests = compileCanvasGroupRun([...nodes, ...groupNodes], [...edges, ...nextEdges], groupId); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "无法创建剪辑任务"); return false; }
|
||||||
|
addNodes(groupNodes, nextEdges);
|
||||||
|
setSelectedNodeId(groupId);
|
||||||
|
setViewport(current => ({ ...current,
|
||||||
|
x: Math.round((window.innerWidth - (window.innerWidth > 800 ? 540 : 0)) / 2 - (x + 700) * current.zoom),
|
||||||
|
y: Math.round(window.innerHeight / 2 - (y + 180) * current.zoom),
|
||||||
|
}));
|
||||||
|
try {
|
||||||
|
await groupRuns.submit(requests);
|
||||||
|
generationTasks.refresh();
|
||||||
|
toast.success(`已开始分析 ${videos.length} 段真实视频并合成成片`);
|
||||||
|
return groupId;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`${error instanceof Error ? error.message : "提交失败"};剪辑节点已保留,可选中编组重试`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [addNodes, compileCanvasGroupRun, edges, generationTasks, groupRuns, nodes, toCanvasPoint, videoCanvasFunctionConfig.defaultMultimodalModel]);
|
||||||
|
|
||||||
|
const applyCharacterStudio = useCallback(async (character: StudioCharacter, style: string, views: StudioView[], referenceUrl?: string): Promise<boolean> => {
|
||||||
|
if (!views.length) return false;
|
||||||
|
const requiresIdentityReference = Boolean(referenceUrl) || views.length > 1;
|
||||||
|
// Recover a missed initial catalog load before deciding that generation is unavailable.
|
||||||
|
let availableModels = canvasModelOptions;
|
||||||
|
if (!availableModels.length) {
|
||||||
|
const response = await fetch("/api/models", { cache: "no-store" });
|
||||||
|
if (!response.ok) throw Error("角色出图模型暂时无法读取,请稍后重试");
|
||||||
|
const catalog = await response.json();
|
||||||
|
availableModels = Array.isArray(catalog.models) ? catalog.models : [];
|
||||||
|
}
|
||||||
|
const imageCandidates = filterCanvasModels(availableModels, requiresIdentityReference ? "image-edit" : "image");
|
||||||
|
if (!imageCandidates.length) {
|
||||||
|
toast.error(requiresIdentityReference ? "没有支持参考图的图片模型,无法保持多视图角色一致性" : "没有可执行的图片模型");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const imageModelRef = imageCandidates.find(model => model.id === videoCanvasFunctionConfig.defaultImageModel
|
||||||
|
|| model.modelId === videoCanvasFunctionConfig.defaultImageModel)?.id || imageCandidates[0]?.id;
|
||||||
|
const center = toCanvasPoint(window.innerWidth / 2, window.innerHeight / 2);
|
||||||
|
const x = Math.round(center.x - 360);
|
||||||
|
const y = Math.round(center.y - 160);
|
||||||
|
// Appearance is shared; generated prompt framing must not override each view's composition.
|
||||||
|
const identity = [character.name, character.description, character.look, character.wardrobe,
|
||||||
|
...(character.look || character.wardrobe ? [] : [character.prompt]), `风格:${style}`].filter(Boolean).join("。 ");
|
||||||
|
const source = createTextResourceNode({ content: identity, title: `${character.name} · 角色设定`, x, y });
|
||||||
|
source.draftValues = { ...source.draftValues, source: "character-studio", characterIdentity: identity };
|
||||||
|
const viewPrompts: Record<StudioView, string> = {
|
||||||
|
"角色立绘": "全身角色立绘,站姿自然,人物完整入画,纯净背景,清晰展示稳定面部特征、服装和道具。",
|
||||||
|
"脸部近景": "只拍同一角色脸部近景,脸部占据画幅主体,最多露出肩部,不出现全身或半身立绘;保持五官、发型与标志性特征完全一致,柔和电影布光。",
|
||||||
|
"表情参考": "同一角色表情设定图,四宫格分别展示平静、喜悦、惊讶、愤怒,五官与服装细节一致。",
|
||||||
|
"角色三视图": "同一角色正面、侧面、背面三视图并排,站姿和服装统一,清晰标注轮廓,纯净背景。",
|
||||||
|
};
|
||||||
|
const nextNodes: CloneNode[] = [source];
|
||||||
|
const nextEdges: CloneEdge[] = [];
|
||||||
|
// A single generated identity anchor feeds every other view. Text alone
|
||||||
|
// does not constrain an image model to reproduce the same face.
|
||||||
|
const orderedViews: StudioView[] = views.includes("角色立绘")
|
||||||
|
? ["角色立绘", ...views.filter(view => view !== "角色立绘")]
|
||||||
|
: views;
|
||||||
|
let identityAnchorId: string | undefined;
|
||||||
|
orderedViews.forEach((view, index) => {
|
||||||
|
const singleView = view === "角色立绘" || view === "脸部近景"
|
||||||
|
? "只生成一张单一完整构图,禁止拼贴、画中画、分屏、宫格和附加小窗;参考图只用于人物身份,不复用其构图。" : "";
|
||||||
|
const prompt = `${identity}\n${viewPrompts[view]} 不改变角色身份,不增加多余人物。${singleView}`;
|
||||||
|
const node = createTargetModuleNode("image", x + 500 + index * 440, y, nodes.length + index + 1);
|
||||||
|
node.title = `${character.name} · ${view}`;
|
||||||
|
node.draftValues = {
|
||||||
|
...node.draftValues,
|
||||||
|
prompt,
|
||||||
|
params: { prompt, aspectRatio: view === "角色三视图" || view === "表情参考" ? "16:9" : "3:4", ...(referenceUrl && index === 0 ? { referenceImages: [referenceUrl] } : {}), ...(imageModelRef ? { model: imageModelRef } : {}) },
|
||||||
|
characterIdentity: identity,
|
||||||
|
characterView: view,
|
||||||
|
characterAnchorId: identityAnchorId,
|
||||||
|
source: "character-studio",
|
||||||
|
};
|
||||||
|
nextNodes.push(node);
|
||||||
|
nextEdges.push({ id: makeId("edge"), source: source.id, target: node.id });
|
||||||
|
if (identityAnchorId) nextEdges.push({ id: makeId("edge"), source: identityAnchorId, target: node.id });
|
||||||
|
else identityAnchorId = node.id;
|
||||||
|
});
|
||||||
|
const groupId = makeId("character-group");
|
||||||
|
const groupNodes = makeCanvasGroup(nextNodes, nextNodes.map(node => node.id), groupId, `${character.name} · 角色造型`);
|
||||||
|
let requests: ReturnType<typeof compileCanvasGroupRun>;
|
||||||
|
try { requests = compileCanvasGroupRun([...nodes, ...groupNodes], [...edges, ...nextEdges], groupId); }
|
||||||
|
catch (error) { toast.error(error instanceof Error ? error.message : "无法创建角色视图任务"); return false; }
|
||||||
|
addNodes(groupNodes, nextEdges);
|
||||||
|
setSelectedNodeId(groupId);
|
||||||
|
setViewport(current => ({ ...current, x: Math.round(window.innerWidth / 2 - (x + 570) * current.zoom), y: Math.round(window.innerHeight / 2 - (y + 180) * current.zoom) }));
|
||||||
|
try {
|
||||||
|
await groupRuns.submit(requests);
|
||||||
|
generationTasks.refresh();
|
||||||
|
setActivePanel(null);
|
||||||
|
toast.success(`已开始生成 ${character.name} 的 ${views.length} 个角色视图`);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(`${error instanceof Error ? error.message : "角色视图提交失败"};节点已保留,可选中编组重试`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}, [addNodes, canvasModelOptions, compileCanvasGroupRun, edges, generationTasks, groupRuns, nodes, toCanvasPoint, videoCanvasFunctionConfig.defaultImageModel]);
|
||||||
|
|
||||||
const readMediaIntrinsicSize = useCallback(async (file: File) => {
|
const readMediaIntrinsicSize = useCallback(async (file: File) => {
|
||||||
if (file.type.startsWith("video/")) {
|
if (file.type.startsWith("video/")) {
|
||||||
return await new Promise<{ width: number; height: number } | null>((resolve) => {
|
return await new Promise<{ width: number; height: number } | null>((resolve) => {
|
||||||
@ -9719,29 +10177,7 @@ export function LiblibVideoCanvasReplica({
|
|||||||
if(!selectedGroup||groupSubmitting)return;
|
if(!selectedGroup||groupSubmitting)return;
|
||||||
setGroupSubmitting(true);
|
setGroupSubmitting(true);
|
||||||
try {
|
try {
|
||||||
const requests=compileGroupRun(nodes,edges,selectedGroup.id,canvasId,n=>{
|
const requests=compileCanvasGroupRun(nodes,edges,selectedGroup.id);
|
||||||
const node=n as CloneNode,d=node.draftValues||{},p=getNodeParams(node),settings=(p.settings||{}) as Record<string,any>;
|
|
||||||
if(d.action==="VIDEO_HD_UPSCALE")return {kind:"video-upscale",params:{resolution:d.hdResolution||"1080P"}};
|
|
||||||
if(d.audioParams)return {kind:"audio",params:d.audioParams as Record<string,unknown>};
|
|
||||||
if(getTargetModuleKind(node)==="smart-edit"||d.nodeType==="smart-edit"){
|
|
||||||
const draft=(d.smartEditDraft||{}) as any,plan=draft.plans?.[draft.selectedPlanIndex||0]||d.editPlan;
|
|
||||||
const changes=edges.some(e=>e.target===node.id&&groupMembers(nodes,selectedGroup.id).some(m=>m.id===e.source&&(/GENERATE|UPSCALE/.test(String(m.draftValues?.action))||m.draftValues?.generationTaskId)));
|
|
||||||
if(plan&&!changes)return {kind:"smart-edit",params:{operation:"render",plan}};
|
|
||||||
return {kind:"smart-edit",params:{operation:"plan",autoRender:true,mode:draft.mode||"sequence",targetDuration:draft.targetDuration||300,ratio:draft.ratio||"16:9",resolution:draft.resolution||"720p",semantic:draft.semantic??false,prompt:draft.prompt||"",removeSilence:draft.removeSilence||false,transcribe:draft.transcribe||false,music:draft.music,beatSync:draft.beatSync||false,variants:1}};
|
|
||||||
}
|
|
||||||
const key=String(p.functionKey||d.functionKey||(node.inputType==="video"?"text-to-video":node.inputType==="image"?"":"story-script"));
|
|
||||||
const definition=key?getConfiguredFunction(videoCanvasFunctionConfig,key):{key:"image-generate",kind:"image-edit" as const,route:"canvas-generate-image" as const,enabled:true,label:"图片生成",prompt:"",description:""};
|
|
||||||
if(!definition?.enabled||!videoCanvasFunctionConfig.enabled)throw new Error(`${node.title}:功能未启用或未配置`);
|
|
||||||
const model=getFunctionModel(videoCanvasFunctionConfig,definition,normalizeModelRef(settings.model||p.model));
|
|
||||||
const prompt=composeFunctionPrompt(definition,String(p.prompt||d.prompt||""));
|
|
||||||
if(node.inputType==="video")return {kind:"video",params:{prompt,preferredModelRef:model,mode:p.mode||settings.mode||(edges.some(e=>e.target===node.id&&nodes.find(n=>n.id===e.source)?.inputType==="image")?"first-frame":"text-to-video"),duration:Number(String(settings.duration||p.duration||5).replace(/s$/,"")),ratio:settings.ratio||p.ratio||"16:9",resolution:settings.resolution||p.resolution||"720p",generateAudio:settings.audio!=="关闭"}};
|
|
||||||
if(node.inputType==="image"){
|
|
||||||
if(["enhance","extend","remove-bg"].includes(definition.route||""))return {kind:"image-operation",params:{operation:definition.route,prompt}};
|
|
||||||
return {kind:"image",params:{prompt,model,allowFailover:false,imageCount:1,imageSize:settings.resolution||p.imageSize||"1K",aspectRatio:settings.ratio||p.ratio||"auto",billingFeature:getImageGenerationBillingFeature(key),promptExtend:true}};
|
|
||||||
}
|
|
||||||
if(node.inputType==="text"||node.kind==="script"||node.kind==="text")return {kind:"analysis",params:{prompt,preferredModelRef:model,mode:key==="story-script"?"story-script":key==="video-analysis"?"video-analysis":"agent-plan",nodeTitle:node.title}};
|
|
||||||
throw new Error(`${node.title}:尚未配置可执行动作`);
|
|
||||||
},()=>crypto.randomUUID());
|
|
||||||
await groupRuns.submit(requests);
|
await groupRuns.submit(requests);
|
||||||
generationTasks.refresh();toast.success(`已提交 ${requests.length} 个节点,按连线依赖执行`);
|
generationTasks.refresh();toast.success(`已提交 ${requests.length} 个节点,按连线依赖执行`);
|
||||||
}catch(e){toast.error((e as Error).message);}finally{setGroupSubmitting(false);}
|
}catch(e){toast.error((e as Error).message);}finally{setGroupSubmitting(false);}
|
||||||
@ -10532,10 +10968,54 @@ export function LiblibVideoCanvasReplica({
|
|||||||
};
|
};
|
||||||
}, [lineConnectState, nodes]);
|
}, [lineConnectState, nodes]);
|
||||||
|
|
||||||
|
const handleAgentVideoUiCommand = async (command: CanvasAgentUiCommand) => {
|
||||||
|
const target = nodes.find((node) => node.id === (command.nodeIds[0] || selectedNodeId));
|
||||||
|
if (command.nodeIds.some((id) => !nodes.some((node) => node.id === id))) throw new Error("目标节点不属于当前视频画布");
|
||||||
|
if (target) { setSelectedNodeId(target.id); setSelectedEdgeId(null); }
|
||||||
|
if (command.featureId.startsWith("video.function.")) {
|
||||||
|
const key = command.featureId.slice("video.function.".length);
|
||||||
|
const tool = configuredTools.find((item) => item.toolKey === key);
|
||||||
|
if (!tool) throw new Error("此视频功能已关闭或尚未配置");
|
||||||
|
if ((key === "grid-split" || key === "image-crop") && target) { await runSelectedImageToolAction(target.id, "crop"); return; }
|
||||||
|
if (key === "angle-edit" && target) { setAngleEditorNodeId(target.id); return; }
|
||||||
|
const created = createToolNode(tool, target ? target.x + target.width + 72 : 360, target?.y || 300);
|
||||||
|
addNodes([created], command.nodeIds.map((id) => ({ id: makeId("edge"), source: id, target: created.id })));
|
||||||
|
setInspectorNodeId(created.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const action = command.featureId.replace("video.ui.", "");
|
||||||
|
const panels: Record<string, Exclude<ActivePanel, null>> = { assets: "assets", roles: "roleLibrary", styles: "styleLibrary", effects: "effectLibrary", history: "history", workflows: "workflow", share: "share", publish: "publish", skills: "skills", help: "help" };
|
||||||
|
if (panels[action]) { setActivePanel(panels[action]); return; }
|
||||||
|
if (action.startsWith("upload-")) { addTargetModule(action === "upload-video" ? "video" : action === "upload-audio" ? "audio" : "image"); toast.message("已添加上传模块,请选择本机文件"); return; }
|
||||||
|
if (action === "save") { if (!(await persistence.saveAndConfirm())) throw new Error("画布保存尚未确认,请稍后重试"); return; }
|
||||||
|
if (action === "export") {
|
||||||
|
const url = URL.createObjectURL(new Blob([JSON.stringify({ title: projectTitle, workspaceType: "video", canvasData: { nodes: serializeNodes(nodes), edges: serializeEdges(edges), viewport } }, null, 2)], { type: "application/json" }));
|
||||||
|
const link = document.createElement("a"); link.href = url; link.download = `${projectTitle}.json`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); return;
|
||||||
|
}
|
||||||
|
if (action === "import") {
|
||||||
|
const picker = document.createElement("input"); picker.type = "file"; picker.accept = ".json,application/json";
|
||||||
|
picker.onchange = async () => { try { const file = picker.files?.[0]; if (!file) return; const data = JSON.parse(await file.text()); const imported = restoreNodes(data.canvasData || data); if (!imported.length) throw new Error("文件中没有可用的视频画布节点"); if (!window.confirm("确认将文件里的节点添加到当前画布?")) return; const ids = new Map(imported.map((node) => [node.id, makeId("import")])); addNodes(imported.map((node) => ({ ...node, id: ids.get(node.id)! })), restoreEdges(data.canvasData || data).filter((edge) => ids.has(edge.source) && ids.has(edge.target)).map((edge) => ({ id: makeId("edge"), source: ids.get(edge.source)!, target: ids.get(edge.target)! }))); } catch (error) { toast.error(error instanceof Error ? error.message : "导入失败"); } }; picker.click(); return;
|
||||||
|
}
|
||||||
|
if (!target) throw new Error("请先选中具体素材节点");
|
||||||
|
if (action === "download") { downloadMediaNode(target); return; }
|
||||||
|
if (action === "preview") { setPreviewNode(target); return; }
|
||||||
|
if (action === "local-edit") { await runSelectedImageToolAction(target.id, "localEdit"); return; }
|
||||||
|
if (action === "annotate") { await runSelectedImageToolAction(target.id, "annotate"); return; }
|
||||||
|
if (action === "director") { setDirectorConsoleNodeId(target.id); return; }
|
||||||
|
if (action === "storyboard") { openStoryScriptWorkflow(target.id); return; }
|
||||||
|
if (action === "batch-storyboard" || action === "batch-video") { openStoryScriptWorkflow(target.id); toast.message("请检查分镜及费用后在工作台提交批量任务"); return; }
|
||||||
|
if (action === "video-hd") { setInspectorNodeId(target.id); toast.message("当前视频 AI 高清尚缺真实后端,不能将原视频冒充高清结果"); return; }
|
||||||
|
if (action === "video-clip") { setActiveVideoToolbarMode("clip"); return; }
|
||||||
|
if (action === "video-crop") { setActiveVideoToolbarMode("crop"); toast.message("当前裁剪导出后端尚未接入,不能当作已完成的视频裁剪"); return; }
|
||||||
|
if (action === "subtitle-erase") { setActiveVideoToolbarMode("subtitleErase"); toast.message("当前去字幕尚未接入真实处理后端"); return; }
|
||||||
|
if (["audio-split", "voice-split", "background-split", "frame-first", "frame-last", "frame-current"].includes(action)) { setPreviewNode(target); toast.message("已授权入口;当前页面此功能仍为模拟流程,Agent 不会生成占位素材或伪报完成"); return; }
|
||||||
|
throw new Error("此入口需要在相应的视频工作区打开");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="video-canvas-workspace fixed inset-0 h-dvh w-full overflow-clip bg-[#151515] text-white"
|
className="video-canvas-workspace fixed inset-0 h-dvh w-full overflow-clip bg-[#151515] text-white"
|
||||||
style={{fontFamily:'-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif', "--spacing":"4px"} as CSSProperties}
|
style={{fontFamily:'-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif', "--spacing":"4px", width: activePanel === "tvstar" && tvstarDocked ? `calc(100vw - ${tvstarDockWidth}px)` : undefined} as CSSProperties}
|
||||||
onContextMenu={openCanvasCommand}
|
onContextMenu={openCanvasCommand}
|
||||||
onDoubleClick={openCanvasCommand}
|
onDoubleClick={openCanvasCommand}
|
||||||
onPointerDown={startCanvasDrag}
|
onPointerDown={startCanvasDrag}
|
||||||
@ -10574,6 +11054,7 @@ export function LiblibVideoCanvasReplica({
|
|||||||
void addUploadedFilesAtPoint(files, toCanvasPoint(event.clientX, event.clientY));
|
void addUploadedFilesAtPoint(files, toCanvasPoint(event.clientX, event.clientY));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<CanvasAgentUiListener projectId={canvasId} workspace="video" onVideoAction={handleAgentVideoUiCommand} />
|
||||||
<div className="pointer-events-none absolute inset-0" style={{backgroundImage:"radial-gradient(circle,rgba(255,255,255,0.14) 0.7px,transparent 0.7px)",backgroundPosition:"0.5px 0.5px",backgroundSize:"16px 16px"}} />
|
<div className="pointer-events-none absolute inset-0" style={{backgroundImage:"radial-gradient(circle,rgba(255,255,255,0.14) 0.7px,transparent 0.7px)",backgroundPosition:"0.5px 0.5px",backgroundSize:"16px 16px"}} />
|
||||||
{fileDragActive && (
|
{fileDragActive && (
|
||||||
<div className="pointer-events-none absolute inset-3 z-[1800] flex items-center justify-center rounded-2xl border-2 border-dashed border-cyan-300 bg-cyan-300/5" role="status" aria-live="polite">
|
<div className="pointer-events-none absolute inset-3 z-[1800] flex items-center justify-center rounded-2xl border-2 border-dashed border-cyan-300 bg-cyan-300/5" role="status" aria-live="polite">
|
||||||
@ -11462,6 +11943,29 @@ export function LiblibVideoCanvasReplica({
|
|||||||
onResolve={persistence.resolveConflict}
|
onResolve={persistence.resolveConflict}
|
||||||
onDownload={persistence.downloadDraft}
|
onDownload={persistence.downloadDraft}
|
||||||
/>
|
/>
|
||||||
|
{ZCODE_VIDEO_CANVAS_AUTHORIZED && (isVideoAgentOpen ? (
|
||||||
|
<VideoCanvasAgentPanel
|
||||||
|
key={canvasId}
|
||||||
|
projectId={canvasId}
|
||||||
|
selectedNodeIds={selectedNodeId ? [selectedNodeId] : []}
|
||||||
|
videoModels={canvasModelOptions.filter((model) => isVideoModelDescriptor(model))}
|
||||||
|
imageModels={canvasModelOptions.filter((model) => isImageGenerationModelDescriptor(model))}
|
||||||
|
beforeSend={saveBeforeVideoAgent}
|
||||||
|
onResults={(projectId, ids) => void refreshVideoAgentResults(projectId, ids)}
|
||||||
|
onClose={() => setIsVideoAgentOpen(false)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-canvas-overlay="true"
|
||||||
|
onClick={() => { setInspectorNodeId(null); setIsVideoAgentOpen(true); }}
|
||||||
|
className="absolute right-4 top-[76px] z-40 flex items-center gap-2 rounded-xl border border-white/10 bg-[#252525] px-4 py-3 text-sm text-white shadow-lg hover:bg-[#303030]"
|
||||||
|
aria-label="打开视频创作 Agent"
|
||||||
|
>
|
||||||
|
<FileText className="h-4 w-4" />视频 Agent
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
<TopBar
|
<TopBar
|
||||||
canvasId={canvasId}
|
canvasId={canvasId}
|
||||||
canvasViewMode={canvasViewMode}
|
canvasViewMode={canvasViewMode}
|
||||||
@ -11519,6 +12023,48 @@ export function LiblibVideoCanvasReplica({
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{activePanel === "tvstar" ? (
|
||||||
|
<TVstarPanel
|
||||||
|
canvasId={canvasId}
|
||||||
|
models={tvstarModels}
|
||||||
|
generationModels={tvstarGenerationModels}
|
||||||
|
tasks={generationTasks.tasks}
|
||||||
|
references={tvstarReferences}
|
||||||
|
canvasNodes={tvstarCanvasNodes}
|
||||||
|
selectedCanvasNode={tvstarCanvasNodes.find(item => item.id === selectedNodeId) || null}
|
||||||
|
onApply={applyTVstarShots}
|
||||||
|
onPrepare={(shots, goal, references, selection) => applyTVstarShots(shots, goal, references, selection, "prepare")}
|
||||||
|
onRunPrepared={runPreparedTVstarGroup}
|
||||||
|
onEdit={applyTVstarEdit}
|
||||||
|
onClose={() => setActivePanel(null)}
|
||||||
|
onOpenPlugin={() => window.open("/tvstar/plugin", "_blank", "noopener,noreferrer")}
|
||||||
|
docked={tvstarDocked}
|
||||||
|
dockWidth={tvstarDockWidth}
|
||||||
|
onDockChange={(value) => { setTvstarDocked(value); try { localStorage.setItem(`tvstar:docked:${canvasId}`, value ? "1" : "0"); } catch { /* optional */ } }}
|
||||||
|
onDockWidthChange={(value) => { setTvstarDockWidth(value); try { localStorage.setItem(`tvstar:dock-width:${canvasId}`, String(value)); } catch { /* optional */ } }}
|
||||||
|
onUpload={async file => {
|
||||||
|
const uploaded = await uploadCanvasMediaFile(file);
|
||||||
|
if (uploaded.mediaType !== "image" && uploaded.mediaType !== "video") throw new Error("请选择图片或视频素材");
|
||||||
|
return { url: uploaded.url, type: uploaded.mediaType, duration: uploaded.duration };
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{activePanel === "characterStudio" ? (
|
||||||
|
<CharacterStudioPanel
|
||||||
|
canvasId={canvasId}
|
||||||
|
models={tvstarModels}
|
||||||
|
onApply={applyCharacterStudio}
|
||||||
|
onClose={() => setActivePanel(null)}
|
||||||
|
onOpenLibrary={() => setActivePanel("roleLibrary")}
|
||||||
|
onUpload={async file => {
|
||||||
|
const uploaded = await uploadCanvasMediaFile(file);
|
||||||
|
if (uploaded.mediaType !== "image") throw new Error("请选择图片参考素材");
|
||||||
|
return uploaded.url;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<ZoomDock
|
<ZoomDock
|
||||||
assetManagerOpen={activePanel === "assetManager"}
|
assetManagerOpen={activePanel === "assetManager"}
|
||||||
assetManagerWidth={assetManagerWidth}
|
assetManagerWidth={assetManagerWidth}
|
||||||
@ -12318,6 +12864,22 @@ function LeftToolbar({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
<div className="group absolute left-[calc(100%+10px)] top-1/2 -translate-y-1/2">
|
||||||
|
<button
|
||||||
|
aria-label="TVstar"
|
||||||
|
aria-pressed={activePanel === "tvstar"}
|
||||||
|
className={cn("flex size-12 items-center justify-center rounded-full border border-white/10 bg-[#292929] shadow-[0_8px_24px_rgba(0,0,0,.4)] transition-transform hover:scale-105", activePanel === "tvstar" && "ring-2 ring-cyan-300/40")}
|
||||||
|
onClick={() => onOpen("tvstar")}
|
||||||
|
title="TVstar"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<span className="relative block size-7 overflow-hidden rounded-full border border-cyan-100/60 bg-[radial-gradient(circle_at_35%_32%,#8df9f2_0%,#39dce9_24%,#579cff_53%,#7259d6_78%,#2a647c_100%)] shadow-[0_0_13px_rgba(90,206,245,.72),inset_-3px_-3px_8px_rgba(15,34,99,.45)]">
|
||||||
|
<span className="absolute inset-0 rounded-full bg-[radial-gradient(ellipse_at_70%_72%,rgba(85,255,207,.8),transparent_38%)]" />
|
||||||
|
<span className="absolute left-[18%] top-[13%] h-[22%] w-[30%] -rotate-25 rounded-full bg-white/55 blur-[3px]" />
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
<span className="pointer-events-none absolute bottom-[calc(100%+9px)] left-1/2 -translate-x-1/2 whitespace-nowrap rounded-lg border border-white/10 bg-[#151515] px-2 py-1 text-xs text-white opacity-0 shadow-lg transition-opacity group-hover:opacity-100">TVstar</span>
|
||||||
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -14544,7 +15106,7 @@ function DirectorNodeComposer({
|
|||||||
if(file.size>20*1024*1024){setError("参考图需小于 20 MiB");return;}
|
if(file.size>20*1024*1024){setError("参考图需小于 20 MiB");return;}
|
||||||
setBusy(true);setError("");try{
|
setBusy(true);setError("");try{
|
||||||
const form=new FormData();form.append("file",file);form.append("purpose","director-studio");
|
const form=new FormData();form.append("file",file);form.append("purpose","director-studio");
|
||||||
const response=await fetch("/api/files/upload",{method:"POST",body:form,signal:AbortSignal.timeout(120000)});
|
const response=await fetchUploadWithRetry(form,{signal:AbortSignal.timeout(120000)});
|
||||||
const result=await response.json();const url=result.url||result.data?.url;
|
const result=await response.json();const url=result.url||result.data?.url;
|
||||||
if(!response.ok||!url)throw new Error(result.error||"图片上传失败");
|
if(!response.ok||!url)throw new Error(result.error||"图片上传失败");
|
||||||
onDraft({directorReferenceUrl:String(url)});
|
onDraft({directorReferenceUrl:String(url)});
|
||||||
@ -15065,7 +15627,8 @@ function VideoTargetModuleComposer({
|
|||||||
const ratio = supported.ratios.length && !supported.ratios.includes(normalizeVideoRatioValue(current.ratio)) ? supported.ratios[0] : current.ratio;
|
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 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 resolution = executableResolutions.length && !executableResolutions.includes(normalizeVideoResolutionValue(current.resolution)) ? executableResolutions[0].toUpperCase() : current.resolution;
|
||||||
const duration = supported.durations.length && !supported.durations.includes(normalizeVideoDurationValue(current.duration)) ? `${supported.durations[0]}s` : current.duration;
|
const durations = getCanvasVideoParameters(target, activeMode, resolution || "720P").durations;
|
||||||
|
const duration = durations.length && !durations.includes(normalizeVideoDurationValue(current.duration)) ? `${durations[0]}s` : current.duration;
|
||||||
const audio = supported.supportsAudio ? current.audio : "关闭";
|
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};
|
return ratio === current.ratio && resolution === current.resolution && duration === current.duration && audio === current.audio ? current : {...current, ratio, resolution, duration, audio};
|
||||||
});
|
});
|
||||||
@ -17368,7 +17931,7 @@ function VideoParameterEditor({
|
|||||||
const candidates = filterCanvasModels(modelOptions, audioRequired ? "audio-video" : "video", mode);
|
const candidates = filterCanvasModels(modelOptions, audioRequired ? "audio-video" : "video", mode);
|
||||||
const model = candidates.find(item => item.id === settings.model || item.modelId === settings.model) ||
|
const model = candidates.find(item => item.id === settings.model || item.modelId === settings.model) ||
|
||||||
(!normalizeModelRef(settings.model) || settings.model === "auto" ? candidates[0] : undefined);
|
(!normalizeModelRef(settings.model) || settings.model === "auto" ? candidates[0] : undefined);
|
||||||
const options = getCanvasVideoParameters(model, mode);
|
const options = getCanvasVideoParameters(model, mode, settings.resolution || "720P");
|
||||||
const executableResolutions = options.resolutions.filter(value => ["480p", "720p", "1080p"].includes(value.toLowerCase())).map(value => value.toUpperCase());
|
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)));
|
const durationIndex = Math.max(0, options.durations.indexOf(normalizeVideoDurationValue(settings.duration)));
|
||||||
return (
|
return (
|
||||||
@ -20278,8 +20841,18 @@ function PresetMediaCanvasNode({
|
|||||||
</div>
|
</div>
|
||||||
) : mediaType === "audio" ? (
|
) : mediaType === "audio" ? (
|
||||||
<div className="relative h-[calc(100%-32px)]">
|
<div className="relative h-[calc(100%-32px)]">
|
||||||
<OfficialAudioCard durationSeconds={getDraftNumber(node, "durationSeconds", 3)} mediaUrl={mediaUrl} selected={selected} />
|
{isGenerating || isGenerationFailed ? (
|
||||||
{!generated ? (
|
<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 ? (
|
||||||
<button
|
<button
|
||||||
aria-label={mediaUrl ? "替换音频" : "上传音频"}
|
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"
|
className="absolute right-3 top-3 flex h-9 w-9 items-center justify-center rounded-[8px] bg-black/56 text-white/90"
|
||||||
@ -20825,12 +21398,14 @@ function GenerationPendingPreview({
|
|||||||
previewUrl,
|
previewUrl,
|
||||||
progress,
|
progress,
|
||||||
status,
|
status,
|
||||||
|
statusLabel,
|
||||||
}: {
|
}: {
|
||||||
errorMessage?: string;
|
errorMessage?: string;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
previewUrl?: string;
|
previewUrl?: string;
|
||||||
progress: number;
|
progress: number;
|
||||||
status: string;
|
status: string;
|
||||||
|
statusLabel?: string;
|
||||||
}) {
|
}) {
|
||||||
const displayProgress = Math.max(2, Math.min(99, Math.round(progress)));
|
const displayProgress = Math.max(2, Math.min(99, Math.round(progress)));
|
||||||
const failed = status === "failed";
|
const failed = status === "failed";
|
||||||
@ -20876,7 +21451,7 @@ function GenerationPendingPreview({
|
|||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<span>生成中 {displayProgress}%...</span>
|
<span>{statusLabel || `生成中 ${displayProgress}%...`}</span>
|
||||||
<button
|
<button
|
||||||
className="font-medium text-white/42 transition hover:text-white/80"
|
className="font-medium text-white/42 transition hover:text-white/80"
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
@ -20904,11 +21479,7 @@ function PureTextResourceCanvasNode({
|
|||||||
onTextResourceChange: (content: string) => void;
|
onTextResourceChange: (content: string) => void;
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
}) {
|
}) {
|
||||||
const contentValues = node.draftValues?.content;
|
const textContent = restoreTextResourceContent(node.draftValues)[0] || "";
|
||||||
const textContent =
|
|
||||||
Array.isArray(contentValues) && typeof contentValues[0] === "string"
|
|
||||||
? contentValues[0]
|
|
||||||
: "";
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-full w-full">
|
<div className="h-full w-full">
|
||||||
@ -21274,8 +21845,8 @@ const STYLE_MARKET_CATEGORIES = [
|
|||||||
"全部",
|
"全部",
|
||||||
];
|
];
|
||||||
|
|
||||||
const STYLE_MARKET_THUMBNAIL_URL = "https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-character-three-view-cover.png";
|
const STYLE_MARKET_THUMBNAIL_URL = "https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-character-three-view-cover.png";
|
||||||
const EFFECT_MARKET_THUMBNAIL_URL = "https://demo-sparkai.oss-cn-shanghai.aliyuncs.com/video-canvas-demo/starter-first-frame-video-cover.png";
|
const EFFECT_MARKET_THUMBNAIL_URL = "https://scqnycdn.jiansun.vip/legacy-oss/demo-sparkai/video-canvas-demo/starter-first-frame-video-cover.png";
|
||||||
|
|
||||||
const STYLE_MARKET_CARDS: AssetMarketCard[] = [
|
const STYLE_MARKET_CARDS: AssetMarketCard[] = [
|
||||||
["复古马卡龙", "算力潮汐", 177],
|
["复古马卡龙", "算力潮汐", 177],
|
||||||
@ -23554,14 +24125,12 @@ function SkillsAccessModal({
|
|||||||
<h2 className="text-[15px] font-semibold leading-none text-white">我的Access key</h2>
|
<h2 className="text-[15px] font-semibold leading-none text-white">我的Access key</h2>
|
||||||
<div className="mt-5 space-y-2 text-[13px] leading-none text-white/76">
|
<div className="mt-5 space-y-2 text-[13px] leading-none text-white/76">
|
||||||
<p>· Access key 仅用于 {skillsName} 的调用授权使用,一旦传播给他人,有账号泄露的风险,请谨慎保管!</p>
|
<p>· Access key 仅用于 {skillsName} 的调用授权使用,一旦传播给他人,有账号泄露的风险,请谨慎保管!</p>
|
||||||
<p>· {skillsName} 是 {siteName} 提供给 agent 使用的入口,可在 openclaw 中调用,完成专业视频创作。</p>
|
<p>· {skillsName} 可授权 Agent 读取和操作画布节点;视频生成仍需通过画布任务执行。</p>
|
||||||
<p>
|
<p>
|
||||||
· 安装使用请戳
|
· 安装使用请戳
|
||||||
<button
|
<button
|
||||||
className="ml-1 text-[#2f8bff] underline-offset-2 hover:underline"
|
className="ml-1 text-[#2f8bff] underline-offset-2 hover:underline"
|
||||||
onClick={() =>
|
onClick={() => window.open("/tvstar/plugin", "_blank", "noopener,noreferrer")}
|
||||||
toast.info("安装包位于 integrations/openclaw,可通过 STDIO MCP 接入。")
|
|
||||||
}
|
|
||||||
type="button"
|
type="button"
|
||||||
>
|
>
|
||||||
接口文档
|
接口文档
|
||||||
|
|||||||
452
components/canvas/ReferenceImageToolbar.tsx
Normal file
452
components/canvas/ReferenceImageToolbar.tsx
Normal file
@ -0,0 +1,452 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ChevronRight, X } from "lucide-react";
|
||||||
|
import {
|
||||||
|
Children,
|
||||||
|
cloneElement,
|
||||||
|
forwardRef,
|
||||||
|
isValidElement,
|
||||||
|
useState,
|
||||||
|
type HTMLAttributes,
|
||||||
|
type MouseEvent,
|
||||||
|
type ReactElement,
|
||||||
|
type ReactNode,
|
||||||
|
} from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { ReferenceIcon } from "@/components/lovart/reference-icon";
|
||||||
|
import { CanvasToolbarIcon } from "@/components/canvas/CanvasToolbarIcon";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/components/ui/tooltip";
|
||||||
|
import {
|
||||||
|
saveImageToolbarPreferences,
|
||||||
|
useImageToolbarPreferences,
|
||||||
|
type ImageToolbarPreferences,
|
||||||
|
} from "@/lib/canvas-image-toolbar-preferences";
|
||||||
|
|
||||||
|
type ToolProps = HTMLAttributes<HTMLButtonElement> & {
|
||||||
|
"data-tool-key"?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
children?: ReactNode;
|
||||||
|
};
|
||||||
|
type Tool = ReactElement<ToolProps>;
|
||||||
|
type Props = HTMLAttributes<HTMLDivElement> & {
|
||||||
|
referencePresentation: boolean;
|
||||||
|
defaultPinnedKeys: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function toolLabel(tool: Tool) {
|
||||||
|
return tool.props.title || "";
|
||||||
|
}
|
||||||
|
function toolIcon(tool: Tool, size: number) {
|
||||||
|
const icon = Children.toArray(tool.props.children).find(isValidElement);
|
||||||
|
if (
|
||||||
|
!isValidElement<{
|
||||||
|
className?: string;
|
||||||
|
style?: object;
|
||||||
|
referenceSize?: number;
|
||||||
|
}>(icon)
|
||||||
|
)
|
||||||
|
return null;
|
||||||
|
return cloneElement(icon, {
|
||||||
|
className: "shrink-0",
|
||||||
|
style: { width: size, height: size },
|
||||||
|
...(icon.type === CanvasToolbarIcon ? { referenceSize: size } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function toolCredit(tool: Tool) {
|
||||||
|
return Children.toArray(tool.props.children).find(
|
||||||
|
(child) =>
|
||||||
|
isValidElement<{ compact?: boolean; label?: string }>(child) &&
|
||||||
|
child.props.compact &&
|
||||||
|
child.props.label
|
||||||
|
) as
|
||||||
|
| ReactElement<{ compact?: boolean; label?: string; className?: string }>
|
||||||
|
| undefined;
|
||||||
|
}
|
||||||
|
function tooltipButton(tool: Tool, showNames: boolean) {
|
||||||
|
const name = toolLabel(tool);
|
||||||
|
// Clone the existing action so its handler, busy state and administrator icon override remain intact.
|
||||||
|
const button = cloneElement(tool, {
|
||||||
|
title: undefined,
|
||||||
|
"aria-label": name,
|
||||||
|
children: (
|
||||||
|
<>
|
||||||
|
{toolIcon(tool, 25)}
|
||||||
|
{showNames && <span className="lovart-image-tool-label">{name}</span>}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<Tooltip key={tool.props["data-tool-key"] || name}>
|
||||||
|
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
className="lovart-image-tool-tooltip"
|
||||||
|
side="top"
|
||||||
|
sideOffset={8}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
{toolCredit(tool) &&
|
||||||
|
cloneElement(toolCredit(tool)!, {
|
||||||
|
compact: false,
|
||||||
|
className: "lovart-image-tool-cost",
|
||||||
|
})}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ReferenceImageToolbar = forwardRef<HTMLDivElement, Props>(
|
||||||
|
function ReferenceImageToolbar(
|
||||||
|
{ referencePresentation, defaultPinnedKeys, children, ...rootProps },
|
||||||
|
ref
|
||||||
|
) {
|
||||||
|
const saved = useImageToolbarPreferences();
|
||||||
|
const [draft, setDraft] = useState<ImageToolbarPreferences | null>(null);
|
||||||
|
const [draggedKey, setDraggedKey] = useState<string | null>(null);
|
||||||
|
const elements = Children.toArray(children).filter(
|
||||||
|
isValidElement
|
||||||
|
) as ReactElement<ToolProps>[];
|
||||||
|
const tools = elements.filter(
|
||||||
|
(element) =>
|
||||||
|
element.props["data-tool-key"] &&
|
||||||
|
!["addToChat", "download"].includes(element.props["data-tool-key"]!)
|
||||||
|
);
|
||||||
|
const toolMap = new Map(
|
||||||
|
tools.map((tool) => [tool.props["data-tool-key"]!, tool])
|
||||||
|
);
|
||||||
|
const preferences = saved || {
|
||||||
|
pinnedKeys: defaultPinnedKeys,
|
||||||
|
showNames: false,
|
||||||
|
};
|
||||||
|
const pinned = preferences.pinnedKeys.filter((key) => toolMap.has(key));
|
||||||
|
const moreTools = tools.filter(
|
||||||
|
(tool) => !pinned.includes(tool.props["data-tool-key"]!)
|
||||||
|
);
|
||||||
|
const addToChat = elements.find(
|
||||||
|
(element) => element.props["data-tool-key"] === "addToChat"
|
||||||
|
);
|
||||||
|
const download = elements.find(
|
||||||
|
(element) => element.props["data-tool-key"] === "download"
|
||||||
|
);
|
||||||
|
const originalMenu = elements.find(
|
||||||
|
(element) => element.type === DropdownMenu
|
||||||
|
);
|
||||||
|
const menuChildren = originalMenu
|
||||||
|
? (Children.toArray(originalMenu.props.children).filter(
|
||||||
|
isValidElement
|
||||||
|
) as ReactElement<{ children?: ReactNode }>[])
|
||||||
|
: [];
|
||||||
|
const menuTrigger = menuChildren.find(
|
||||||
|
(element) => element.type === DropdownMenuTrigger
|
||||||
|
);
|
||||||
|
const moreButton =
|
||||||
|
menuTrigger &&
|
||||||
|
(Children.toArray(menuTrigger.props.children).find(isValidElement) as
|
||||||
|
| Tool
|
||||||
|
| undefined);
|
||||||
|
const extras = menuChildren.find(
|
||||||
|
(element) => element.type === DropdownMenuContent
|
||||||
|
)?.props.children;
|
||||||
|
const openCustomizer = () =>
|
||||||
|
setDraft({
|
||||||
|
pinnedKeys: [...preferences.pinnedKeys],
|
||||||
|
showNames: preferences.showNames,
|
||||||
|
});
|
||||||
|
const toggle = (key: string) =>
|
||||||
|
setDraft((current) =>
|
||||||
|
current
|
||||||
|
? {
|
||||||
|
...current,
|
||||||
|
pinnedKeys: current.pinnedKeys.includes(key)
|
||||||
|
? current.pinnedKeys.filter((item) => item !== key)
|
||||||
|
: [...current.pinnedKeys, key],
|
||||||
|
}
|
||||||
|
: current
|
||||||
|
);
|
||||||
|
const move = (key: string, target: string) =>
|
||||||
|
setDraft((current) => {
|
||||||
|
if (!current || key === target) return current;
|
||||||
|
const next = [...current.pinnedKeys];
|
||||||
|
const from = next.indexOf(key),
|
||||||
|
to = next.indexOf(target);
|
||||||
|
if (from < 0 || to < 0) return current;
|
||||||
|
next.splice(from, 1);
|
||||||
|
next.splice(to, 0, key);
|
||||||
|
return { ...current, pinnedKeys: next };
|
||||||
|
});
|
||||||
|
if (!referencePresentation)
|
||||||
|
return (
|
||||||
|
<div {...rootProps} ref={ref}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
{...rootProps}
|
||||||
|
ref={ref}
|
||||||
|
style={{ ...rootProps.style, overflowX: "auto" }}
|
||||||
|
data-show-tool-names={preferences.showNames ? "true" : "false"}
|
||||||
|
>
|
||||||
|
{addToChat && tooltipButton(addToChat, preferences.showNames)}
|
||||||
|
{addToChat && <div className="w-px" />}
|
||||||
|
{pinned.map((key) =>
|
||||||
|
tooltipButton(toolMap.get(key)!, preferences.showNames)
|
||||||
|
)}
|
||||||
|
<DropdownMenu>
|
||||||
|
{moreButton && (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
{cloneElement(moreButton, {
|
||||||
|
title: undefined,
|
||||||
|
"aria-label": toolLabel(moreButton),
|
||||||
|
children: toolIcon(moreButton, 25),
|
||||||
|
})}
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent
|
||||||
|
className="lovart-image-tool-tooltip"
|
||||||
|
sideOffset={8}
|
||||||
|
>
|
||||||
|
{toolLabel(moreButton)}
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
<DropdownMenuContent
|
||||||
|
className="lovart-image-action-menu lovart-image-custom-more"
|
||||||
|
side="bottom"
|
||||||
|
align="end"
|
||||||
|
>
|
||||||
|
{moreTools.map((tool) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={tool.props["data-tool-key"]}
|
||||||
|
disabled={tool.props.disabled}
|
||||||
|
onClick={(event) =>
|
||||||
|
tool.props.onClick?.(
|
||||||
|
event as unknown as MouseEvent<HTMLButtonElement>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{toolIcon(tool, 18)}
|
||||||
|
<span>{toolLabel(tool)}</span>
|
||||||
|
{toolCredit(tool) &&
|
||||||
|
cloneElement(toolCredit(tool)!, {
|
||||||
|
compact: false,
|
||||||
|
className: "lovart-image-tool-cost",
|
||||||
|
})}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
{extras}
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="lovart-customize-entry"
|
||||||
|
onSelect={openCustomizer}
|
||||||
|
>
|
||||||
|
自定义工具栏
|
||||||
|
<ChevronRight size={14} />
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
{download && (
|
||||||
|
<>
|
||||||
|
<div className="w-px" />
|
||||||
|
{tooltipButton(download, preferences.showNames)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Dialog
|
||||||
|
open={Boolean(draft)}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) setDraft(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent
|
||||||
|
hideCloseButton
|
||||||
|
className="lovart-toolbar-customizer"
|
||||||
|
overlayClassName="lovart-toolbar-customizer-overlay"
|
||||||
|
onPointerDown={(event) => event.stopPropagation()}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
>
|
||||||
|
<header className="lovart-customizer-header">
|
||||||
|
<div>
|
||||||
|
<DialogTitle>自定义工具栏</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
选择你想在编辑栏中使用的工具
|
||||||
|
</DialogDescription>
|
||||||
|
</div>
|
||||||
|
<div className="lovart-customizer-header-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="恢复默认工具栏"
|
||||||
|
onClick={() =>
|
||||||
|
setDraft({
|
||||||
|
pinnedKeys: [...defaultPinnedKeys],
|
||||||
|
showNames: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="toolbar-reset" size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="关闭自定义工具栏"
|
||||||
|
onClick={() => setDraft(null)}
|
||||||
|
>
|
||||||
|
<ReferenceIcon name="toolbar-close" size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="lovart-customizer-body">
|
||||||
|
<div
|
||||||
|
className="lovart-customizer-preview"
|
||||||
|
aria-label="工具栏预览"
|
||||||
|
>
|
||||||
|
<div className="lovart-customizer-preview-bar">
|
||||||
|
{addToChat && (
|
||||||
|
<span className="lovart-preview-fixed">
|
||||||
|
{toolIcon(addToChat, 18)}
|
||||||
|
{draft?.showNames && toolLabel(addToChat)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{draft?.pinnedKeys
|
||||||
|
.filter((key) => toolMap.has(key))
|
||||||
|
.map((key, index, keys) => {
|
||||||
|
const tool = toolMap.get(key)!;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="lovart-preview-chip"
|
||||||
|
key={key}
|
||||||
|
draggable
|
||||||
|
onDragStart={(event) => {
|
||||||
|
setDraggedKey(key);
|
||||||
|
event.dataTransfer.setData("text/plain", key);
|
||||||
|
event.dataTransfer.effectAllowed = "move";
|
||||||
|
}}
|
||||||
|
onDragEnd={() => setDraggedKey(null)}
|
||||||
|
onDragOver={(event) => event.preventDefault()}
|
||||||
|
onDrop={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
if (draggedKey) move(draggedKey, key);
|
||||||
|
setDraggedKey(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="lovart-preview-handle"
|
||||||
|
aria-label={`${toolLabel(tool)},按左右方向键调整顺序`}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
const offset =
|
||||||
|
event.key === "ArrowLeft"
|
||||||
|
? -1
|
||||||
|
: event.key === "ArrowRight"
|
||||||
|
? 1
|
||||||
|
: 0;
|
||||||
|
if (offset && keys[index + offset]) {
|
||||||
|
event.preventDefault();
|
||||||
|
move(key, keys[index + offset]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{toolIcon(tool, 18)}
|
||||||
|
{draft.showNames && <span>{toolLabel(tool)}</span>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={`移除${toolLabel(tool)}`}
|
||||||
|
onClick={() => toggle(key)}
|
||||||
|
>
|
||||||
|
<X size={12} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="lovart-customizer-tools">
|
||||||
|
{tools.map((tool) => {
|
||||||
|
const key = tool.props["data-tool-key"]!;
|
||||||
|
const isPinned = Boolean(draft?.pinnedKeys.includes(key));
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
aria-label={`${isPinned ? "取消固定" : "固定"}${toolLabel(tool)}`}
|
||||||
|
aria-pressed={isPinned}
|
||||||
|
onClick={() => toggle(key)}
|
||||||
|
>
|
||||||
|
{toolIcon(tool, 18)}
|
||||||
|
<span>{toolLabel(tool)}</span>
|
||||||
|
<ReferenceIcon
|
||||||
|
name={
|
||||||
|
isPinned
|
||||||
|
? "toolbar-pin-filled"
|
||||||
|
: "toolbar-pin-outline"
|
||||||
|
}
|
||||||
|
size={13}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<footer className="lovart-customizer-footer">
|
||||||
|
<label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-label="显示工具名称"
|
||||||
|
aria-checked={Boolean(draft?.showNames)}
|
||||||
|
className="lovart-customizer-switch"
|
||||||
|
onClick={() =>
|
||||||
|
setDraft((current) =>
|
||||||
|
current
|
||||||
|
? { ...current, showNames: !current.showNames }
|
||||||
|
: current
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span />
|
||||||
|
</button>
|
||||||
|
显示工具名称
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<button type="button" onClick={() => setDraft(null)}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="lovart-customizer-save"
|
||||||
|
onClick={() => {
|
||||||
|
if (draft && saveImageToolbarPreferences(draft))
|
||||||
|
setDraft(null);
|
||||||
|
else
|
||||||
|
toast.error("无法保存工具栏设置,请检查浏览器存储权限");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
保存
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
47
components/canvas/chat-panel/canvas-agent-progress.tsx
Normal file
47
components/canvas/chat-panel/canvas-agent-progress.tsx
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
"use client";
|
||||||
|
import { CircleAlert, Check, ChevronDown, Loader2, RotateCcw, Square } from "lucide-react";
|
||||||
|
import type { AgentRunView } from "@/lib/ai/canvas-agent-runtime/protocol";
|
||||||
|
import { canvasAgentProgressLabel, type CanvasAgentProgress } from "@/lib/ai/canvas-agent-runtime/progress";
|
||||||
|
|
||||||
|
export function CanvasAgentProgressMessage(props: {
|
||||||
|
progress: CanvasAgentProgress; run?: AgentRunView | null; busy?: boolean;
|
||||||
|
stopping?: boolean; sending?: boolean; onCancel?: () => void; onResume?: () => void;
|
||||||
|
}) {
|
||||||
|
const { progress, run } = props;
|
||||||
|
const running = progress.status === "running";
|
||||||
|
const label = progress.status === "completed" ? "处理完成"
|
||||||
|
: props.stopping && running ? "正在停止后续步骤,已完成的结果会保留"
|
||||||
|
: canvasAgentProgressLabel(progress.message || "正在处理你的任务");
|
||||||
|
return (
|
||||||
|
<div className="my-2 w-full min-w-0 text-xs text-zinc-500 dark:text-zinc-400" data-testid="canvas-agent-progress" data-agent-message-id={run?.assistantMessageId}>
|
||||||
|
<div className="flex items-start gap-2">
|
||||||
|
<details className="min-w-0 flex-1" open={running}>
|
||||||
|
<summary className="flex cursor-pointer list-none items-center gap-2 py-1 [&::-webkit-details-marker]:hidden">
|
||||||
|
{running ? <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" /> : progress.status === "completed" ? <Check className="h-3.5 w-3.5 shrink-0" /> : <CircleAlert className="h-3.5 w-3.5 shrink-0" />}
|
||||||
|
<span className="min-w-0 flex-1" role="status" aria-live="polite">{label}</span>
|
||||||
|
<ChevronDown className="h-3 w-3 shrink-0" />
|
||||||
|
</summary>
|
||||||
|
{progress.activities?.length ? (
|
||||||
|
<ol className="ml-1.5 mt-1 space-y-1.5 border-l border-zinc-200 pl-4 dark:border-zinc-800" aria-label="任务执行步骤">
|
||||||
|
{progress.activities.map(activity => (
|
||||||
|
<li key={activity.id} className="flex items-center gap-2">
|
||||||
|
{activity.status === "started" ? <Loader2 className="h-3 w-3 shrink-0 animate-spin" /> : <span className="h-1 w-1 shrink-0 rounded-full bg-current" />}
|
||||||
|
<span>{canvasAgentProgressLabel(activity.title)}</span>
|
||||||
|
<span className="text-[11px] opacity-75">{activity.status === "succeeded" ? "已完成" : activity.status === "failed" ? "未完成" : activity.status === "queued" ? "待执行" : "进行中"}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
) : null}
|
||||||
|
{run?.inputs.slice(-2).map(input => (
|
||||||
|
<p key={input.id} className="mt-2 whitespace-pre-wrap break-words">{input.applied ? "已应用补充要求" : "已收到补充要求"}:{input.text}</p>
|
||||||
|
))}
|
||||||
|
</details>
|
||||||
|
{running && props.onCancel ? (
|
||||||
|
<button type="button" onClick={props.onCancel} disabled={props.sending || props.stopping} className="rounded-md p-1.5 hover:bg-zinc-100 disabled:opacity-40 dark:hover:bg-white/10" title="停止后续步骤" aria-label="停止后续步骤"><Square className="h-3.5 w-3.5" /></button>
|
||||||
|
) : run?.resumable && props.onResume ? (
|
||||||
|
<button type="button" onClick={props.onResume} disabled={props.busy} className="inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-1 hover:bg-zinc-100 disabled:opacity-40 dark:hover:bg-white/10"><RotateCcw className="h-3.5 w-3.5" />继续任务</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
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