xiaolongmr commited on
Commit
48b1e94
·
1 Parent(s): 315e369

画图页新增批量生图:一个入口 + 原地展开的多行编辑器

Browse files

- image-composer: 工具条新增「批量」入口,同一张输入卡原地展开为多行
提示词编辑器(行号 / 行内张数 stepper / @@N 语法 / # 注释 / 回车新增
行 / 粘贴多行自动拆分 / 逐行解析状态点);批量态复用现有参数 chip,
右侧显示「预计 X 积分 + N 行 · 共 M 张 · 忽略 K 行」,提交后自动收起
回单张模式,不新增页面或页签
- page: handleBatchSubmit 按总张数做积分/号池预检后,每行展开为一个
queued turn 交给现有会话队列顺序执行,结果沿用现有消息流渲染
- prompt-composer: SubmitButton 支持 testId,便于真机验证

docs/批量生图-方案.md ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 批量生图 · 产品与技术方案(v1 讨论稿)
2
+
3
+ > 状态:待拍板。本文只做设计,不含实现。
4
+ > 前置结论:**站内画图页其实已经有"一次出 N 张",缺的不是"N 张",而是"多组提示词的批处理 + 批次管理 + 打包交付"。**
5
+
6
+ ---
7
+
8
+ ## 0. 一句话结论
9
+
10
+ 把「批量生图」做成一等公民的**批次(Batch)**概念:一次提交一批「行」(每行一个提示词 + 张数 + 可选参考图),服务端并发跑成 N 个现有单图任务,前端用一张批次进度表 + 分组网格管理结果,最后支持打包下载与失败项重跑。
11
+
12
+ 技术上有两条路:
13
+
14
+ - **路线 A(前端扇出,零后端改动)**:沿用现有 `createImageGenerationTask` × N,前端记录批次分组。1 天可上线,适合先验证产品逻辑。
15
+ - **路线 B(服务端批次模型)**:照抄 `product_visual_service.py` 的"父任务 + 子项"范式,新增批次服务。跨设备、可续跑、可打包、可暂停取消,是最终形态。
16
+
17
+ 建议:**A 先跑通产品闭环,用一周验证;然后按 B 重构**(A 的 UI 与数据结构要按 B 的字段设计,避免返工)。
18
+
19
+ ---
20
+
21
+ ## 1. 先厘清:「批量」到底是哪一种
22
+
23
+ 这是产品逻辑最容易含混的地方,四种语义差别很大,做的事完全不同。
24
+
25
+ | 语义 | 描述 | 现状 |
26
+ |---|---|---|
27
+ | **A. 同提示词出多张** | 一个 prompt,要 4 张选一张 | **已实现**:输入框「张数」1~100,前端扇出 N 个任务(`image-composer.tsx:743`、`page.tsx:2374/2464`) |
28
+ | **B. 多提示词矩阵** | 20 个 prompt,每个出 2 张 = 40 张 | **缺失**,这是"批量生图"的主战场 |
29
+ | **C. 参考图批量** | 1 张参考图 × 20 个 prompt;或 20 张参考图 × 1 个 prompt | 能力上有(参考图走 edit 链路),但没有批量入口 |
30
+ | **D. 批次任务中心** | 提交后关页面去干别的,回来收图、打包、只看失败的 | **部分缺失**:任务在服务端照跑,但图片只存浏览器 IndexedDB,换设备/清缓存就没了 |
31
+
32
+ **建议把 B 做核心、C 作为 B 的一个维度、D 作为 B 的交付形态**。A 不用动。
33
+
34
+ ---
35
+
36
+ ## 2. 现状盘点:哪些家底可以直接用
37
+
38
+ 摸过一遍代码,结论是**能复用的比想象中多**,真正要新建的只有"批次编排"和"交付层"。
39
+
40
+ ### 2.1 已经具备的能力(不要重造)
41
+
42
+ | 能力 | 位置 | 说明 |
43
+ |---|---|---|
44
+ | 单图异步任务接口 | `POST /api/image-tasks/generations`、`/edits`(`api/image_tasks.py:274/305`) | 请求体无 `n`,恒定单张 |
45
+ | 任务轮询(支持批量 id) | `GET /api/image-tasks?ids=a,b,c`(`api/image_tasks.py:266`) | 前端已经在批拉(`api.ts:1838`) |
46
+ | 任务状态机 | `queued / running / success / error`(`image_task_service.py:28-33`) | 简单清晰,够用 |
47
+ | 任务持久化 | SQLite `image_tasks` 表,路径走 `sqlite_mirror_service.runtime_file` | **已经吃到 HF 存储桶**,重启不丢 |
48
+ | 重启保护 | `_recover_unfinished_locked`:未完成 → error + 自动退款 | 批量也不会丢钱 |
49
+ | 逐张计费 | 每任务 `reserve_credits` → 终态 `consume` / `refund` | **逐张粒度天然支持"部分失败自动退"** |
50
+ | 第三方专属钱包 | `third_party_wallet_*` 按成功张数结算 | 同上 |
51
+ | 并发控制 | 号池每账号并发 3(`config.image_account_concurrency`);第三方每连接并发 5 | 批量提交多个任务即自动生效 |
52
+ | 内容审核 | `filter_or_log` → `content_filter.check_request`,提交前调用 | 批量的每一行各调一次即可 |
53
+ | 父任务 + 子项范式 | `services/product_visual_service.py`:`ThreadPoolExecutor(max(2,min(12,len)))`、子项状态聚合、单张重试、并发/串行两种模式 | **直接照抄结构**,这是最大的省力点 |
54
+ | 图片库与批量下载 | `app/image-manager`:多选、`downloadImages(paths)`、批量删除 | 打包导出的交互可借鉴 |
55
+
56
+ ### 2.2 关键约束(设计的边界条件)
57
+
58
+ 1. **图片默认只存浏览器**:`store/image-conversations.ts` 用 IndexedDB(localforage)存会话与 blob;服务端只存任务记录。→ 批量结果的"交付"必须决定:留在浏览器,还是推到服务端图片库。
59
+ 2. **没有全局并发上限**:`_submit` 每张起一个 daemon 线程,靠号池 `wait_for_slot` 阻塞。批量 100 张会瞬间起 100 个线程。→ 批次层必须自己加线程池。
60
+ 3. **没有取消能力**:全 image 链路无 AbortController。任务一旦提交,上游请求无法中断,只能"不再等待"。
61
+ 4. **部分成功**:通用积分预扣是"整任务成功即全额 consume / 失败即全额 refund",不区分部分。→ 批量必须拆成 N 次独立预扣(现有前端扇出正好符合,不要改成"一次预扣 N 张")。
62
+ 5. **超时挂起**:带 conversation_id 的超时任务会**暂不结算**、等 `resume-poll` 再定终态。→ 批次聚合时不能把"挂起中"当失败。
63
+ 6. **`_cleanup_locked` 有死代码 bug**(`image_task_service.py:1630` 附近引用未定义的 `_settle_credit_locked` / `TASK_STATUS_COMPLETED`,被 except 吞掉)→ 结果就是**过期终态任务永远不清理**。批量上线后任务量成倍增长,要先修这个。
64
+
65
+ ---
66
+
67
+ ## 3. 产品逻辑:要有什么功能
68
+
69
+ ### 3.1 核心概念(三层结构)
70
+
71
+ ```
72
+ 批次 Batch(一次提交,一个"活")
73
+ └── 行 Row / 子项(一个提示词 + 参数 + 张数)
74
+ └── 张 Image(一个真实任务,一个 image_task)
75
+ ```
76
+
77
+ 用户视角:**一个批次 = 一个可命名、可查看进度、可打包下载的工作单元。** 而不是"一堆散落在会话里的图"。
78
+
79
+ ### 3.2 输入(怎么做批量的"批")
80
+
81
+ | 方式 | 说明 | 优先级 |
82
+ |---|---|---|
83
+ | 多行文本 | 一行一个提示词,空行忽略,支持 `#` 注释行 | P0 |
84
+ | 行内指定张数 | 语法如 `提示词@@3`(不写则用全局张数) | P1 |
85
+ | CSV / Excel 导入 | 列:prompt、张数、比例、模型、参考图 | P1 |
86
+ | 参考图集 | 多选参考图 → 每张参考图 × 每个提示词的笛卡尔积 | P2 |
87
+ | 从已有图"再来一版" | 图片库多选 → 批量重跑/批量微调 | P2 |
88
+
89
+ 配套:**参数分两层**——全局默认(模型 / 比例 / 质量 / 号池策略 / 每行张数)+ 行级覆盖。批量功能不能让用户"每行都填一遍参数"。
90
+
91
+ ### 3.3 提交前(把错误挡在产生费用之前)
92
+
93
+ 1. **总量预检**:总张数 = Σ(行张数),预估积分 = 总张数 × 单价。余额不足直接拦住并提示差多少。
94
+ 2. **逐行过审**:每行各自调一次内容审核,被拦的行**标红但不阻塞整批**,用户可以选择"跳过这些行继续"。
95
+ 3. **重复行提示**:同一提示词的重复行给个提示(允许继续,只是提醒)。
96
+ 4. **二次确认**:显示"共 42 张,预计消耗 84 积分",确认后提交。
97
+
98
+ ### 3.4 运行中
99
+
100
+ | 功能 | 说明 | 优先级 |
101
+ |---|---|---|
102
+ | 进度总览 | 完成 / 进行中 / 排队 / 失败 / 已跳过,一眼看完 | P0 |
103
+ | 分组网格 | 按行分组展示,每行显示它的 N 张 | P0 |
104
+ | 并发上限 | 默认 3(对齐号池每账号并发),可调 1~10 | P0 |
105
+ | 单张重试 | 复用现有"重新生成这一张" | P0 |
106
+ | 失败批量重试 | 一键重跑所有失败张 | P1 |
107
+ | 暂停 / 恢复 | 暂停 = 不再提交新的子任务(已在跑的无法中断,要说清) | P1 |
108
+ | 取消批次 | 同上:标记取消,未开始的直接作废并退款 | P1 |
109
+ | 自动重试 | 失败且属于"可重试错误"(换号失败等)自动重试 1~2 次 | P2 |
110
+ | 关闭页面继续跑 | 服务端任务本来就在跑;前端刷新后按 batch_id 恢复视图 | P0(靠 B 路线) |
111
+
112
+ ### 3.5 结果与交付
113
+
114
+ | 功能 | 说明 | 优先级 |
115
+ |---|---|---|
116
+ | 打包下载 | 一键 zip,命名 `001-提示词前12字.png`,失败项附 `failures.txt` | P0 |
117
+ | 服务端留档 | 结果入图片库(`image-manager`),跨设备可见、可清缓存不丢 | P1 |
118
+ | 批次记录 | 批次列表:名称、时间、张数、成功/失败、总消耗积分 | P1 |
119
+ | 导出清单 | 导出 CSV:prompt / 张数 / 状态 / 图片路径 / 消耗 | P2 |
120
+ | 成本报表 | 批次级消耗汇总(可与已有 `credit_ledger` 打通) | P2 |
121
+
122
+ ### 3.6 明确不做(v1 边界)
123
+
124
+ - 不做"任务优先级插队"(号池是共享的,插队容易把别人饿死)。
125
+ - 不做"定时/周期批量"(那是自动化,另立项)。
126
+ - 不做"上游请求中断"(技术上做不到,只能停止等待)。
127
+
128
+ ---
129
+
130
+ ## 4. 关键设计决策(含建议)
131
+
132
+ | # | 决策点 | 选项 | 建议 |
133
+ |---|---|---|---|
134
+ | 1 | 批次跑在哪 | 纯前端扇出 / 服务端父任务 | **服务端**(跨设备、可续跑、可打包) |
135
+ | 2 | 计费粒度 | 一次预扣 N 张 / 每张独立预扣 | **每张独立**(天然支持部分退款,不用改计费代码) |
136
+ | 3 | 图片留档 | 浏览器 IndexedDB / 服务端图片库 | **服务端**;至少批次结果要服务端留档 |
137
+ | 4 | 批次并发 | 无限 / 固定上限 | **默认 3,可调 1~10**(对齐 `image_account_concurrency`) |
138
+ | 5 | 取消语义 | 真取消 / 停止等待 | **停止等待**(已在跑的任务让它跑完,只影响未提交的) |
139
+ | 6 | 审核失败的行 | 整批拒绝 / 跳过该行 | **跳过该行**并标记,不阻塞其他行 |
140
+ | 7 | 与"会话"的关系 | 批次进会话历史 / 独立批次中心 | **独立批次中心**;图片可选"收藏进会话" |
141
+
142
+ ---
143
+
144
+ ## 5. 实现方案(路线 B)
145
+
146
+ ### 5.1 数据模型(复用现有 SQLite 机制)
147
+
148
+ 两个新表,走 `sqlite_mirror_service.runtime_file(DATA_DIR, "image_batches.db")`(**必须走 runtime_file,否则 HF 重建即丢**)。
149
+
150
+ ```sql
151
+ -- 批次表
152
+ CREATE TABLE image_batches (
153
+ batch_id TEXT PRIMARY KEY,
154
+ owner_id TEXT NOT NULL,
155
+ title TEXT,
156
+ status TEXT, -- queued | running | success | partial | error | cancelled
157
+ total_count INTEGER, -- 计划总张数
158
+ success_count INTEGER,
159
+ failed_count INTEGER,
160
+ skipped_count INTEGER,
161
+ concurrency INTEGER,
162
+ defaults TEXT, -- JSON:模型/比例/质量/号池策略
163
+ created_at TEXT, updated_at TEXT
164
+ );
165
+
166
+ -- 批次子项(行)
167
+ CREATE TABLE image_batch_items (
168
+ batch_id TEXT,
169
+ seq INTEGER, -- 行号(1 起)
170
+ prompt TEXT,
171
+ count INTEGER, -- 该行张数
172
+ overrides TEXT, -- JSON:行级参数覆盖
173
+ status TEXT, -- pending | queued | running | success | error | skipped
174
+ task_ids TEXT, -- JSON:该行展开的 image_task id 列表
175
+ error TEXT,
176
+ PRIMARY KEY (batch_id, seq)
177
+ );
178
+ ```
179
+
180
+ **复用而非新建**:每张图仍然是 `image_task_service` 的一个普通任务(`client_task_id = f"{batch_id}:{seq}:{index}"`,保证幂等键唯一),批次表只做"分组 + 聚合",不复制任务数据。
181
+
182
+ ### 5.2 接口(新增)
183
+
184
+ ```
185
+ POST /api/image-batches 提交批次(含行列表)→ 返回 batch_id
186
+ GET /api/image-batches?ids= 批次聚合进度(含每行状态、每张任务态)
187
+ POST /api/image-batches/{id}/retry-failed 重跑所有失败项
188
+ POST /api/image-batches/{id}/cancel 停止等待 + 未提交的作废退款
189
+ POST /api/image-batches/{id}/resume 继续未完成的行
190
+ GET /api/image-batches/{id}/export.zip 流式打包(服务端 zip)
191
+ DELETE /api/image-batches/{id} 删批次记录(图片按图片库策略处理)
192
+ ```
193
+
194
+ 提交时服务端做的事(顺序很关键):
195
+
196
+ ```
197
+ 1. 解析行列表 → 展开成 (行, 张) 清单
198
+ 2. 逐行过审(filter_or_log),被拦的行 → status=skipped,不进清单
199
+ 3. 整批额度预检(总张数 × 单价 vs 可用积分)
200
+ 4. 建批次记录(status=queued)
201
+ 5. ThreadPoolExecutor(max_workers=并发上限) 提交子任务
202
+ 每个子任务内部仍走现有的 submit_generation(自己预扣、自己跑、自己结算)
203
+ 6. 线程池外的一层轮询循环(每 2~3s)聚合子任务状态 → 更新批次表
204
+ ```
205
+
206
+ 注意 5 和 6:**不要在批次层做计费**,让每个子任务自己走 `image_task_service` 的预扣/结算链路,这样失败自动退款、部分成功天然正确,也不用碰 `_settle_credit`。
207
+
208
+ ### 5.3 后端改动清单
209
+
210
+ | 文件 | 改动 | 量级 |
211
+ |---|---|---|
212
+ | `services/image_batch_service.py` | 新建(照 `product_visual_service.py` 结构:`submit` / `_save_locked` / `_recover_unfinished_locked` / `_sync_item_status_locked` / `_derive_parent_status` / `retry_item`) | ~400 行 |
213
+ | `api/image_batches.py` | 新建路由(6 个接口),挂到 `api/app.py:194` 一带 | ~150 行 |
214
+ | `services/sqlite_mirror_service.py` | `_SCHEMAS` 登记两张新表 | 1 处 |
215
+ | `services/image_task_service.py` | 修 `_cleanup_locked` 死代码 bug(批量后任务量放大) | 1 处 |
216
+ | `api/image_tasks.py` | 不改(子任务仍走原接口内部函数) | 0 |
217
+
218
+ 打包 zip 的两个选择:服务端流式打包(大文件稳,但要处理图片在浏览器的情况)或前端 JSZip(零后端,受浏览器内存限制)。**建议服务端**,因为批次结果本来就要服务端留档。
219
+
220
+ ### 5.4 前端改动清单
221
+
222
+ ```
223
+ app/image/batch/page.tsx(新页面,或 image 页新增"批量"tab)
224
+ ├─ BatchComposer:多行提示词 textarea + 全局参数 + 行数/张数统计 + 预估积分
225
+ ├─ BatchProgress:总进度条 + 五个状态计数
226
+ ├─ BatchRows:按行分组的网格(复用 image-results 的图片卡片与操作)
227
+ └─ BatchActions:打包下载 / 重跑失败 / 取消 / 继续
228
+
229
+ 复用:
230
+ - 图片卡片、lightbox、单张重试(image-results.tsx)
231
+ - 参数控件(image-composer.tsx 的模型/比例/质量/号池策略)
232
+ - 积分展示(loadQuota / displayAvailableQuota)
233
+ - 多选与批量下载交互(image-manager/page.tsx)
234
+ ```
235
+
236
+ 轮询:批次级一个 `GET /api/image-batches?ids=`(2s),返回里带每行每张状态,**前端不再需要按 task id 逐个轮询**,比现在更省。
237
+
238
+ ### 5.5 会被"多提示词批量"打破的现有假设
239
+
240
+ 这几处是 A→B 升级时的硬约束,路线 A 也要按此设计字段:
241
+
242
+ 1. `ImageTurn` 是**单 prompt**(`store/image-conversations.ts:47`),一个 turn 塞不下多行 → 批次不能复用 turn 结构。
243
+ 2. `deriveTurnStatus` 是聚合推导,部分成功只能给"其中 N 张未成功" → 批次需要行级状态。
244
+ 3. `image-results.tsx` 按 `turn → images` 一维渲染 → 批次是 `batch → row → image` 三维,需要新渲染层。
245
+ 4. 轮询终止条件"没有 loading 任务就结束"→ 批次要区分"排队中但还没提交"的子项。
246
+ 5. 额度校验 `canAffordThirdPartyImages(..., parsedCount)` 要改成总张数。
247
+
248
+ ---
249
+
250
+ ## 6. 分期路线
251
+
252
+ | 阶段 | 内容 | 后端 | 前端 | 目的 |
253
+ |---|---|---|---|---|
254
+ | **P0** | 前端扇出版批量:多行提示词 + 全局参数 + 进度表 + 打包下载;批次数据暂存本地,按 `batch_id` 前缀聚合��务 | 0(复用现有接口) | 新增批量面板 + 批次分组渲染 | 一周内验证产品逻辑(用户要不要、用法对不对) |
255
+ | **P1** | 服务端批次模型(5.1/5.2/5.3)+ 批次中心页面 + 服务端留档 + zip 导出 + 失败重试/取消 | ~600 行 | 新页面 | 变成正式能力:跨设备、可续跑、可交付 |
256
+ | **P2** | CSV 导入导出、参考图集批量、自动重试策略、批次成本报表、从图片库批量重跑 | 少量 | 少量 | 面向重度用户(电商/素材) |
257
+
258
+ ---
259
+
260
+ ## 7. 风险与坑(精选)
261
+
262
+ 1. **别把计费改成"一次预扣 N 张"**:`_settle_credit` 不支持部分成功,会算错钱。逐张独立预扣是当前唯一正确姿势。
263
+ 2. **必须限线程**:不限并发会让 100 张任务同时卡在 `wait_for_slot`,既有内存风险也让号池排队行为不可预测。
264
+ 3. **"暂停/取消"要说清语义**:已在跑的上游请求无法中断,UI 文案别写"中止生成",写"停止等待后续队列"。
265
+ 4. **超时挂起 ≠ 失败**:带 conversation_id 的超时任务会等 `resume-poll`,批次聚合要单独统计"待继续等待"。
266
+ 5. **重启会打断批次**:服务端重启时未完成子任务变 error 并退款(已有逻辑),批次会被标记部分失败 → 这是正确行为,但要在 UI 上说明"服务重启会导致未完成的任务失败并自动退款"。
267
+ 6. **审核逐行做**:只审第一行会让后面的违规提示词漏网。
268
+ 7. **`_cleanup_locked` 先修**:不然批次记录与任务记录会无限堆积。
269
+ 8. **图片体积**:批量 100 张 4K 图,服务端留档要配图片库的清理策略(`image-manager` 已有删除能力)。
270
+ 9. **积分预检要含第三方钱包**:第三方通道走 `third_party_wallet_*`,预检金额要用 `cost_for_route` 的单价,不能一律用普通积分单价。
271
+ 10. **幂等键唯一**:`_submit` 里 `client_task_id` 相同直接返回旧任务,批量子任务 id 必须 `batch:row:index` 三段唯一。
272
+
273
+ ---
274
+
275
+ ## 8. 待拍板
276
+
277
+ 1. 核心场景是 B(多提示词矩阵)还是 C(参考图批量)为主?
278
+ 2. 首期走路线 A(前端扇出验证)还是直接 B(服务端批次)?
279
+ 3. 结果是否要服务端留档(换设备可见)?
280
+ 4. 并发默认值与上限(建议 3 / 10)。
web/src/app/image/components/image-composer.tsx CHANGED
@@ -1,6 +1,6 @@
1
  "use client";
2
- import { Check, ChevronDown, ImagePlus, LoaderCircle, X } from "lucide-react";
3
- import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type DragEvent, type PointerEvent, type RefObject } from "react";
4
 
5
  import {
6
  PromptComposerResizeHandle,
@@ -78,6 +78,11 @@ type ImageComposerProps = {
78
  onMemoryToggle: () => void;
79
  onAccountPoolStrategyChange: (value: string) => void;
80
  onSubmit: () => void | Promise<void>;
 
 
 
 
 
81
  onOptimizePrompt: () => void | Promise<void>;
82
  isOptimizingPrompt?: boolean;
83
  onBenefitsClick?: () => void;
@@ -91,6 +96,50 @@ type ImageComposerProps = {
91
 
92
  const imageFileNamePattern = /\.(avif|bmp|gif|heic|heif|ico|jpe?g|png|svg|tiff?|webp)$/i;
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  const defaultImageSizeOptions = [
95
  { value: "", label: "智能比例" },
96
  { value: "1:1", label: "1:1(正方形)" },
@@ -156,6 +205,7 @@ export function ImageComposer({
156
  onMemoryToggle,
157
  onAccountPoolStrategyChange,
158
  onSubmit,
 
159
  onOptimizePrompt,
160
  isOptimizingPrompt = false,
161
  onBenefitsClick,
@@ -172,6 +222,11 @@ export function ImageComposer({
172
  const [customRatioHeight, setCustomRatioHeight] = useState("1");
173
  const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
174
  const [isDraggingImage, setIsDraggingImage] = useState(false);
 
 
 
 
 
175
  const [sizeMenuPos, setSizeMenuPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
176
  const [modelMenuPos, setModelMenuPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
177
  // 心跳由全局 PresenceProvider 统一上报(覆盖站内所有页面),这里只负责展示数字。
@@ -255,6 +310,18 @@ export function ImageComposer({
255
  const unitCreditCostLabel = Number.isInteger(unitCreditCost)
256
  ? String(unitCreditCost)
257
  : unitCreditCost.toFixed(2).replace(/\.?0+$/, "");
 
 
 
 
 
 
 
 
 
 
 
 
258
  const requiresImageSize = imageModel.trim().toLowerCase() === "gpt-image-2-4k";
259
  const selectedImageSizeOption = imageSizeOptions.find((option) => option.value === imageSize);
260
  const isCustomImageSize = Boolean(imageSize && !selectedImageSizeOption && isSupportedAspectRatio(imageSize));
@@ -300,6 +367,117 @@ export function ImageComposer({
300
  );
301
  const accountPoolLabel = selectableAccountPoolOptions[accountPoolIndex]?.label || selectableAccountPoolOptions[0].label;
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  useEffect(() => {
304
  const controls = controlsScrollRef.current;
305
  if (!controls) return;
@@ -508,14 +686,123 @@ export function ImageComposer({
508
  onDragLeave={handleComposerDragLeave}
509
  onDrop={handleComposerDrop}
510
  onClick={() => {
 
511
  textareaRef.current?.focus();
512
  }}
513
  >
514
- <PromptComposerResizeHandle
515
- onClick={(event) => event.stopPropagation()}
516
- onPointerDown={handlePromptResizePointerDown}
517
- />
518
- <PromptComposerTextarea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  ref={textareaRef}
520
  value={prompt}
521
  style={promptHeight ? { height: `${promptHeight}px` } : undefined}
@@ -530,6 +817,7 @@ export function ImageComposer({
530
  onOptimize={onOptimizePrompt}
531
  isOptimizing={isOptimizingPrompt}
532
  />
 
533
  {isDraggingImage ? (
534
  <div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[24px] border-2 border-dashed border-stone-900 bg-white/85 text-sm font-medium text-stone-900 backdrop-blur-[1px] sm:rounded-[32px]">
535
  <div className="flex items-center gap-2 rounded-full bg-stone-950 px-4 py-2 text-white shadow-lg">
@@ -554,6 +842,23 @@ export function ImageComposer({
554
  >
555
  <ImagePlus className="size-3.5 sm:size-4" />
556
  </Button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  {availableQuota !== "--" && (
558
  onBenefitsClick ? (
559
  <Button
@@ -741,7 +1046,9 @@ export function ImageComposer({
741
  </div>
742
  )}
743
  <div className="flex h-9 shrink-0 items-center gap-1 rounded-full border border-stone-200 bg-white px-2 py-0.5 sm:h-auto sm:px-2.5 sm:py-1">
744
- <span className="hidden text-[11px] font-medium text-stone-700 sm:inline sm:text-sm">张数</span>
 
 
745
  <Input
746
  type="number"
747
  inputMode="numeric"
@@ -905,6 +1212,31 @@ export function ImageComposer({
905
  </>
906
  }
907
  actions={
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  <>
909
  <output
910
  data-testid="estimated-credit-cost"
@@ -928,6 +1260,7 @@ export function ImageComposer({
928
  label={referenceImages.length > 0 ? "编辑图片" : "生成图片"}
929
  />
930
  </>
 
931
  }
932
  />
933
  </div>
 
1
  "use client";
2
+ import { Check, ChevronDown, ImagePlus, List, LoaderCircle, Minus, Plus, Trash2, X } from "lucide-react";
3
+ import { useCallback, useEffect, useMemo, useRef, useState, type ClipboardEvent, type DragEvent, type KeyboardEvent, type PointerEvent, type RefObject } from "react";
4
 
5
  import {
6
  PromptComposerResizeHandle,
 
78
  onMemoryToggle: () => void;
79
  onAccountPoolStrategyChange: (value: string) => void;
80
  onSubmit: () => void | Promise<void>;
81
+ /**
82
+ * 批量生图提交。每一行会被展开成一个独立的生成任务(复用现有单张链路),
83
+ * 返回 false 表示校验未通过(积分/额度不足等),此时输入卡不清空。
84
+ */
85
+ onBatchSubmit: (rows: BatchRowInput[]) => boolean | Promise<boolean>;
86
  onOptimizePrompt: () => void | Promise<void>;
87
  isOptimizingPrompt?: boolean;
88
  onBenefitsClick?: () => void;
 
96
 
97
  const imageFileNamePattern = /\.(avif|bmp|gif|heic|heif|ico|jpe?g|png|svg|tiff?|webp)$/i;
98
 
99
+ /** 批量生图:单行的提交参数。 */
100
+ export type BatchRowInput = {
101
+ /** 该行的提示词(已剥离 `@@N` 后缀) */
102
+ prompt: string;
103
+ /** 该行要生成的张数 */
104
+ count: number;
105
+ };
106
+
107
+ type BatchEditorRow = {
108
+ id: string;
109
+ text: string;
110
+ count: number;
111
+ };
112
+
113
+ const MAX_BATCH_ROWS = 50;
114
+ const MAX_BATCH_COUNT = 100;
115
+
116
+ function createBatchRowId() {
117
+ return `batch-row-${Math.random().toString(36).slice(2, 10)}`;
118
+ }
119
+
120
+ function createBatchRow(count = 1): BatchEditorRow {
121
+ return { id: createBatchRowId(), text: "", count };
122
+ }
123
+
124
+ /**
125
+ * 解析批量编辑器的一行:
126
+ * - 空行 / `#` 开头 → null(忽略)
127
+ * - 行尾 `@@3` → 覆盖该行张数
128
+ */
129
+ function parseBatchLine(text: string, fallbackCount: number): BatchRowInput | null {
130
+ const raw = text.trim();
131
+ if (!raw || raw.startsWith("#")) return null;
132
+ const normalizedFallback = Math.max(1, Math.min(MAX_BATCH_COUNT, Math.floor(fallbackCount) || 1));
133
+ const match = raw.match(/@@\s*(\d{1,3})\s*$/);
134
+ if (!match) {
135
+ return { prompt: raw, count: normalizedFallback };
136
+ }
137
+ const prompt = raw.replace(/@@\s*\d{1,3}\s*$/, "").trim();
138
+ if (!prompt) return null;
139
+ const count = Math.max(1, Math.min(MAX_BATCH_COUNT, Number(match[1]) || normalizedFallback));
140
+ return { prompt, count };
141
+ }
142
+
143
  const defaultImageSizeOptions = [
144
  { value: "", label: "智能比例" },
145
  { value: "1:1", label: "1:1(正方形)" },
 
205
  onMemoryToggle,
206
  onAccountPoolStrategyChange,
207
  onSubmit,
208
+ onBatchSubmit,
209
  onOptimizePrompt,
210
  isOptimizingPrompt = false,
211
  onBenefitsClick,
 
222
  const [customRatioHeight, setCustomRatioHeight] = useState("1");
223
  const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
224
  const [isDraggingImage, setIsDraggingImage] = useState(false);
225
+ const [isBatchMode, setIsBatchMode] = useState(false);
226
+ const [isSubmittingBatch, setIsSubmittingBatch] = useState(false);
227
+ const [batchRows, setBatchRows] = useState<BatchEditorRow[]>(() => [createBatchRow()]);
228
+ const batchRowInputRefs = useRef<Map<string, HTMLTextAreaElement>>(new Map());
229
+ const pendingBatchFocusIdRef = useRef<string | null>(null);
230
  const [sizeMenuPos, setSizeMenuPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
231
  const [modelMenuPos, setModelMenuPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
232
  // 心跳由全局 PresenceProvider 统一上报(覆盖站内所有页面),这里只负责展示数字。
 
310
  const unitCreditCostLabel = Number.isInteger(unitCreditCost)
311
  ? String(unitCreditCost)
312
  : unitCreditCost.toFixed(2).replace(/\.?0+$/, "");
313
+
314
+ const batchParsedRows = useMemo(
315
+ () => batchRows.map((row) => ({ row, parsed: parseBatchLine(row.text, row.count) })),
316
+ [batchRows],
317
+ );
318
+ const batchValidRowCount = batchParsedRows.filter((item) => item.parsed).length;
319
+ const batchTotalCount = batchParsedRows.reduce((sum, item) => sum + (item.parsed?.count ?? 0), 0);
320
+ const batchIgnoredRowCount = batchParsedRows.filter((item) => !item.parsed && item.row.text.trim()).length;
321
+ const batchEstimatedCreditCost = Math.round(unitCreditCost * batchTotalCount * 100) / 100;
322
+ const batchEstimatedCreditCostLabel = Number.isInteger(batchEstimatedCreditCost)
323
+ ? String(batchEstimatedCreditCost)
324
+ : batchEstimatedCreditCost.toFixed(2).replace(/\.?0+$/, "");
325
  const requiresImageSize = imageModel.trim().toLowerCase() === "gpt-image-2-4k";
326
  const selectedImageSizeOption = imageSizeOptions.find((option) => option.value === imageSize);
327
  const isCustomImageSize = Boolean(imageSize && !selectedImageSizeOption && isSupportedAspectRatio(imageSize));
 
367
  );
368
  const accountPoolLabel = selectableAccountPoolOptions[accountPoolIndex]?.label || selectableAccountPoolOptions[0].label;
369
 
370
+ useEffect(() => {
371
+ // 批量行文本框按内容自适应高度(最多 96px),粘贴多行后也能立刻撑开。
372
+ batchRowInputRefs.current.forEach((el) => {
373
+ if (!el) return;
374
+ el.style.height = "auto";
375
+ el.style.height = `${Math.min(el.scrollHeight, 96)}px`;
376
+ });
377
+ const pendingId = pendingBatchFocusIdRef.current;
378
+ if (!pendingId) return;
379
+ pendingBatchFocusIdRef.current = null;
380
+ const target = batchRowInputRefs.current.get(pendingId);
381
+ if (!target) return;
382
+ target.focus();
383
+ const end = target.value.length;
384
+ target.setSelectionRange(end, end);
385
+ }, [batchRows]);
386
+
387
+ const enterBatchMode = useCallback(() => {
388
+ setBatchRows((rows) => {
389
+ const trimmed = prompt.trim();
390
+ // 切到批量时把已经敲在单张输入框里的提示词带进来,避免内容凭空消失。
391
+ if (trimmed && rows.length === 1 && !rows[0].text.trim()) {
392
+ return [{ ...rows[0], text: trimmed }];
393
+ }
394
+ return rows;
395
+ });
396
+ setIsBatchMode(true);
397
+ }, [prompt]);
398
+
399
+ const exitBatchMode = useCallback(() => {
400
+ setIsBatchMode(false);
401
+ }, []);
402
+
403
+ const updateBatchRow = useCallback((id: string, patch: Partial<BatchEditorRow>) => {
404
+ setBatchRows((rows) => rows.map((row) => (row.id === id ? { ...row, ...patch } : row)));
405
+ }, []);
406
+
407
+ const addBatchRow = useCallback((afterId?: string) => {
408
+ const created = createBatchRow();
409
+ setBatchRows((rows) => {
410
+ if (rows.length >= MAX_BATCH_ROWS) return rows;
411
+ if (!afterId) return [...rows, created];
412
+ const index = rows.findIndex((row) => row.id === afterId);
413
+ if (index < 0) return [...rows, created];
414
+ const next = [...rows];
415
+ next.splice(index + 1, 0, created);
416
+ return next;
417
+ });
418
+ pendingBatchFocusIdRef.current = created.id;
419
+ }, []);
420
+
421
+ const removeBatchRow = useCallback((id: string) => {
422
+ setBatchRows((rows) => {
423
+ if (rows.length <= 1) {
424
+ return rows.map((row) => (row.id === id ? { ...row, text: "", count: 1 } : row));
425
+ }
426
+ return rows.filter((row) => row.id !== id);
427
+ });
428
+ }, []);
429
+
430
+ const handleBatchRowKeyDown = useCallback(
431
+ (event: KeyboardEvent<HTMLTextAreaElement>, id: string) => {
432
+ if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
433
+ event.preventDefault();
434
+ addBatchRow(id);
435
+ },
436
+ [addBatchRow],
437
+ );
438
+
439
+ const handleBatchRowPaste = useCallback((event: ClipboardEvent<HTMLTextAreaElement>, id: string) => {
440
+ const text = event.clipboardData?.getData("text/plain") ?? "";
441
+ if (!text || !/[\r\n]/.test(text)) return;
442
+ const lines = text
443
+ .split(/\r?\n/)
444
+ .map((line) => line.trim())
445
+ .filter(Boolean);
446
+ if (lines.length <= 1) return;
447
+ event.preventDefault();
448
+ setBatchRows((rows) => {
449
+ const index = rows.findIndex((row) => row.id === id);
450
+ if (index < 0) return rows;
451
+ const head = rows[index];
452
+ const next = [...rows];
453
+ const [firstLine, ...restLines] = lines;
454
+ next[index] = { ...head, text: firstLine };
455
+ next.splice(
456
+ index + 1,
457
+ 0,
458
+ ...restLines.map((line) => ({ ...createBatchRow(head.count), text: line })),
459
+ );
460
+ return next;
461
+ });
462
+ }, []);
463
+
464
+ const handleBatchSubmitClick = useCallback(async () => {
465
+ const rows = batchParsedRows
466
+ .map((item) => item.parsed)
467
+ .filter((item): item is BatchRowInput => Boolean(item));
468
+ if (rows.length === 0 || isSubmittingBatch) return;
469
+ setIsSubmittingBatch(true);
470
+ try {
471
+ const accepted = await onBatchSubmit(rows);
472
+ if (accepted) {
473
+ setBatchRows([createBatchRow()]);
474
+ setIsBatchMode(false);
475
+ }
476
+ } finally {
477
+ setIsSubmittingBatch(false);
478
+ }
479
+ }, [batchParsedRows, isSubmittingBatch, onBatchSubmit]);
480
+
481
  useEffect(() => {
482
  const controls = controlsScrollRef.current;
483
  if (!controls) return;
 
686
  onDragLeave={handleComposerDragLeave}
687
  onDrop={handleComposerDrop}
688
  onClick={() => {
689
+ if (isBatchMode) return;
690
  textareaRef.current?.focus();
691
  }}
692
  >
693
+ {isBatchMode ? null : (
694
+ <PromptComposerResizeHandle
695
+ onClick={(event) => event.stopPropagation()}
696
+ onPointerDown={handlePromptResizePointerDown}
697
+ />
698
+ )}
699
+ {isBatchMode ? (
700
+ <div className="px-4 pb-1.5 pt-3 sm:px-5">
701
+ <div className="mb-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
702
+ <span className="text-xs font-medium text-stone-800">批量生成</span>
703
+ <span className="text-[11px] leading-4 text-stone-400">
704
+ 每行一个提示词 · 行尾 @@3 指定张数 · # 开头为注释
705
+ </span>
706
+ </div>
707
+ <div className="max-h-[44dvh] space-y-1.5 overflow-y-auto pr-0.5">
708
+ {batchParsedRows.map(({ row, parsed }, index) => {
709
+ const isIgnored = !parsed && row.text.trim().length > 0;
710
+ const effectiveCount = parsed?.count ?? row.count;
711
+ return (
712
+ <div key={row.id} className="flex items-start gap-1.5">
713
+ <span className="mt-2 w-4 shrink-0 text-right text-[11px] tabular-nums text-stone-400">
714
+ {index + 1}
715
+ </span>
716
+ <textarea
717
+ ref={(node) => {
718
+ if (node) batchRowInputRefs.current.set(row.id, node);
719
+ else batchRowInputRefs.current.delete(row.id);
720
+ }}
721
+ value={row.text}
722
+ rows={1}
723
+ spellCheck={false}
724
+ data-batch-row={row.id}
725
+ data-batch-row-index={index}
726
+ onChange={(event) => {
727
+ updateBatchRow(row.id, { text: event.target.value });
728
+ const el = event.currentTarget;
729
+ el.style.height = "auto";
730
+ el.style.height = `${Math.min(el.scrollHeight, 96)}px`;
731
+ }}
732
+ onKeyDown={(event) => handleBatchRowKeyDown(event, row.id)}
733
+ onPaste={(event) => handleBatchRowPaste(event, row.id)}
734
+ placeholder={index === 0 ? "第一行提示词…" : ""}
735
+ className={cn(
736
+ "min-h-9 flex-1 resize-none rounded-xl border border-stone-200 bg-white px-3 py-2 text-sm leading-5 text-stone-800 shadow-none outline-none transition placeholder:text-stone-400 focus-visible:border-stone-400 focus-visible:ring-0",
737
+ isIgnored && "text-stone-400",
738
+ )}
739
+ />
740
+ <span className="mt-1 flex h-9 shrink-0 items-center gap-0.5 rounded-full border border-stone-200 bg-white px-0.5 text-xs text-stone-600">
741
+ <button
742
+ type="button"
743
+ onClick={() =>
744
+ updateBatchRow(row.id, {
745
+ text: row.text.replace(/@@\s*\d{1,3}\s*$/, "").trim(),
746
+ count: Math.max(1, effectiveCount - 1),
747
+ })
748
+ }
749
+ disabled={effectiveCount <= 1}
750
+ className="flex size-6 items-center justify-center rounded-full text-stone-500 transition hover:bg-stone-100 hover:text-stone-800 disabled:opacity-40"
751
+ aria-label="减少张数"
752
+ >
753
+ <Minus className="size-3" />
754
+ </button>
755
+ <span className="w-6 text-center tabular-nums">{effectiveCount}</span>
756
+ <button
757
+ type="button"
758
+ onClick={() =>
759
+ updateBatchRow(row.id, {
760
+ text: row.text.replace(/@@\s*\d{1,3}\s*$/, "").trim(),
761
+ count: Math.min(MAX_BATCH_COUNT, effectiveCount + 1),
762
+ })
763
+ }
764
+ disabled={effectiveCount >= MAX_BATCH_COUNT}
765
+ className="flex size-6 items-center justify-center rounded-full text-stone-500 transition hover:bg-stone-100 hover:text-stone-800 disabled:opacity-40"
766
+ aria-label="增加张数"
767
+ >
768
+ <Plus className="size-3" />
769
+ </button>
770
+ </span>
771
+ <span
772
+ aria-hidden
773
+ className={cn(
774
+ "mt-4 size-1.5 shrink-0 rounded-full",
775
+ parsed ? "bg-emerald-500" : isIgnored ? "bg-stone-300" : "bg-transparent",
776
+ )}
777
+ />
778
+ <button
779
+ type="button"
780
+ onClick={() => removeBatchRow(row.id)}
781
+ className="mt-1 flex size-9 shrink-0 items-center justify-center rounded-full text-stone-400 transition hover:bg-stone-100 hover:text-stone-700"
782
+ aria-label="删除该行"
783
+ title="删除该行"
784
+ >
785
+ <Trash2 className="size-3.5" />
786
+ </button>
787
+ </div>
788
+ );
789
+ })}
790
+ </div>
791
+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1">
792
+ <button
793
+ type="button"
794
+ onClick={() => addBatchRow()}
795
+ data-testid="batch-add-row"
796
+ className="inline-flex items-center gap-1 rounded-full border border-dashed border-stone-300 px-2.5 py-1 text-[11px] font-medium text-stone-600 transition hover:border-stone-400 hover:text-stone-800"
797
+ >
798
+ <Plus className="size-3" />
799
+ 添加一行
800
+ </button>
801
+ <span className="text-[11px] text-stone-400">回车新增下一行 · 粘贴多行文本自动拆分</span>
802
+ </div>
803
+ </div>
804
+ ) : (
805
+ <PromptComposerTextarea
806
  ref={textareaRef}
807
  value={prompt}
808
  style={promptHeight ? { height: `${promptHeight}px` } : undefined}
 
817
  onOptimize={onOptimizePrompt}
818
  isOptimizing={isOptimizingPrompt}
819
  />
820
+ )}
821
  {isDraggingImage ? (
822
  <div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[24px] border-2 border-dashed border-stone-900 bg-white/85 text-sm font-medium text-stone-900 backdrop-blur-[1px] sm:rounded-[32px]">
823
  <div className="flex items-center gap-2 rounded-full bg-stone-950 px-4 py-2 text-white shadow-lg">
 
842
  >
843
  <ImagePlus className="size-3.5 sm:size-4" />
844
  </Button>
845
+ <Button
846
+ type="button"
847
+ variant="outline"
848
+ className={cn(
849
+ "h-9 shrink-0 gap-1 rounded-full px-2.5 text-[11px] font-medium shadow-none sm:h-10 sm:gap-1.5 sm:px-3 sm:text-xs",
850
+ isBatchMode
851
+ ? "border-stone-900 bg-stone-950 text-white hover:bg-stone-800 hover:text-white active:text-white"
852
+ : "border-stone-200 bg-white text-stone-700 hover:bg-stone-100",
853
+ )}
854
+ onClick={() => (isBatchMode ? exitBatchMode() : enterBatchMode())}
855
+ data-testid="batch-toggle"
856
+ aria-label={isBatchMode ? "退出批量模式" : "批量生图"}
857
+ title={isBatchMode ? "退出批量模式" : "批量生图(一行一个提示词)"}
858
+ >
859
+ {isBatchMode ? <X className="size-3.5" /> : <List className="size-3.5" />}
860
+ <span className="hidden sm:inline">批量</span>
861
+ </Button>
862
  {availableQuota !== "--" && (
863
  onBenefitsClick ? (
864
  <Button
 
1046
  </div>
1047
  )}
1048
  <div className="flex h-9 shrink-0 items-center gap-1 rounded-full border border-stone-200 bg-white px-2 py-0.5 sm:h-auto sm:px-2.5 sm:py-1">
1049
+ <span className="hidden text-[11px] font-medium text-stone-700 sm:inline sm:text-sm">
1050
+ {isBatchMode ? "每行张数" : "张数"}
1051
+ </span>
1052
  <Input
1053
  type="number"
1054
  inputMode="numeric"
 
1212
  </>
1213
  }
1214
  actions={
1215
+ isBatchMode ? (
1216
+ <>
1217
+ <output
1218
+ data-testid="batch-estimated-credit-cost"
1219
+ className="text-right font-normal text-stone-400 tabular-nums min-w-[7.5rem] text-[11px] leading-tight sm:text-xs"
1220
+ aria-label={`批量:${batchValidRowCount} 行共 ${batchTotalCount} 张,单张 ${unitCreditCostLabel} 积分,预计扣除 ${batchEstimatedCreditCostLabel} 积分`}
1221
+ title={`批量 ${batchValidRowCount} 行 × ${batchTotalCount} 张,单张 ${unitCreditCostLabel} 积分,预计扣除 ${batchEstimatedCreditCostLabel} 积分`}
1222
+ >
1223
+ <span className="flex flex-col items-end">
1224
+ <span className="font-normal text-stone-500">预计 {batchEstimatedCreditCostLabel} 积分</span>
1225
+ <span className="text-[10px] text-stone-400">
1226
+ {batchValidRowCount} 行 · 共 {batchTotalCount} 张
1227
+ {batchIgnoredRowCount > 0 ? ` · 忽略 ${batchIgnoredRowCount} 行` : ""}
1228
+ </span>
1229
+ </span>
1230
+ </output>
1231
+ <PromptComposerSubmitButton
1232
+ onSubmit={handleBatchSubmitClick}
1233
+ disabled={batchValidRowCount === 0 || isSubmittingBatch}
1234
+ label={`开始生成 ${batchTotalCount} 张`}
1235
+ title={`开始生成 ${batchTotalCount} 张(共 ${batchValidRowCount} 行)`}
1236
+ testId="batch-submit"
1237
+ />
1238
+ </>
1239
+ ) : (
1240
  <>
1241
  <output
1242
  data-testid="estimated-credit-cost"
 
1260
  label={referenceImages.length > 0 ? "编辑图片" : "生成图片"}
1261
  />
1262
  </>
1263
+ )
1264
  }
1265
  />
1266
  </div>
web/src/app/image/page.tsx CHANGED
@@ -10,7 +10,7 @@ import {
10
  buildImageExpansionPrompt,
11
  type ImageEditorAction,
12
  } from "@/app/image/components/image-annotation";
13
- import { ImageComposer } from "@/app/image/components/image-composer";
14
  import { ImageResults, type ImageLightboxItem } from "@/app/image/components/image-results";
15
  import { ConversationSidebar, type ConversationSidebarItem } from "@/components/chat/conversation-sidebar";
16
  import { ImageLightbox } from "@/components/image-lightbox";
@@ -575,6 +575,10 @@ function taskDataToStoredImages(image: StoredImage, task: ImageTask): StoredImag
575
  conversationId: task.conversation_id || undefined,
576
  durationMs: task.duration_ms,
577
  canContinueWaiting: task.can_continue_waiting ?? Boolean(task.conversation_id),
 
 
 
 
578
  }];
579
  }
580
 
@@ -612,6 +616,7 @@ function hasStoredImageChanged(current: StoredImage, next: StoredImage) {
612
  current.revised_prompt !== next.revised_prompt ||
613
  current.error !== next.error ||
614
  current.upstreamNote !== next.upstreamNote ||
 
615
  current.elapsedSecs !== next.elapsedSecs ||
616
  current.durationMs !== next.durationMs
617
  );
@@ -656,11 +661,21 @@ function mergeImageTaskResults(images: StoredImage[], taskMap: Map<string, Image
656
  (task.conversation_id || task.upstream_note) &&
657
  (!image.conversationId || !image.upstreamNote),
658
  );
 
 
 
 
 
 
 
 
 
659
  if (
660
  !task ||
661
  (image.status !== "loading" &&
662
  !(image.status === "success" && task.status === "success" && image.taskId) &&
663
- !shouldBackfillErrorMeta)
 
664
  ) {
665
  nextImages.push(image);
666
  continue;
@@ -764,7 +779,10 @@ async function syncConversationImageTasks(items: ImageConversation[]) {
764
  (image.status === "success" && !image.b64_json && !image.url) ||
765
  // 失败图缺上游会话 id / 官网原话时也拉一次任务做回填(见 mergeImageTaskResults 的
766
  // shouldBackfillErrorMeta);补齐后此条件不再命中,不会反复拉。
767
- (image.status === "error" && (!image.conversationId || !image.upstreamNote))
 
 
 
768
  ) ? [image.taskId] : [],
769
  ),
770
  ),
@@ -879,6 +897,7 @@ function conversationsRecoveredFromServerTasks(tasks: ImageTask[]): ImageConvers
879
  // 失败恢复的旧任务同样要带上游会话 id / 官网原话,和 taskDataToStoredImages 的 error 分支保持一致。
880
  conversationId: task.conversation_id || undefined,
881
  upstreamNote: task.upstream_note || undefined,
 
882
  durationMs: task.duration_ms,
883
  }));
884
  if (images.length === 0) {
@@ -889,6 +908,7 @@ function conversationsRecoveredFromServerTasks(tasks: ImageTask[]): ImageConvers
889
  error: task.error,
890
  conversationId: task.conversation_id || undefined,
891
  upstreamNote: task.upstream_note || undefined,
 
892
  durationMs: task.duration_ms,
893
  });
894
  }
@@ -2977,6 +2997,123 @@ function ImagePageContent({ session }: { session: StoredAuthSession }) {
2977
  }
2978
  };
2979
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2980
  const handleRedeem = async () => {
2981
  const normalizedCode = redeemValue.trim();
2982
  if (!normalizedCode) {
@@ -3472,6 +3609,7 @@ function ImagePageContent({ session }: { session: StoredAuthSession }) {
3472
  onMemoryToggle={() => setIsMemoryEnabled((value) => !value)}
3473
  onAccountPoolStrategyChange={setAccountPoolStrategy}
3474
  onSubmit={handleSubmit}
 
3475
  onOptimizePrompt={handleOptimizePrompt}
3476
  isOptimizingPrompt={isOptimizingPrompt}
3477
  onBenefitsClick={isNormalUser ? () => setIsBenefitsOpen(true) : undefined}
 
10
  buildImageExpansionPrompt,
11
  type ImageEditorAction,
12
  } from "@/app/image/components/image-annotation";
13
+ import { ImageComposer, type BatchRowInput } from "@/app/image/components/image-composer";
14
  import { ImageResults, type ImageLightboxItem } from "@/app/image/components/image-results";
15
  import { ConversationSidebar, type ConversationSidebarItem } from "@/components/chat/conversation-sidebar";
16
  import { ImageLightbox } from "@/components/image-lightbox";
 
575
  conversationId: task.conversation_id || undefined,
576
  durationMs: task.duration_ms,
577
  canContinueWaiting: task.can_continue_waiting ?? Boolean(task.conversation_id),
578
+ // 「查看官网对话」入口:后端明确说「官网没有可核对的东西」(账号生图配额耗尽)时为
579
+ // false,卡片据此收掉入口。写成显式布尔值(而不是只在 false 时赋值),回填一次就稳定,
580
+ // 不会每次加载都重新拉这个任务。
581
+ canViewOfficial: task.can_view_official !== false,
582
  }];
583
  }
584
 
 
616
  current.revised_prompt !== next.revised_prompt ||
617
  current.error !== next.error ||
618
  current.upstreamNote !== next.upstreamNote ||
619
+ current.canViewOfficial !== next.canViewOfficial ||
620
  current.elapsedSecs !== next.elapsedSecs ||
621
  current.durationMs !== next.durationMs
622
  );
 
661
  (task.conversation_id || task.upstream_note) &&
662
  (!image.conversationId || !image.upstreamNote),
663
  );
664
+ // 「查看官网」入口也有同样的问题:老卡片存的是 undefined,任务里已经有明确结论时
665
+ // 要回填一次(true/false 都会被写死),否则配额类报错的老卡片会一直挂着没用的按钮。
666
+ const shouldBackfillViewOfficial = Boolean(
667
+ image.status === "error" &&
668
+ task &&
669
+ task.status === "error" &&
670
+ image.taskId &&
671
+ image.canViewOfficial === undefined,
672
+ );
673
  if (
674
  !task ||
675
  (image.status !== "loading" &&
676
  !(image.status === "success" && task.status === "success" && image.taskId) &&
677
+ !shouldBackfillErrorMeta &&
678
+ !shouldBackfillViewOfficial)
679
  ) {
680
  nextImages.push(image);
681
  continue;
 
779
  (image.status === "success" && !image.b64_json && !image.url) ||
780
  // 失败图缺上游会话 id / 官网原话时也拉一次任务做回填(见 mergeImageTaskResults 的
781
  // shouldBackfillErrorMeta);补齐后此条件不再命中,不会反复拉。
782
+ (image.status === "error" && (!image.conversationId || !image.upstreamNote)) ||
783
+ // 「查看官网」入口同理:老卡片存的是 undefined,回填后会写成显式布尔值,
784
+ // 条件随即不再命中(任务确实取不到时保持原样,和上一条同一个兜底口径)。
785
+ (image.status === "error" && image.canViewOfficial === undefined)
786
  ) ? [image.taskId] : [],
787
  ),
788
  ),
 
897
  // 失败恢复的旧任务同样要带上游会话 id / 官网原话,和 taskDataToStoredImages 的 error 分支保持一致。
898
  conversationId: task.conversation_id || undefined,
899
  upstreamNote: task.upstream_note || undefined,
900
+ canViewOfficial: task.can_view_official !== false,
901
  durationMs: task.duration_ms,
902
  }));
903
  if (images.length === 0) {
 
908
  error: task.error,
909
  conversationId: task.conversation_id || undefined,
910
  upstreamNote: task.upstream_note || undefined,
911
+ canViewOfficial: task.can_view_official !== false,
912
  durationMs: task.duration_ms,
913
  });
914
  }
 
2997
  }
2998
  };
2999
 
3000
+ /**
3001
+ * 批量生图提交:每一行展开成一个独立的 turn(复用现有单张任务链路)。
3002
+ * 现有会话队列会顺序处理这些 queued turn,结果照常落在消息流里。
3003
+ * 返回 false 表示校验未通过,批量输入卡保持原样。
3004
+ */
3005
+ const handleBatchSubmit = async (rows: BatchRowInput[]): Promise<boolean> => {
3006
+ const validRows = rows
3007
+ .map((row) => ({
3008
+ prompt: String(row?.prompt || "").trim(),
3009
+ count: Math.max(1, Math.min(100, Math.floor(Number(row?.count) || 1))),
3010
+ }))
3011
+ .filter((row) => row.prompt.length > 0);
3012
+ if (validRows.length === 0) {
3013
+ toast.error("请至少填写一行提示词");
3014
+ return false;
3015
+ }
3016
+ const totalCount = validRows.reduce((sum, row) => sum + row.count, 0);
3017
+
3018
+ const effectiveImageMode: ImageConversationMode = referenceImageFiles.length > 0 ? "edit" : "generate";
3019
+ const requestedResolution = ["1k", "2k", "4k"].includes(imageResolution) ? imageResolution : "1k";
3020
+ const effectiveThirdPartyModel = selectedThirdPartyModel;
3021
+ const useThirdPartyImageApi = Boolean(effectiveThirdPartyModel);
3022
+ if ((imageResolution === "4k" || thirdPartyImageGroupId) && !effectiveThirdPartyModel) {
3023
+ toast.error(imageResolution === "4k" ? "后台还没有为当前用户开启可用的 4K 生图 API" : "这个 API 模型当前不可用,请在后台确认模型已启用");
3024
+ return false;
3025
+ }
3026
+ if (imageModel.trim().toLowerCase() === "gpt-image-2-4k" && !imageSize.trim()) {
3027
+ toast.error("使用 gpt-image-2-4k 时必须先选择图片比例");
3028
+ return false;
3029
+ }
3030
+ const batchEstimatedCredits = Math.round(selectedUnitCreditCost * totalCount * 100) / 100;
3031
+ if (isNormalUser && useThirdPartyImageApi) {
3032
+ if (!canAffordThirdPartyImages(creditSummary, effectiveThirdPartyModel, totalCount)) {
3033
+ toast.error("剩余可用积分不足,请先充值");
3034
+ setIsRedeemOpen(true);
3035
+ return false;
3036
+ }
3037
+ }
3038
+ if (isNormalUser && !useThirdPartyImageApi && (creditSummary?.credits ?? 0) < batchEstimatedCredits) {
3039
+ toast.error("剩余积分不足,请先充值");
3040
+ setIsRedeemOpen(true);
3041
+ return false;
3042
+ }
3043
+ if (
3044
+ isNormalUser &&
3045
+ !useThirdPartyImageApi &&
3046
+ !canFallbackToStandardImageApi &&
3047
+ accountPoolQuotaCount !== null &&
3048
+ accountPoolQuotaCount < totalCount
3049
+ ) {
3050
+ const siteCredits = toCreditAmount(creditSummary?.credits) ?? 0;
3051
+ if (siteCredits < batchEstimatedCredits) {
3052
+ toast.error("剩余积分不足,请先充值");
3053
+ setIsRedeemOpen(true);
3054
+ } else {
3055
+ toast.error("号池可用生图额度不足,请提醒站长补充账号");
3056
+ }
3057
+ return false;
3058
+ }
3059
+
3060
+ const targetConversation = selectedConversationId
3061
+ ? conversationsRef.current.find((conversation) => conversation.id === selectedConversationId) ?? null
3062
+ : null;
3063
+ const effectiveThirdPartyResolution = effectiveThirdPartyModel ? thirdPartyModelResolution(effectiveThirdPartyModel) : requestedResolution;
3064
+ const effectiveThirdPartyQuality = effectiveThirdPartyModel
3065
+ ? thirdPartyModelDefaultQuality(effectiveThirdPartyModel)
3066
+ : imageQuality;
3067
+ const now = new Date().toISOString();
3068
+ const conversationId = targetConversation?.id ?? createId();
3069
+
3070
+ const batchTurns: ImageTurn[] = validRows.map((row) => {
3071
+ const turnId = createId();
3072
+ return {
3073
+ id: turnId,
3074
+ prompt: row.prompt,
3075
+ model: useThirdPartyImageApi ? effectiveThirdPartyModel?.id || imageModel : "gpt-image-2",
3076
+ mode: effectiveImageMode,
3077
+ referenceImages: effectiveImageMode === "edit" ? referenceImages : [],
3078
+ count: row.count,
3079
+ size: imageSize,
3080
+ quality: useThirdPartyImageApi ? effectiveThirdPartyQuality : undefined,
3081
+ resolution: useThirdPartyImageApi ? effectiveThirdPartyResolution : undefined,
3082
+ thirdPartyImageGroupId: useThirdPartyImageApi ? effectiveThirdPartyModel?.group_id : undefined,
3083
+ memoryEnabled: isMemoryEnabled,
3084
+ images: createLoadingImages(turnId, row.count),
3085
+ createdAt: now,
3086
+ status: "queued",
3087
+ };
3088
+ });
3089
+
3090
+ const baseConversation: ImageConversation = targetConversation
3091
+ ? {
3092
+ ...targetConversation,
3093
+ updatedAt: now,
3094
+ turns: [...targetConversation.turns, ...batchTurns],
3095
+ }
3096
+ : {
3097
+ id: conversationId,
3098
+ title: buildConversationTitle(validRows[0].prompt),
3099
+ createdAt: now,
3100
+ updatedAt: now,
3101
+ turns: batchTurns,
3102
+ };
3103
+
3104
+ shouldStickToBottomRef.current = true;
3105
+ setScrollToLatestVisible(false);
3106
+ setSelectedConversationId(conversationId);
3107
+
3108
+ await persistConversation(baseConversation);
3109
+ clearComposerInputs();
3110
+ void clearImageComposerDraft();
3111
+ void runConversationQueue(conversationId);
3112
+
3113
+ toast.success(`已提交 ${validRows.length} 行,共 ${totalCount} 张`);
3114
+ return true;
3115
+ };
3116
+
3117
  const handleRedeem = async () => {
3118
  const normalizedCode = redeemValue.trim();
3119
  if (!normalizedCode) {
 
3609
  onMemoryToggle={() => setIsMemoryEnabled((value) => !value)}
3610
  onAccountPoolStrategyChange={setAccountPoolStrategy}
3611
  onSubmit={handleSubmit}
3612
+ onBatchSubmit={handleBatchSubmit}
3613
  onOptimizePrompt={handleOptimizePrompt}
3614
  isOptimizingPrompt={isOptimizingPrompt}
3615
  onBenefitsClick={isNormalUser ? () => setIsBenefitsOpen(true) : undefined}
web/src/components/prompt-composer.tsx CHANGED
@@ -345,6 +345,7 @@ type PromptComposerSubmitButtonProps = {
345
  label: string;
346
  title?: string;
347
  className?: string;
 
348
  };
349
 
350
  export function PromptComposerSubmitButton({
@@ -355,6 +356,7 @@ export function PromptComposerSubmitButton({
355
  label,
356
  title = "发送(Enter)",
357
  className,
 
358
  }: PromptComposerSubmitButtonProps) {
359
  return (
360
  <button
@@ -365,6 +367,7 @@ export function PromptComposerSubmitButton({
365
  else void onSubmit();
366
  }}
367
  disabled={isSubmitting ? !onStop : disabled}
 
368
  className={cn(
369
  "inline-flex size-10 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition-[transform,background-color] duration-150 ease-out hover:bg-stone-800 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-300 disabled:cursor-not-allowed disabled:bg-stone-300 disabled:opacity-100 sm:size-11 motion-reduce:transition-none",
370
  className,
 
345
  label: string;
346
  title?: string;
347
  className?: string;
348
+ testId?: string;
349
  };
350
 
351
  export function PromptComposerSubmitButton({
 
356
  label,
357
  title = "发送(Enter)",
358
  className,
359
+ testId,
360
  }: PromptComposerSubmitButtonProps) {
361
  return (
362
  <button
 
367
  else void onSubmit();
368
  }}
369
  disabled={isSubmitting ? !onStop : disabled}
370
+ data-testid={testId}
371
  className={cn(
372
  "inline-flex size-10 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition-[transform,background-color] duration-150 ease-out hover:bg-stone-800 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-300 disabled:cursor-not-allowed disabled:bg-stone-300 disabled:opacity-100 sm:size-11 motion-reduce:transition-none",
373
  className,