sync: 同步总仓库 luoguang/monkey-ai weiyuan@bfdfb339 的 web/ 改动
同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2) 范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json) - 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models - 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s - dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台) - b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join - 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文 - e4c301d5 fix: merge enterprise task record date filters - c9369b95 feat: expose enterprise image and video task records - a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2) - 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写 - 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费 - f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口 - 8cdf1994 fix(topup): reset amount when switching from PayPal - 93a4ac34 feat(baidu): configure Seedance liveness header by channel - cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21) - 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分) - e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分) - b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足 - e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销 - 584aad52 style(web): 个人中心侧边栏按 prettier 换行 - b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView - eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤 - 8b254d49 fix: 小程序里隐藏企业充值入口与页面 - a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转 - cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票 - c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费 - 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式 - 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
This commit is contained in:
@@ -27,6 +27,9 @@ import { API, showError } from '../../helpers';
|
||||
*/
|
||||
export const useAnalyticsData = (active = true) => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
// 概览单独一个 loading:它是全页最慢的一个接口(活跃/消耗要跨月聚合),
|
||||
// 和其余 7 个接口共用一个全页遮罩的话,整页都要等它,见 refreshAll。
|
||||
const [overviewLoading, setOverviewLoading] = useState(false);
|
||||
const [overview, setOverview] = useState(null);
|
||||
const [userTrend, setUserTrend] = useState([]);
|
||||
const [financeTrend, setFinanceTrend] = useState([]);
|
||||
@@ -81,6 +84,7 @@ export const useAnalyticsData = (active = true) => {
|
||||
|
||||
// 获取概览数据。后端对概览结果做了 60s 缓存,force=true 时穿透(用户主动点刷新)
|
||||
const fetchOverview = useCallback(async (force = false) => {
|
||||
setOverviewLoading(true);
|
||||
try {
|
||||
const res = await API.get(
|
||||
`/api/analytics/overview${force ? '?refresh=true' : ''}`,
|
||||
@@ -92,6 +96,8 @@ export const useAnalyticsData = (active = true) => {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取概览数据失败:', error);
|
||||
} finally {
|
||||
setOverviewLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -220,13 +226,16 @@ export const useAnalyticsData = (active = true) => {
|
||||
[buildQueryParams],
|
||||
);
|
||||
|
||||
// 刷新所有数据
|
||||
// 刷新所有数据。
|
||||
// 概览不参与全页 loading:它只影响顶部 6 张卡片(卡片自己有骨架屏),
|
||||
// 却是耗时最长的一个请求,纳入遮罩会让下面的图表白白陪等。
|
||||
// 返回的 Promise 仍然等齐全部 8 个请求,刷新按钮据此显示完整进度。
|
||||
const refreshAll = useCallback(
|
||||
async (currentPeriod, currentDateRange, force = false) => {
|
||||
const overviewTask = fetchOverview(force);
|
||||
setLoading(true);
|
||||
try {
|
||||
await Promise.all([
|
||||
fetchOverview(force),
|
||||
fetchUserTrend(currentPeriod, currentDateRange),
|
||||
fetchFinanceTrend(currentPeriod, currentDateRange),
|
||||
fetchChannelConsumption(currentPeriod, currentDateRange),
|
||||
@@ -238,6 +247,7 @@ export const useAnalyticsData = (active = true) => {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
await overviewTask;
|
||||
},
|
||||
[
|
||||
fetchOverview,
|
||||
@@ -287,6 +297,7 @@ export const useAnalyticsData = (active = true) => {
|
||||
|
||||
return {
|
||||
loading,
|
||||
overviewLoading,
|
||||
overview,
|
||||
userTrend,
|
||||
financeTrend,
|
||||
|
||||
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useState, useCallback, useEffect } from 'react';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
|
||||
/**
|
||||
* 风控看板数据 Hook
|
||||
@@ -106,15 +107,15 @@ export const useRiskControlData = (active = true) => {
|
||||
try {
|
||||
const res = await API.post('/api/analytics/risk/rules', rule);
|
||||
if (res.data.success) {
|
||||
showSuccess('保存成功');
|
||||
showSuccess(i18next.t('保存成功'));
|
||||
// 阈值变化后,列表里"是否命中"的状态标签依赖新规则计算,需联动刷新
|
||||
await Promise.all([fetchRules(), fetchSuspects()]);
|
||||
return true;
|
||||
}
|
||||
showError(res.data.message || '保存失败');
|
||||
showError(res.data.message || i18next.t('保存失败'));
|
||||
return false;
|
||||
} catch (e) {
|
||||
showError(e?.message || '保存失败');
|
||||
showError(e?.message || i18next.t('保存失败'));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -125,13 +126,13 @@ export const useRiskControlData = (active = true) => {
|
||||
try {
|
||||
const res = await API.post('/api/analytics/risk/rules/run-now');
|
||||
if (res.data.success) {
|
||||
showSuccess('已触发后台扫描');
|
||||
showSuccess(i18next.t('已触发后台扫描'));
|
||||
return true;
|
||||
}
|
||||
showError(res.data.message);
|
||||
return false;
|
||||
} catch (e) {
|
||||
showError(e?.message || '触发失败');
|
||||
showError(e?.message || i18next.t('触发失败'));
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
@@ -174,7 +175,7 @@ export const useRiskControlData = (active = true) => {
|
||||
reason: reason || '',
|
||||
});
|
||||
if (res.data.success) {
|
||||
showSuccess('解封成功');
|
||||
showSuccess(i18next.t('解封成功'));
|
||||
// 解封会改变两个数据集的状态,并发刷新
|
||||
await Promise.all([fetchSuspects(), fetchBanLogs()]);
|
||||
return true;
|
||||
@@ -182,7 +183,7 @@ export const useRiskControlData = (active = true) => {
|
||||
showError(res.data.message);
|
||||
return false;
|
||||
} catch (e) {
|
||||
showError(e?.message || '解封失败');
|
||||
showError(e?.message || i18next.t('解封失败'));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -235,7 +235,7 @@ export const useChannelsData = () => {
|
||||
key: tag,
|
||||
id: tag,
|
||||
tag: tag,
|
||||
name: '标签:' + tag,
|
||||
name: t('标签:{{name}}', { name: tag }),
|
||||
group: '',
|
||||
used_quota: 0,
|
||||
response_time: 0,
|
||||
@@ -627,8 +627,9 @@ export const useChannelsData = () => {
|
||||
}
|
||||
} catch (error) {
|
||||
showError(
|
||||
t('渠道复制失败: ') +
|
||||
(error?.response?.data?.message || error?.message || error),
|
||||
t('渠道复制失败: {{message}}', {
|
||||
message: error?.response?.data?.message || error?.message || error,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -887,7 +888,7 @@ export const useChannelsData = () => {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
showError(`${t('模型')} ${model}: ${message}`);
|
||||
showError(t('模型 {{model}}: {{message}}', { model, message }));
|
||||
}
|
||||
} catch (error) {
|
||||
// 处理网络错误
|
||||
@@ -901,7 +902,12 @@ export const useChannelsData = () => {
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
}));
|
||||
showError(`${t('模型')} ${model}: ${error.message || t('测试失败')}`);
|
||||
showError(
|
||||
t('模型 {{model}}: {{message}}', {
|
||||
model,
|
||||
message: error.message || t('测试失败'),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
// 从正在测试的模型集合中移除
|
||||
setTestingModels((prev) => {
|
||||
@@ -1021,7 +1027,9 @@ export const useChannelsData = () => {
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
showError(t('批量测试过程中发生错误: ') + error.message);
|
||||
showError(
|
||||
t('批量测试过程中发生错误: {{message}}', { message: error.message }),
|
||||
);
|
||||
} finally {
|
||||
setIsBatchTesting(false);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import { useEffect, useState } from 'react';
|
||||
import { fetchTokenKeys, getServerAddress } from '../../helpers/token';
|
||||
import { showError } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
|
||||
export function useTokenKeys(id) {
|
||||
const [keys, setKeys] = useState([]);
|
||||
@@ -30,7 +31,9 @@ export function useTokenKeys(id) {
|
||||
const loadAllData = async () => {
|
||||
const fetchedKeys = await fetchTokenKeys();
|
||||
if (fetchedKeys.length === 0) {
|
||||
showError('当前没有可用的启用令牌,请确认是否有令牌处于启用状态!');
|
||||
showError(
|
||||
i18next.t('当前没有可用的启用令牌,请确认是否有令牌处于启用状态!'),
|
||||
);
|
||||
setTimeout(() => {
|
||||
window.location.href = '/console/token';
|
||||
}, 1500); // 延迟 1.5 秒后跳转
|
||||
|
||||
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
|
||||
/**
|
||||
* 用户权限钩子 - 从后端获取用户权限,替代前端角色判断
|
||||
@@ -39,11 +40,11 @@ export const useUserPermissions = () => {
|
||||
setPermissions(userPermissions);
|
||||
console.log('用户权限加载成功:', userPermissions);
|
||||
} else {
|
||||
setError(res.data.message || '获取权限失败');
|
||||
setError(res.data.message || i18next.t('获取权限失败'));
|
||||
console.error('获取权限失败:', res.data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
setError('网络错误,请重试');
|
||||
setError(i18next.t('网络错误,请重试'));
|
||||
console.error('加载用户权限异常:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 获取 API 代码(WP C-1,方案 §4.4):由作品的参数快照(任务详情 request)生成等价的公开接口调用。
|
||||
// 图像 → POST /v1/images/generations(编辑模式的参考图换成占位 URL);
|
||||
// 视频 → POST /v1/video/generations 标准 director 协议(model / prompt / duration /
|
||||
// metadata{resolution, aspect_ratio, negative_prompt, seed, generate_audio, watermark,
|
||||
// camera{movement}, return_last_frame, prompt_extend} / media[{type, url}],
|
||||
// 字段与 controller/experience_video_director.go、relay/common/video_director.go 一致)。
|
||||
// 不依赖 React / 浏览器,node --test 覆盖(creationApiCode.test.js)。
|
||||
|
||||
export const API_KEY_PLACEHOLDER = 'sk-xxx';
|
||||
export const IMAGE_URL_PLACEHOLDER = '<YOUR_IMAGE_URL>';
|
||||
export const API_CODE_LANGS = ['curl', 'python', 'javascript'];
|
||||
|
||||
export const IMAGE_API_PATH = '/v1/images/generations';
|
||||
export const VIDEO_API_PATH = '/v1/video/generations';
|
||||
|
||||
/** 说明(i18n key):替换占位图片 / 视频为异步任务。 */
|
||||
export const API_CODE_NOTES = {
|
||||
replaceImages:
|
||||
'请把 <YOUR_IMAGE_URL> 替换为你自己的公网图片地址(/v1 接口支持外部链接)',
|
||||
asyncVideo:
|
||||
'视频为异步任务:提交后返回 task_id,再用 GET {{path}}/{task_id} 查询结果',
|
||||
};
|
||||
|
||||
/** 接口地址:系统设置的服务器地址优先,否则当前页面的 origin;去掉结尾斜杠。 */
|
||||
export const apiBaseUrlOf = (status, origin = '') => {
|
||||
const configured = String(status?.server_address || '').trim();
|
||||
const base = configured || String(origin || '').trim();
|
||||
return base.replace(/\/+$/, '');
|
||||
};
|
||||
|
||||
const str = (v) => (typeof v === 'string' ? v.trim() : '');
|
||||
const isBool = (v) => typeof v === 'boolean';
|
||||
const isInt = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
|
||||
/** n 张占位图:1 张为 <YOUR_IMAGE_URL>,多张编号 <YOUR_IMAGE_URL_1>…,保证每张可区分。 */
|
||||
const placeholders = (count) =>
|
||||
Array.from({ length: count }, (_, i) =>
|
||||
count > 1 ? `<YOUR_IMAGE_URL_${i + 1}>` : IMAGE_URL_PLACEHOLDER,
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 请求体
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 图像任务 → /v1/images/generations 请求体。task 为作品流的作品(含详情 request 时优先用快照)。 */
|
||||
export const imageApiBody = (task) => {
|
||||
const t = task || {};
|
||||
const req = t.request || {};
|
||||
const hasSnapshot = Boolean(t.request);
|
||||
const body = {
|
||||
model: str(req.model) || str(t.model),
|
||||
prompt: hasSnapshot ? String(req.prompt || '') : String(t.prompt || ''),
|
||||
};
|
||||
const n = Number(hasSnapshot ? req.n : t.n);
|
||||
if (Number.isInteger(n) && n > 0) body.n = n;
|
||||
const size = str(req.size) || str(t.size);
|
||||
if (size) body.size = size;
|
||||
const quality = str(req.quality) || str(t.quality);
|
||||
if (quality) body.quality = quality;
|
||||
if (str(req.negative_prompt)) body.negative_prompt = str(req.negative_prompt);
|
||||
if (isInt(req.seed)) body.seed = req.seed;
|
||||
['style', 'background', 'output_format'].forEach((k) => {
|
||||
if (str(req[k])) body[k] = str(req[k]);
|
||||
});
|
||||
if (isBool(req.watermark)) body.watermark = req.watermark;
|
||||
|
||||
const mode = str(req.mode) || str(t.mode);
|
||||
const isEdit = mode === 'edit' || mode === 'image-to-image';
|
||||
let count = 0;
|
||||
if (Array.isArray(req.reference_image_refs)) {
|
||||
count = req.reference_image_refs.length;
|
||||
} else if (Array.isArray(req.reference_images)) {
|
||||
count = req.reference_images.length;
|
||||
}
|
||||
if (isEdit && count === 0) count = 1;
|
||||
if (count > 0) {
|
||||
const urls = placeholders(count);
|
||||
body.image = urls.length === 1 ? urls[0] : urls;
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
/** 视频任务 → /v1/video/generations 标准 director 请求体。 */
|
||||
export const videoApiBody = (task) => {
|
||||
const t = task || {};
|
||||
const req = t.request || {};
|
||||
const body = {
|
||||
model: str(req.model) || str(t.model),
|
||||
prompt: t.request ? String(req.prompt || '') : String(t.prompt || ''),
|
||||
};
|
||||
const duration = Number(req.duration) || Number(t.duration) || 0;
|
||||
if (duration > 0) body.duration = duration;
|
||||
|
||||
const metadata = {};
|
||||
const resolution = str(req.resolution) || str(t.resolution);
|
||||
if (resolution) metadata.resolution = resolution;
|
||||
const ratio = str(req.aspect_ratio) || str(req.ratio) || str(t.ratio);
|
||||
if (ratio) metadata.aspect_ratio = ratio;
|
||||
if (str(req.negative_prompt)) {
|
||||
metadata.negative_prompt = str(req.negative_prompt);
|
||||
}
|
||||
if (isInt(req.seed)) metadata.seed = req.seed;
|
||||
if (isBool(req.generate_audio)) metadata.generate_audio = req.generate_audio;
|
||||
else if (req.audio === true) metadata.generate_audio = true;
|
||||
// watermark / audio 在快照 DTO 中为 omitempty:缺省即未开启,不写出
|
||||
if (req.watermark === true) metadata.watermark = true;
|
||||
if (str(req.camera)) metadata.camera = { movement: str(req.camera) };
|
||||
if (isBool(req.return_last_frame)) {
|
||||
metadata.return_last_frame = req.return_last_frame;
|
||||
}
|
||||
if (isBool(req.prompt_extend)) metadata.prompt_extend = req.prompt_extend;
|
||||
if (Object.keys(metadata).length) body.metadata = metadata;
|
||||
|
||||
const types = [];
|
||||
if (str(req.image_ref) || str(req.image)) types.push('first_image');
|
||||
if (str(req.last_image_ref) || str(req.last_image)) types.push('last_image');
|
||||
const refs = Array.isArray(req.reference_image_refs)
|
||||
? req.reference_image_refs
|
||||
: Array.isArray(req.reference_images)
|
||||
? req.reference_images
|
||||
: [];
|
||||
refs.forEach(() => types.push('reference_image'));
|
||||
if (types.length) {
|
||||
const urls = placeholders(types.length);
|
||||
body.media = types.map((type, i) => ({ type, url: urls[i] }));
|
||||
}
|
||||
return body;
|
||||
};
|
||||
|
||||
/**
|
||||
* 作品 → 等价的公开接口调用。
|
||||
* @returns {{ kind, method: 'POST', url: string, path: string, body: object, notes: string[] }}
|
||||
* notes 为 i18n key(API_CODE_NOTES 的值)
|
||||
*/
|
||||
export const buildApiCall = (task, { baseUrl = '' } = {}) => {
|
||||
const kind = task?.kind === 'video' ? 'video' : 'image';
|
||||
const path = kind === 'video' ? VIDEO_API_PATH : IMAGE_API_PATH;
|
||||
const body = kind === 'video' ? videoApiBody(task) : imageApiBody(task);
|
||||
const notes = [];
|
||||
const usesPlaceholder =
|
||||
kind === 'video' ? Boolean(body.media) : Boolean(body.image);
|
||||
if (usesPlaceholder) notes.push(API_CODE_NOTES.replaceImages);
|
||||
if (kind === 'video') notes.push(API_CODE_NOTES.asyncVideo);
|
||||
return {
|
||||
kind,
|
||||
method: 'POST',
|
||||
path,
|
||||
url: `${String(baseUrl || '').replace(/\/+$/, '')}${path}`,
|
||||
body,
|
||||
notes,
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 代码渲染
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const indentLines = (text, pad) =>
|
||||
text
|
||||
.split('\n')
|
||||
.map((line, i) => (i === 0 ? line : pad + line))
|
||||
.join('\n');
|
||||
|
||||
/** JSON 值 → Python 字面量(True / False / None,4 空格缩进,与 json 序列化顺序一致)。 */
|
||||
export const toPythonLiteral = (value, indent = '') => {
|
||||
if (value === null || value === undefined) return 'None';
|
||||
if (value === true) return 'True';
|
||||
if (value === false) return 'False';
|
||||
if (typeof value === 'number') {
|
||||
return Number.isFinite(value) ? String(value) : 'None';
|
||||
}
|
||||
if (typeof value === 'string') return JSON.stringify(value);
|
||||
const inner = `${indent} `;
|
||||
if (Array.isArray(value)) {
|
||||
if (!value.length) return '[]';
|
||||
const items = value.map((v) => `${inner}${toPythonLiteral(v, inner)},`);
|
||||
return `[\n${items.join('\n')}\n${indent}]`;
|
||||
}
|
||||
const keys = Object.keys(value);
|
||||
if (!keys.length) return '{}';
|
||||
const items = keys.map(
|
||||
(k) => `${inner}${JSON.stringify(k)}: ${toPythonLiteral(value[k], inner)},`,
|
||||
);
|
||||
return `{\n${items.join('\n')}\n${indent}}`;
|
||||
};
|
||||
|
||||
const shellQuote = (text) => `'${String(text).replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
export const renderCurl = (call, apiKey = API_KEY_PLACEHOLDER) =>
|
||||
[
|
||||
`curl -X POST ${shellQuote(call.url)} \\`,
|
||||
` -H ${shellQuote(`Authorization: Bearer ${apiKey}`)} \\`,
|
||||
` -H 'Content-Type: application/json' \\`,
|
||||
` -d ${shellQuote(JSON.stringify(call.body, null, 2))}`,
|
||||
].join('\n');
|
||||
|
||||
export const renderPython = (call, apiKey = API_KEY_PLACEHOLDER) =>
|
||||
[
|
||||
'import requests',
|
||||
'',
|
||||
'resp = requests.post(',
|
||||
` ${JSON.stringify(call.url)},`,
|
||||
` headers={"Authorization": ${JSON.stringify(`Bearer ${apiKey}`)}},`,
|
||||
` json=${toPythonLiteral(call.body, ' ')},`,
|
||||
' timeout=300,',
|
||||
')',
|
||||
'print(resp.json())',
|
||||
].join('\n');
|
||||
|
||||
export const renderJavaScript = (call, apiKey = API_KEY_PLACEHOLDER) =>
|
||||
[
|
||||
`const resp = await fetch(${JSON.stringify(call.url)}, {`,
|
||||
` method: 'POST',`,
|
||||
' headers: {',
|
||||
` Authorization: ${JSON.stringify(`Bearer ${apiKey}`)},`,
|
||||
` 'Content-Type': 'application/json',`,
|
||||
' },',
|
||||
` body: JSON.stringify(${indentLines(JSON.stringify(call.body, null, 2), ' ')}),`,
|
||||
'});',
|
||||
'console.log(await resp.json());',
|
||||
].join('\n');
|
||||
|
||||
/** @param {'curl'|'python'|'javascript'} lang */
|
||||
export const renderApiCode = (call, lang, apiKey = API_KEY_PLACEHOLDER) => {
|
||||
if (!call) return '';
|
||||
if (lang === 'python') return renderPython(call, apiKey);
|
||||
if (lang === 'javascript') return renderJavaScript(call, apiKey);
|
||||
return renderCurl(call, apiKey);
|
||||
};
|
||||
@@ -0,0 +1,307 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
API_CODE_NOTES,
|
||||
apiBaseUrlOf,
|
||||
buildApiCall,
|
||||
imageApiBody,
|
||||
renderApiCode,
|
||||
toPythonLiteral,
|
||||
videoApiBody,
|
||||
} from './creationApiCode.js';
|
||||
|
||||
const imageTask = {
|
||||
kind: 'image',
|
||||
id: 't1',
|
||||
model: 'gpt-image-1',
|
||||
prompt: 'fallback',
|
||||
request: {
|
||||
model: 'gpt-image-1',
|
||||
mode: 'edit',
|
||||
prompt: "a cat's hat",
|
||||
size: '1024x1024',
|
||||
quality: 'high',
|
||||
n: 2,
|
||||
seed: 7,
|
||||
background: 'transparent',
|
||||
reference_image_refs: ['cos://playground/1/a.png', 'task://x#1'],
|
||||
reference_images: ['https://signed/a.png', 'https://signed/b.png'],
|
||||
},
|
||||
};
|
||||
|
||||
const videoTask = {
|
||||
kind: 'video',
|
||||
id: 'v1',
|
||||
model: 'kling-v2',
|
||||
request: {
|
||||
model: 'kling-v2',
|
||||
mode: 'first_last_frame',
|
||||
prompt: 'run',
|
||||
duration: 5,
|
||||
resolution: '1080P',
|
||||
ratio: '16:9',
|
||||
aspect_ratio: '16:9',
|
||||
negative_prompt: 'blur',
|
||||
seed: 42,
|
||||
generate_audio: false,
|
||||
watermark: true,
|
||||
camera: 'push_in',
|
||||
image_ref: 'cos://playground/1/f.png',
|
||||
last_image_ref: 'task://img#0',
|
||||
},
|
||||
};
|
||||
|
||||
test('apiBaseUrlOf:系统服务器地址优先,否则 origin,去结尾斜杠', () => {
|
||||
assert.equal(
|
||||
apiBaseUrlOf({ server_address: 'https://api.example.com/' }, 'x'),
|
||||
'https://api.example.com',
|
||||
);
|
||||
assert.equal(
|
||||
apiBaseUrlOf({}, 'http://localhost:3000/'),
|
||||
'http://localhost:3000',
|
||||
);
|
||||
assert.equal(apiBaseUrlOf(null, ''), '');
|
||||
});
|
||||
|
||||
test('imageApiBody:快照参数 + 参考图占位 URL', () => {
|
||||
assert.deepEqual(imageApiBody(imageTask), {
|
||||
model: 'gpt-image-1',
|
||||
prompt: "a cat's hat",
|
||||
n: 2,
|
||||
size: '1024x1024',
|
||||
quality: 'high',
|
||||
seed: 7,
|
||||
background: 'transparent',
|
||||
image: ['<YOUR_IMAGE_URL_1>', '<YOUR_IMAGE_URL_2>'],
|
||||
});
|
||||
// 编辑但参考图已失效:仍给 1 个占位
|
||||
const lost = {
|
||||
...imageTask,
|
||||
request: { ...imageTask.request, reference_image_refs: [] },
|
||||
};
|
||||
assert.equal(imageApiBody(lost).image, '<YOUR_IMAGE_URL>');
|
||||
// 旧任务(无快照):用作品字段
|
||||
assert.deepEqual(
|
||||
imageApiBody({
|
||||
kind: 'image',
|
||||
model: 'dall-e-3',
|
||||
prompt: 'p',
|
||||
size: '1792x1024',
|
||||
n: 1,
|
||||
mode: 'text-to-image',
|
||||
}),
|
||||
{ model: 'dall-e-3', prompt: 'p', n: 1, size: '1792x1024' },
|
||||
);
|
||||
});
|
||||
|
||||
test('videoApiBody:标准 director 协议(metadata + media)', () => {
|
||||
assert.deepEqual(videoApiBody(videoTask), {
|
||||
model: 'kling-v2',
|
||||
prompt: 'run',
|
||||
duration: 5,
|
||||
metadata: {
|
||||
resolution: '1080P',
|
||||
aspect_ratio: '16:9',
|
||||
negative_prompt: 'blur',
|
||||
seed: 42,
|
||||
generate_audio: false,
|
||||
watermark: true,
|
||||
camera: { movement: 'push_in' },
|
||||
},
|
||||
media: [
|
||||
{ type: 'first_image', url: '<YOUR_IMAGE_URL_1>' },
|
||||
{ type: 'last_image', url: '<YOUR_IMAGE_URL_2>' },
|
||||
],
|
||||
});
|
||||
// v1 快照:audio=true → generate_audio;参考图
|
||||
assert.deepEqual(
|
||||
videoApiBody({
|
||||
kind: 'video',
|
||||
request: {
|
||||
model: 'm',
|
||||
prompt: 'p',
|
||||
audio: true,
|
||||
reference_images: ['https://a'],
|
||||
},
|
||||
}),
|
||||
{
|
||||
model: 'm',
|
||||
prompt: 'p',
|
||||
metadata: { generate_audio: true },
|
||||
media: [{ type: 'reference_image', url: '<YOUR_IMAGE_URL>' }],
|
||||
},
|
||||
);
|
||||
// 无快照:作品字段兜底
|
||||
assert.deepEqual(
|
||||
videoApiBody({
|
||||
kind: 'video',
|
||||
model: 'm',
|
||||
prompt: 'p',
|
||||
duration: 4,
|
||||
ratio: '9:16',
|
||||
resolution: '720P',
|
||||
}),
|
||||
{
|
||||
model: 'm',
|
||||
prompt: 'p',
|
||||
duration: 4,
|
||||
metadata: { resolution: '720P', aspect_ratio: '9:16' },
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('buildApiCall:路径与说明', () => {
|
||||
const img = buildApiCall(imageTask, { baseUrl: 'https://h/' });
|
||||
assert.equal(img.url, 'https://h/v1/images/generations');
|
||||
assert.deepEqual(img.notes, [API_CODE_NOTES.replaceImages]);
|
||||
const text = buildApiCall(
|
||||
{ kind: 'image', request: { model: 'm', prompt: 'p' } },
|
||||
{ baseUrl: 'https://h' },
|
||||
);
|
||||
assert.deepEqual(text.notes, []);
|
||||
const vid = buildApiCall(videoTask, { baseUrl: 'https://h' });
|
||||
assert.equal(vid.url, 'https://h/v1/video/generations');
|
||||
assert.deepEqual(vid.notes, [
|
||||
API_CODE_NOTES.replaceImages,
|
||||
API_CODE_NOTES.asyncVideo,
|
||||
]);
|
||||
});
|
||||
|
||||
test('toPythonLiteral:True/False/None 与缩进', () => {
|
||||
assert.equal(
|
||||
toPythonLiteral({ a: true, b: [null, 1] }),
|
||||
'{\n "a": True,\n "b": [\n None,\n 1,\n ],\n}',
|
||||
);
|
||||
assert.equal(toPythonLiteral([]), '[]');
|
||||
assert.equal(toPythonLiteral({}), '{}');
|
||||
});
|
||||
|
||||
test('renderApiCode:curl / Python / JS 快照(图像)', () => {
|
||||
const call = buildApiCall(
|
||||
{
|
||||
kind: 'image',
|
||||
request: {
|
||||
model: 'gpt-image-1',
|
||||
prompt: "it's",
|
||||
size: '1024x1024',
|
||||
n: 1,
|
||||
},
|
||||
},
|
||||
{ baseUrl: 'https://api.example.com' },
|
||||
);
|
||||
assert.equal(
|
||||
renderApiCode(call, 'curl'),
|
||||
[
|
||||
"curl -X POST 'https://api.example.com/v1/images/generations' \\",
|
||||
" -H 'Authorization: Bearer sk-xxx' \\",
|
||||
" -H 'Content-Type: application/json' \\",
|
||||
" -d '{",
|
||||
' "model": "gpt-image-1",',
|
||||
` "prompt": "it'\\''s",`,
|
||||
' "n": 1,',
|
||||
' "size": "1024x1024"',
|
||||
"}'",
|
||||
].join('\n'),
|
||||
);
|
||||
assert.equal(
|
||||
renderApiCode(call, 'python'),
|
||||
[
|
||||
'import requests',
|
||||
'',
|
||||
'resp = requests.post(',
|
||||
' "https://api.example.com/v1/images/generations",',
|
||||
' headers={"Authorization": "Bearer sk-xxx"},',
|
||||
' json={',
|
||||
' "model": "gpt-image-1",',
|
||||
` "prompt": "it's",`,
|
||||
' "n": 1,',
|
||||
' "size": "1024x1024",',
|
||||
' },',
|
||||
' timeout=300,',
|
||||
')',
|
||||
'print(resp.json())',
|
||||
].join('\n'),
|
||||
);
|
||||
assert.equal(
|
||||
renderApiCode(call, 'javascript'),
|
||||
[
|
||||
'const resp = await fetch("https://api.example.com/v1/images/generations", {',
|
||||
" method: 'POST',",
|
||||
' headers: {',
|
||||
' Authorization: "Bearer sk-xxx",',
|
||||
" 'Content-Type': 'application/json',",
|
||||
' },',
|
||||
' body: JSON.stringify({',
|
||||
' "model": "gpt-image-1",',
|
||||
` "prompt": "it's",`,
|
||||
' "n": 1,',
|
||||
' "size": "1024x1024"',
|
||||
' }),',
|
||||
'});',
|
||||
'console.log(await resp.json());',
|
||||
].join('\n'),
|
||||
);
|
||||
});
|
||||
|
||||
test('renderApiCode:视频 Python 快照(嵌套 metadata / media)', () => {
|
||||
const call = buildApiCall(
|
||||
{
|
||||
kind: 'video',
|
||||
request: {
|
||||
model: 'm',
|
||||
prompt: 'p',
|
||||
duration: 5,
|
||||
watermark: true,
|
||||
image_ref: 'cos://x',
|
||||
},
|
||||
},
|
||||
{ baseUrl: 'https://h' },
|
||||
);
|
||||
assert.equal(
|
||||
renderApiCode(call, 'python'),
|
||||
[
|
||||
'import requests',
|
||||
'',
|
||||
'resp = requests.post(',
|
||||
' "https://h/v1/video/generations",',
|
||||
' headers={"Authorization": "Bearer sk-xxx"},',
|
||||
' json={',
|
||||
' "model": "m",',
|
||||
' "prompt": "p",',
|
||||
' "duration": 5,',
|
||||
' "metadata": {',
|
||||
' "watermark": True,',
|
||||
' },',
|
||||
' "media": [',
|
||||
' {',
|
||||
' "type": "first_image",',
|
||||
' "url": "<YOUR_IMAGE_URL>",',
|
||||
' },',
|
||||
' ],',
|
||||
' },',
|
||||
' timeout=300,',
|
||||
')',
|
||||
'print(resp.json())',
|
||||
].join('\n'),
|
||||
);
|
||||
assert.equal(renderApiCode(null, 'curl'), '');
|
||||
});
|
||||
@@ -0,0 +1,416 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 图像对比生成(WP C-2,方案 §4.2)纯函数:可选模型、参数交集、逐模型参数解析、
|
||||
// 估价 items[]、batch_id、作品流成组、合计阈值确认。
|
||||
// 不依赖 React / 浏览器,node --test 覆盖(creationCompare.test.js)。
|
||||
|
||||
import {
|
||||
buildImageRequest,
|
||||
composeParams,
|
||||
isModeEnabled,
|
||||
modelNameOf,
|
||||
quoteRequestOf,
|
||||
referenceMaxOf,
|
||||
requestParamsForMode,
|
||||
sizePresetsOf,
|
||||
customSizeRangeOf,
|
||||
normalizeSize,
|
||||
} from '../image/imageCreation.js';
|
||||
import {
|
||||
getParamDefault,
|
||||
optionKey,
|
||||
optionValue,
|
||||
} from '../../components/creation/params/constraints.js';
|
||||
|
||||
export const COMPARE_MIN = 2;
|
||||
export const COMPARE_MAX = 4;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 可选模型
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 模型能否加入对比(只有支持当前模式与已上传图片的模型可选)。
|
||||
* @returns {{ key: string, values?: object } | null} 不可选原因(i18n key + 插值),可选返回 null
|
||||
*/
|
||||
export const compareBlockOf = (
|
||||
model,
|
||||
{ mode = 'text2image', refCount = 0 } = {},
|
||||
) => {
|
||||
if (!model || !model.model) return { key: '模型不可用' };
|
||||
if (model.level_locked) return { key: '需升级' };
|
||||
if (!isModeEnabled(model, mode)) {
|
||||
return { key: mode === 'edit' ? '不支持图生图' : '不支持文生图' };
|
||||
}
|
||||
if (mode === 'edit') {
|
||||
const max = referenceMaxOf(model, 'edit');
|
||||
if (refCount > max) {
|
||||
return { key: '最多支持 {{n}} 张参考图', values: { n: max } };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** 勾选 / 取消一个对比模型;超过上限时不变并返回 full=true。 */
|
||||
export const toggleCompareModel = (selected, name, max = COMPARE_MAX) => {
|
||||
const list = Array.isArray(selected) ? selected : [];
|
||||
if (!name) return { selected: list, full: false };
|
||||
if (list.includes(name)) {
|
||||
return { selected: list.filter((n) => n !== name), full: false };
|
||||
}
|
||||
if (list.length >= max) return { selected: list, full: true };
|
||||
return { selected: [...list, name], full: false };
|
||||
};
|
||||
|
||||
/** 选中的模型名 → schema 模型(保持勾选顺序;已不可选的剔除)。 */
|
||||
export const selectedCompareModels = (models, names, ctx) => {
|
||||
const byName = new Map((models || []).map((m) => [m && m.model, m]));
|
||||
return (names || [])
|
||||
.map((n) => byName.get(n))
|
||||
.filter((m) => m && !compareBlockOf(m, ctx));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 参数交集
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const findIn = (model, key, mode) =>
|
||||
requestParamsForMode(model, mode).find((p) => p.key === key) || null;
|
||||
|
||||
const hasOptions = (p) => Array.isArray(p.options) && p.options.length > 0;
|
||||
|
||||
const intersectOptions = (base, others) => {
|
||||
const sets = others.map(
|
||||
(p) => new Set((p.options || []).map((o) => optionKey(optionValue(o)))),
|
||||
);
|
||||
return base.options.filter((o) =>
|
||||
sets.every((set) => set.has(optionKey(optionValue(o)))),
|
||||
);
|
||||
};
|
||||
|
||||
const defaultWithin = (base, options) => {
|
||||
const keys = options.map((o) => optionKey(optionValue(o)));
|
||||
if (base.default !== undefined && keys.includes(optionKey(base.default))) {
|
||||
return base.default;
|
||||
}
|
||||
return options.length ? optionValue(options[0]) : undefined;
|
||||
};
|
||||
|
||||
const intersectSize = (base, others) => {
|
||||
const all = [base, ...others];
|
||||
const presetSets = others.map(
|
||||
(p) => new Set(sizePresetsOf(p).map((s) => s.value.toLowerCase())),
|
||||
);
|
||||
const options = (base.options || []).filter((o) => {
|
||||
const v = String(optionValue(o) || '').toLowerCase();
|
||||
return v && presetSets.every((set) => set.has(v));
|
||||
});
|
||||
const ranges = all.map(customSizeRangeOf);
|
||||
let custom = null;
|
||||
if (ranges.every(Boolean)) {
|
||||
const min = Math.max(...ranges.map((r) => r.min));
|
||||
const max = Math.min(...ranges.map((r) => r.max));
|
||||
const step = Math.max(...ranges.map((r) => r.step));
|
||||
if (min <= max) custom = { min, max, step };
|
||||
}
|
||||
if (!options.length && !custom) return null;
|
||||
const out = { ...base, options };
|
||||
if (custom) out.custom_size = custom;
|
||||
else delete out.custom_size;
|
||||
out.default = defaultWithin(base, options);
|
||||
if (out.default === undefined) delete out.default;
|
||||
return out;
|
||||
};
|
||||
|
||||
const intersectRange = (base, others) => {
|
||||
const all = [base, ...others];
|
||||
const mins = all.map((p) => Number(p.min)).filter(Number.isFinite);
|
||||
const maxs = all.map((p) => Number(p.max)).filter(Number.isFinite);
|
||||
const out = { ...base };
|
||||
if (mins.length) out.min = Math.max(...mins);
|
||||
if (maxs.length) out.max = Math.min(...maxs);
|
||||
if (mins.length && maxs.length && out.min > out.max) return null;
|
||||
const d = Number(base.default);
|
||||
if (Number.isFinite(d)) {
|
||||
if (mins.length && d < out.min) out.default = out.min;
|
||||
if (maxs.length && d > out.max) out.default = out.max;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* 所选模型共同支持的参数(方案 §4.2):键与类型在每个模型中都存在;有选项的取选项交集
|
||||
* (交集为空则不显示),尺寸取预设交集与自定义范围交集,数值取范围交集。
|
||||
* 以第一个模型的参数为基准(标签 / 顺序),默认值不在交集内时改为交集第一项。
|
||||
* 只考虑适用于当前模式的参数(schema modes):任一模型在该模式下不支持的参数不进交集。
|
||||
*/
|
||||
export const sharedParamsOf = (models, { mode = 'text2image' } = {}) => {
|
||||
const list = (models || []).filter(Boolean);
|
||||
if (!list.length) return [];
|
||||
const [first, ...rest] = list;
|
||||
const out = [];
|
||||
requestParamsForMode(first, mode).forEach((base) => {
|
||||
const others = rest.map((m) => findIn(m, base.key, mode));
|
||||
if (others.some((p) => !p || p.type !== base.type)) return;
|
||||
if (base.type === 'size') {
|
||||
const merged = intersectSize(base, others);
|
||||
if (merged) out.push(merged);
|
||||
return;
|
||||
}
|
||||
if (hasOptions(base) || others.some(hasOptions)) {
|
||||
if (!hasOptions(base) || !others.every(hasOptions)) return;
|
||||
const options = intersectOptions(base, others);
|
||||
if (!options.length) return;
|
||||
const merged = {
|
||||
...base,
|
||||
options,
|
||||
default: defaultWithin(base, options),
|
||||
};
|
||||
out.push(merged);
|
||||
return;
|
||||
}
|
||||
if (base.min !== undefined || base.max !== undefined) {
|
||||
const merged = intersectRange(base, others);
|
||||
if (merged) out.push(merged);
|
||||
return;
|
||||
}
|
||||
out.push({ ...base });
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
const isValidShared = (param, value) => {
|
||||
if (value === undefined || value === null || value === '') return false;
|
||||
if (param.type === 'size') {
|
||||
const r = normalizeSize(param, value);
|
||||
return Boolean(r.value) && !r.changed;
|
||||
}
|
||||
if (hasOptions(param)) {
|
||||
return param.options.some(
|
||||
(o) => optionKey(optionValue(o)) === optionKey(value),
|
||||
);
|
||||
}
|
||||
const n = Number(value);
|
||||
if (param.min !== undefined && Number.isFinite(n) && n < Number(param.min)) {
|
||||
return false;
|
||||
}
|
||||
if (param.max !== undefined && Number.isFinite(n) && n > Number(param.max)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 共同参数的当前取值:依次取第一个在交集内合法的候选(用户在对比模式中设置的值 →
|
||||
* 创作台当前值 → 交集默认值)。没有合法值且无默认(如随机种子)的参数不写出。
|
||||
*/
|
||||
export const sharedValuesOf = (shared, ...candidates) => {
|
||||
const out = {};
|
||||
(shared || []).forEach((p) => {
|
||||
const hit = candidates.find((c) => c && isValidShared(p, c[p.key]));
|
||||
if (hit) {
|
||||
out[p.key] = hit[p.key];
|
||||
return;
|
||||
}
|
||||
const d =
|
||||
p.type === 'size'
|
||||
? normalizeSize(p, undefined).value
|
||||
: getParamDefault(p);
|
||||
if (d !== undefined) out[p.key] = d;
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
/** 只保留共同参数中的取值(提交 / 切换模型时作为"本次会话手动设置的值")。 */
|
||||
export const pickSharedValues = (shared, values) => {
|
||||
const out = {};
|
||||
(shared || []).forEach((p) => {
|
||||
if (values && values[p.key] !== undefined) out[p.key] = values[p.key];
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 逐模型解析与提交
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 每个模型的实际参数与请求体:共同参数用创作台的取值(优先级 1),其余参数按该模型记忆 / 默认值
|
||||
* (方案 §4.3 优先级与吸附);不合法的值吸附并记入 adjustments。
|
||||
*
|
||||
* @param {object[]} models 对比模型(schema)
|
||||
* @param {{ mode, prompt, params, paramMemory, modelName, images }} form 创作台表单(统一形状)
|
||||
* @param {object} sharedValues 共同参数取值
|
||||
* @param {string} batchId
|
||||
* @returns {Array<{ model: object, values: object, adjustments: object[], payload: object }>}
|
||||
*/
|
||||
export const resolveCompareEntries = (models, form, sharedValues, batchId) => {
|
||||
const f = form || {};
|
||||
const memoryOf = (name) => {
|
||||
if (name === f.modelName) return f.params || {};
|
||||
return (f.paramMemory && f.paramMemory[name]) || {};
|
||||
};
|
||||
return (models || []).filter(Boolean).map((model) => {
|
||||
const name = modelNameOf(model);
|
||||
const { values, adjustments } = composeParams(model, {
|
||||
sessionValues: sharedValues || {},
|
||||
memory: memoryOf(name),
|
||||
});
|
||||
const payload = buildImageRequest(model, {
|
||||
mode: f.mode,
|
||||
prompt: f.prompt,
|
||||
params: values,
|
||||
references: (f.images && f.images.reference_images) || [],
|
||||
});
|
||||
if (batchId) payload.batch_id = batchId;
|
||||
return { model, values, adjustments, payload };
|
||||
});
|
||||
};
|
||||
|
||||
/** 对比估价请求(quote items[],与逐模型请求体同一参数)。 */
|
||||
export const compareQuoteRequest = (entries) => {
|
||||
const items = (entries || [])
|
||||
.map((e) => quoteRequestOf(e.model, e.payload))
|
||||
.filter(Boolean)
|
||||
.map((q) => q.items[0]);
|
||||
return items.length ? { kind: 'image', items } : null;
|
||||
};
|
||||
|
||||
/** 摘要行:参数文本(尺寸 / 画质 / 张数 / 种子),供提交前确认。 */
|
||||
export const compareParamSummary = (payload) => {
|
||||
const p = payload || {};
|
||||
const parts = [];
|
||||
if (p.size) parts.push(String(p.size).replace(/x/i, '×'));
|
||||
if (p.quality) parts.push(String(p.quality));
|
||||
if (Number(p.n) > 1) parts.push(`×${p.n}`);
|
||||
if (p.seed !== undefined) parts.push(`seed ${p.seed}`);
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
/** 新的批次标识(UUID v4,后端按 UUID 格式校验)。 */
|
||||
export const newBatchId = (cryptoObj) => {
|
||||
const c =
|
||||
cryptoObj ||
|
||||
(typeof globalThis !== 'undefined' ? globalThis.crypto : undefined);
|
||||
if (c && typeof c.randomUUID === 'function') return c.randomUUID();
|
||||
const bytes = new Uint8Array(16);
|
||||
if (c && typeof c.getRandomValues === 'function') c.getRandomValues(bytes);
|
||||
else
|
||||
for (let i = 0; i < 16; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 合计额度是否需要二次确认(系统设置 ExperienceCenterBatchConfirmThreshold,quota;<=0 不确认)。
|
||||
* 只有多张(n>1)或对比生成才确认,单张不打扰。
|
||||
*/
|
||||
export const needsBatchConfirm = (
|
||||
totalQuota,
|
||||
threshold,
|
||||
{ batch = false } = {},
|
||||
) => {
|
||||
const limit = Number(threshold);
|
||||
const total = Number(totalQuota);
|
||||
if (!batch || !Number.isFinite(limit) || limit <= 0) return false;
|
||||
return Number.isFinite(total) && total > limit;
|
||||
};
|
||||
|
||||
/**
|
||||
* 自动提交(再生成 / 换种子再来)前的金额确认决策,与手动提交共用 needsBatchConfirm 阈值。
|
||||
* - 'submit':单张、阈值关闭,或估价未超阈值,直接提交;
|
||||
* - 'wait':多张且估价尚未对应当前参数(加载中 / 仍是上一次参数的结果),等估价返回;
|
||||
* - 'confirm':合计超过阈值,弹出与手动提交相同的二次确认;
|
||||
* - 'manual':多张但拿不到估价(失败 / 无估价请求),不自动提交,只回填由用户确认。
|
||||
* @param {{ n?: number|string, threshold?: number|string, quote?: object|null, quoteFresh?: boolean, quoteFailed?: boolean }} input
|
||||
* @returns {'submit'|'wait'|'confirm'|'manual'}
|
||||
*/
|
||||
export const autoSubmitDecision = ({
|
||||
n,
|
||||
threshold,
|
||||
quote = null,
|
||||
quoteFresh = false,
|
||||
quoteFailed = false,
|
||||
} = {}) => {
|
||||
const count = Number(n) || 1;
|
||||
const limit = Number(threshold);
|
||||
if (count <= 1 || !Number.isFinite(limit) || limit <= 0) return 'submit';
|
||||
if (!quoteFresh) return 'wait';
|
||||
if (quoteFailed || !quote) return 'manual';
|
||||
return needsBatchConfirm(quote.total, limit, { batch: true })
|
||||
? 'confirm'
|
||||
: 'submit';
|
||||
};
|
||||
|
||||
/**
|
||||
* 手动提交(CreationDock 生成按钮 / 快捷键)前的金额确认决策。与 autoSubmitDecision 同一口径,
|
||||
* 只是估价拿不到(失败 / 无估价请求)时照常提交(估价永远不阻止手动提交):
|
||||
* - 'wait':多张且估价仍是上一次参数的结果 / 加载中,不能用旧估价跳过确认,等估价返回再决定;
|
||||
* - 'confirm' / 'submit':同 autoSubmitDecision。
|
||||
* @returns {'submit'|'wait'|'confirm'}
|
||||
*/
|
||||
export const manualSubmitDecision = (input) => {
|
||||
const decision = autoSubmitDecision(input);
|
||||
return decision === 'manual' ? 'submit' : decision;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 作品流成组
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 把同一 batch_id 的作品合成一行(保持首个成员的位置);批次在本组中只有 1 个作品时按普通卡片显示。
|
||||
* @returns {Array<{ key: string, type: 'task', task } | { key: string, type: 'batch', batchId: string, tasks: object[] }>}
|
||||
*/
|
||||
export const groupBatchRows = (tasks) => {
|
||||
const list = Array.isArray(tasks) ? tasks : [];
|
||||
const counts = new Map();
|
||||
list.forEach((task) => {
|
||||
if (task && task.batchId) {
|
||||
counts.set(task.batchId, (counts.get(task.batchId) || 0) + 1);
|
||||
}
|
||||
});
|
||||
const rows = [];
|
||||
const byBatch = new Map();
|
||||
list.forEach((task) => {
|
||||
if (!task) return;
|
||||
const id = task.batchId;
|
||||
if (id && counts.get(id) > 1) {
|
||||
let row = byBatch.get(id);
|
||||
if (!row) {
|
||||
row = { key: `batch-${id}`, type: 'batch', batchId: id, tasks: [] };
|
||||
byBatch.set(id, row);
|
||||
rows.push(row);
|
||||
}
|
||||
row.tasks.push(task);
|
||||
return;
|
||||
}
|
||||
rows.push({ key: task.id, type: 'task', task });
|
||||
});
|
||||
return rows;
|
||||
};
|
||||
|
||||
/** 批次中可进入对比视图的作品(已成功且有图)。 */
|
||||
export const comparableBatchTasks = (tasks) =>
|
||||
(tasks || []).filter(
|
||||
(task) => task && task.status === 'success' && task.images?.[0]?.url,
|
||||
);
|
||||
@@ -0,0 +1,369 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
COMPARE_MAX,
|
||||
autoSubmitDecision,
|
||||
compareBlockOf,
|
||||
compareParamSummary,
|
||||
compareQuoteRequest,
|
||||
comparableBatchTasks,
|
||||
groupBatchRows,
|
||||
needsBatchConfirm,
|
||||
newBatchId,
|
||||
pickSharedValues,
|
||||
resolveCompareEntries,
|
||||
selectedCompareModels,
|
||||
sharedParamsOf,
|
||||
sharedValuesOf,
|
||||
toggleCompareModel,
|
||||
} from './creationCompare.js';
|
||||
|
||||
const sizeParam = (options, extra = {}) => ({
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options,
|
||||
default: options[0],
|
||||
...extra,
|
||||
});
|
||||
|
||||
const gpt = {
|
||||
model: 'gpt-image-1',
|
||||
modes: ['text2image', 'edit'],
|
||||
inputs: { reference_images: { modes: ['edit'], max: 4 } },
|
||||
params: [
|
||||
sizeParam(['1024x1024', '1536x1024', '1024x1536']),
|
||||
{
|
||||
key: 'quality',
|
||||
type: 'chips',
|
||||
options: ['low', 'medium', 'high'],
|
||||
default: 'high',
|
||||
},
|
||||
{ key: 'n', type: 'slider', min: 1, max: 4, default: 1 },
|
||||
{ key: 'background', type: 'chips', options: ['auto', 'transparent'] },
|
||||
],
|
||||
};
|
||||
const seedream = {
|
||||
model: 'seedream-4',
|
||||
modes: ['text2image', 'edit'],
|
||||
inputs: { reference_images: { modes: ['edit'], max: 1 } },
|
||||
params: [
|
||||
sizeParam(['1024x1024', '2048x2048', '1536x1024'], {
|
||||
custom_size: { min: 512, max: 4096, step: 8 },
|
||||
}),
|
||||
{
|
||||
key: 'quality',
|
||||
type: 'chips',
|
||||
options: ['standard', 'high'],
|
||||
default: 'standard',
|
||||
},
|
||||
{ key: 'n', type: 'slider', min: 1, max: 2, default: 1 },
|
||||
{ key: 'seed', type: 'seed' },
|
||||
],
|
||||
};
|
||||
const dalle = {
|
||||
model: 'dall-e-3',
|
||||
modes: ['text2image'],
|
||||
params: [
|
||||
sizeParam(['1024x1024', '1792x1024']),
|
||||
{ key: 'quality', type: 'chips', options: ['standard', 'hd'] },
|
||||
],
|
||||
};
|
||||
const locked = { ...dalle, model: 'locked', level_locked: true };
|
||||
|
||||
test('compareBlockOf:模式 / 参考图张数 / 等级', () => {
|
||||
assert.equal(compareBlockOf(gpt, { mode: 'text2image' }), null);
|
||||
assert.deepEqual(compareBlockOf(dalle, { mode: 'edit', refCount: 1 }), {
|
||||
key: '不支持图生图',
|
||||
});
|
||||
assert.deepEqual(compareBlockOf(seedream, { mode: 'edit', refCount: 2 }), {
|
||||
key: '最多支持 {{n}} 张参考图',
|
||||
values: { n: 1 },
|
||||
});
|
||||
assert.equal(compareBlockOf(seedream, { mode: 'edit', refCount: 1 }), null);
|
||||
assert.deepEqual(compareBlockOf(locked, {}), { key: '需升级' });
|
||||
assert.deepEqual(compareBlockOf(null), { key: '模型不可用' });
|
||||
});
|
||||
|
||||
test('toggleCompareModel / selectedCompareModels:上限与剔除不可选', () => {
|
||||
let r = toggleCompareModel([], 'a');
|
||||
assert.deepEqual(r, { selected: ['a'], full: false });
|
||||
r = toggleCompareModel(['a', 'b', 'c', 'd'], 'e');
|
||||
assert.equal(r.full, true);
|
||||
assert.equal(r.selected.length, COMPARE_MAX);
|
||||
assert.deepEqual(toggleCompareModel(['a', 'b'], 'a').selected, ['b']);
|
||||
const models = [gpt, seedream, dalle, locked];
|
||||
assert.deepEqual(
|
||||
selectedCompareModels(models, ['dall-e-3', 'gpt-image-1', 'locked', 'x'], {
|
||||
mode: 'text2image',
|
||||
}).map((m) => m.model),
|
||||
['dall-e-3', 'gpt-image-1'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
selectedCompareModels(models, ['dall-e-3', 'gpt-image-1'], {
|
||||
mode: 'edit',
|
||||
refCount: 1,
|
||||
}).map((m) => m.model),
|
||||
['gpt-image-1'],
|
||||
);
|
||||
});
|
||||
|
||||
test('sharedParamsOf:键交集 + 选项交集 + 范围交集', () => {
|
||||
const shared = sharedParamsOf([gpt, seedream]);
|
||||
assert.deepEqual(
|
||||
shared.map((p) => p.key),
|
||||
['size', 'quality', 'n'],
|
||||
);
|
||||
const size = shared.find((p) => p.key === 'size');
|
||||
assert.deepEqual(size.options, ['1024x1024', '1536x1024']);
|
||||
assert.equal(
|
||||
size.custom_size,
|
||||
undefined,
|
||||
'gpt 不支持自定义尺寸,交集也不支持',
|
||||
);
|
||||
const quality = shared.find((p) => p.key === 'quality');
|
||||
// requestParamsOf 给画质补了显示名
|
||||
assert.deepEqual(quality.options, [{ value: 'high', label: '高' }]);
|
||||
assert.equal(quality.default, 'high');
|
||||
const n = shared.find((p) => p.key === 'n');
|
||||
assert.equal(n.min, 1);
|
||||
assert.equal(n.max, 2);
|
||||
// 选项交集为空的参数不显示
|
||||
assert.deepEqual(
|
||||
sharedParamsOf([gpt, dalle]).map((p) => p.key),
|
||||
['size'],
|
||||
);
|
||||
// 单个模型 = 自身参数
|
||||
assert.equal(sharedParamsOf([seedream]).length, 4);
|
||||
assert.deepEqual(sharedParamsOf([]), []);
|
||||
// 两个都支持自定义尺寸:范围取交集
|
||||
const a = {
|
||||
...seedream,
|
||||
params: [
|
||||
sizeParam(['1024x1024'], {
|
||||
custom_size: { min: 256, max: 2048, step: 16 },
|
||||
}),
|
||||
],
|
||||
};
|
||||
const merged = sharedParamsOf([seedream, a])[0];
|
||||
assert.deepEqual(merged.custom_size, { min: 512, max: 2048, step: 16 });
|
||||
});
|
||||
|
||||
test('sharedValuesOf:对比值 → 创作台值 → 默认', () => {
|
||||
const shared = sharedParamsOf([gpt, seedream]);
|
||||
assert.deepEqual(sharedValuesOf(shared, {}, {}), {
|
||||
size: '1024x1024',
|
||||
quality: 'high',
|
||||
n: 1,
|
||||
});
|
||||
assert.deepEqual(
|
||||
sharedValuesOf(
|
||||
shared,
|
||||
{ quality: 'low', n: 2 },
|
||||
{ size: '1536x1024', quality: 'high', n: 4 },
|
||||
),
|
||||
{ size: '1536x1024', quality: 'high', n: 2 },
|
||||
);
|
||||
assert.deepEqual(pickSharedValues(shared, { size: 'x', seed: 1, n: 2 }), {
|
||||
size: 'x',
|
||||
n: 2,
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveCompareEntries:共同参数统一,其余按模型记忆 / 默认;带 batch_id', () => {
|
||||
const form = {
|
||||
modelName: 'gpt-image-1',
|
||||
mode: 'text2image',
|
||||
prompt: 'a cat',
|
||||
params: { size: '1536x1024', quality: 'high', background: 'transparent' },
|
||||
paramMemory: { 'seedream-4': { seed: 42 } },
|
||||
images: { reference_images: [] },
|
||||
};
|
||||
const shared = sharedParamsOf([gpt, seedream]);
|
||||
const values = sharedValuesOf(shared, {}, form.params);
|
||||
const entries = resolveCompareEntries([gpt, seedream], form, values, 'b-1');
|
||||
assert.equal(entries.length, 2);
|
||||
assert.deepEqual(entries[0].payload, {
|
||||
model: 'gpt-image-1',
|
||||
prompt: 'a cat',
|
||||
source: 'creation_studio',
|
||||
size: '1536x1024',
|
||||
quality: 'high',
|
||||
n: 1,
|
||||
background: 'transparent',
|
||||
batch_id: 'b-1',
|
||||
});
|
||||
assert.deepEqual(entries[1].payload, {
|
||||
model: 'seedream-4',
|
||||
prompt: 'a cat',
|
||||
source: 'creation_studio',
|
||||
size: '1536x1024',
|
||||
quality: 'high',
|
||||
n: 1,
|
||||
seed: 42,
|
||||
batch_id: 'b-1',
|
||||
});
|
||||
const quote = compareQuoteRequest(entries);
|
||||
assert.deepEqual(quote, {
|
||||
kind: 'image',
|
||||
items: [
|
||||
{
|
||||
model: 'gpt-image-1',
|
||||
mode: 'text2image',
|
||||
params: { size: '1536x1024', quality: 'high' },
|
||||
n: 1,
|
||||
},
|
||||
{
|
||||
model: 'seedream-4',
|
||||
mode: 'text2image',
|
||||
params: { size: '1536x1024', quality: 'high' },
|
||||
n: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(compareQuoteRequest([]), null);
|
||||
assert.equal(
|
||||
compareParamSummary(entries[1].payload),
|
||||
'1536×1024 · high · seed 42',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveCompareEntries:编辑模式按各模型上限提交参考图', () => {
|
||||
const form = {
|
||||
modelName: 'gpt-image-1',
|
||||
mode: 'edit',
|
||||
prompt: 'p',
|
||||
params: {},
|
||||
images: {
|
||||
reference_images: [{ id: 'a', status: 'ready', ref: 'task://t1' }],
|
||||
},
|
||||
};
|
||||
const entries = resolveCompareEntries([gpt, seedream], form, {}, '');
|
||||
assert.equal(entries[0].payload.image, 'task://t1');
|
||||
assert.equal(entries[1].payload.image, 'task://t1');
|
||||
assert.equal(entries[0].payload.batch_id, undefined);
|
||||
});
|
||||
|
||||
test('newBatchId:UUID v4 格式(有无 randomUUID 都可)', () => {
|
||||
const re =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
assert.match(newBatchId(), re);
|
||||
assert.match(newBatchId({ getRandomValues: (b) => b.fill(255) }), re);
|
||||
assert.match(newBatchId({}), re);
|
||||
});
|
||||
|
||||
test('needsBatchConfirm:只对多张 / 对比生成且超过阈值', () => {
|
||||
assert.equal(needsBatchConfirm(200, 100, { batch: true }), true);
|
||||
assert.equal(needsBatchConfirm(100, 100, { batch: true }), false);
|
||||
assert.equal(needsBatchConfirm(200, 100), false);
|
||||
assert.equal(needsBatchConfirm(200, '0', { batch: true }), false);
|
||||
assert.equal(needsBatchConfirm(200, '', { batch: true }), false);
|
||||
assert.equal(needsBatchConfirm(200, '136986', { batch: true }), false);
|
||||
assert.equal(needsBatchConfirm(200000, '136986', { batch: true }), true);
|
||||
});
|
||||
|
||||
test('autoSubmitDecision:再生成 / 换种子与手动提交同一金额阈值', () => {
|
||||
const big = { total: 200000 };
|
||||
const small = { total: 1000 };
|
||||
// 单张 / 阈值关闭:直接提交,不等估价
|
||||
assert.equal(autoSubmitDecision({ n: 1, threshold: 136986 }), 'submit');
|
||||
assert.equal(autoSubmitDecision({ threshold: 136986 }), 'submit');
|
||||
assert.equal(
|
||||
autoSubmitDecision({ n: 4, threshold: 0, quote: big, quoteFresh: true }),
|
||||
'submit',
|
||||
);
|
||||
assert.equal(autoSubmitDecision({ n: 4, threshold: '' }), 'submit');
|
||||
// 多张:估价未对应当前参数时等待(不能用上一次参数的估价)
|
||||
assert.equal(
|
||||
autoSubmitDecision({ n: 4, threshold: 136986, quote: small }),
|
||||
'wait',
|
||||
);
|
||||
// 超阈值确认,未超直接提交(与 needsBatchConfirm 一致,等于阈值不确认)
|
||||
assert.equal(
|
||||
autoSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 136986,
|
||||
quote: big,
|
||||
quoteFresh: true,
|
||||
}),
|
||||
'confirm',
|
||||
);
|
||||
assert.equal(
|
||||
autoSubmitDecision({
|
||||
n: '2',
|
||||
threshold: '136986',
|
||||
quote: { total: 136986 },
|
||||
quoteFresh: true,
|
||||
}),
|
||||
'submit',
|
||||
);
|
||||
assert.equal(
|
||||
autoSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 136986,
|
||||
quote: small,
|
||||
quoteFresh: true,
|
||||
}),
|
||||
'submit',
|
||||
);
|
||||
// 估价失败 / 无估价:不自动提交
|
||||
assert.equal(
|
||||
autoSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 136986,
|
||||
quoteFresh: true,
|
||||
quoteFailed: true,
|
||||
}),
|
||||
'manual',
|
||||
);
|
||||
assert.equal(
|
||||
autoSubmitDecision({ n: 4, threshold: 136986, quoteFresh: true }),
|
||||
'manual',
|
||||
);
|
||||
});
|
||||
|
||||
test('groupBatchRows:同批次成组,位置取首个成员;单个成员按普通卡片', () => {
|
||||
const tasks = [
|
||||
{ id: '1', batchId: 'b' },
|
||||
{ id: '2' },
|
||||
{ id: '3', batchId: 'b' },
|
||||
{ id: '4', batchId: 'c' },
|
||||
{ id: '5', batchId: 'b' },
|
||||
];
|
||||
const rows = groupBatchRows(tasks);
|
||||
assert.deepEqual(
|
||||
rows.map((r) =>
|
||||
r.type === 'batch'
|
||||
? `${r.batchId}:${r.tasks.map((t) => t.id).join('')}`
|
||||
: r.task.id,
|
||||
),
|
||||
['b:135', '2', '4'],
|
||||
);
|
||||
assert.deepEqual(groupBatchRows(null), []);
|
||||
assert.deepEqual(
|
||||
comparableBatchTasks([
|
||||
{ id: 'a', status: 'success', images: [{ url: 'u' }] },
|
||||
{ id: 'b', status: 'failed', images: [] },
|
||||
{ id: 'c', status: 'success', images: [{ url: '' }] },
|
||||
]).map((t) => t.id),
|
||||
['a'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,597 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 创作台(CreationDock,WP B-3)的纯函数:先传图时的模式推断、图片角色记忆、
|
||||
// 「图N」引用改写、模板参数套用。无 React / i18n 依赖,可直接 node --test。
|
||||
|
||||
import * as video from '../video/videoCreation.js';
|
||||
import * as image from '../image/imageCreation.js';
|
||||
import { optionValue } from '../../components/creation/params/constraints.js';
|
||||
|
||||
/** 图片角色:首帧 / 首尾帧(frames)或参考图 / 编辑(reference)。 */
|
||||
export const ROLE_FRAMES = 'frames';
|
||||
export const ROLE_REFERENCE = 'reference';
|
||||
|
||||
const MODE_ROLES = {
|
||||
image2video: ROLE_FRAMES,
|
||||
first_last_frame: ROLE_FRAMES,
|
||||
reference2video: ROLE_REFERENCE,
|
||||
edit: ROLE_REFERENCE,
|
||||
};
|
||||
|
||||
/** 模式对应的图片角色;文生模式返回 ''。 */
|
||||
export const roleOfMode = (mode) => MODE_ROLES[mode] || '';
|
||||
|
||||
/** 「图1」「图2」指代只在参考图 / 编辑模式下使用(方案 §4.4)。 */
|
||||
export const usesImageRefs = (mode) => roleOfMode(mode) === ROLE_REFERENCE;
|
||||
|
||||
const modelModes = (model) => (model && model.modes) || [];
|
||||
|
||||
/**
|
||||
* 某模式可接收的图片张数:{ min, max }。文生模式 { 0, 0 }。
|
||||
* 首尾帧必须两张都有;参考图 / 编辑至少一张。
|
||||
*/
|
||||
export const modeCapacity = (kind, model, mode) => {
|
||||
if (kind === 'image') {
|
||||
const max = image.referenceMaxOf(model, mode);
|
||||
return { min: max > 0 ? 1 : 0, max };
|
||||
}
|
||||
const a = video.activeInputsOf(model, mode);
|
||||
const frames = (a.first_frame ? 1 : 0) + (a.last_frame ? 1 : 0);
|
||||
if (frames > 0) return { min: frames, max: frames + a.reference_max };
|
||||
return { min: a.reference_max > 0 ? 1 : 0, max: a.reference_max };
|
||||
};
|
||||
|
||||
/** 模型是否接受图片输入(任一可用模式)。 */
|
||||
export const acceptsImages = (kind, model) =>
|
||||
modelModes(model).some((m) => modeCapacity(kind, model, m).max > 0);
|
||||
|
||||
/** 对 count 张图片合法的模式(按模型 modes 顺序)。 */
|
||||
export const legalModesForCount = (kind, model, count) => {
|
||||
if (!model || !(count > 0)) return [];
|
||||
return modelModes(model).filter((m) => {
|
||||
const c = modeCapacity(kind, model, m);
|
||||
return c.max > 0 && count >= c.min && count <= c.max;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 当前模式下按顺序放置 count 张新图的目标槽(只用空着的、当前模式会提交的槽)。
|
||||
* @returns {Array<{ key: string, index?: number }>}
|
||||
*/
|
||||
export const emptyTargetsOf = (kind, model, mode, images, count) => {
|
||||
const imgs = images || {};
|
||||
const out = [];
|
||||
if (kind === 'video') {
|
||||
const a = video.activeInputsOf(model, mode);
|
||||
if (a.first_frame && !imgs.first_frame) out.push({ key: 'first_frame' });
|
||||
if (a.last_frame && !imgs.last_frame) out.push({ key: 'last_frame' });
|
||||
const refs = (imgs.reference_images || []).length;
|
||||
for (let i = refs; i < a.reference_max; i += 1) {
|
||||
out.push({ key: 'reference_images' });
|
||||
}
|
||||
} else {
|
||||
const max = image.referenceMaxOf(model, mode);
|
||||
const refs = (imgs.reference_images || []).length;
|
||||
for (let i = refs; i < max; i += 1) out.push({ key: 'reference_images' });
|
||||
}
|
||||
return out.slice(0, Math.max(0, count));
|
||||
};
|
||||
|
||||
const freshTargets = (kind, model, mode, count) =>
|
||||
emptyTargetsOf(kind, model, mode, {}, count);
|
||||
|
||||
/** 当前模式会提交的已有图片,按 首帧 → 尾帧 → 参考图 顺序。 */
|
||||
export const activeImagesOf = (kind, model, mode, images) => {
|
||||
const imgs = images || {};
|
||||
const refs = imgs.reference_images || [];
|
||||
if (kind !== 'video') {
|
||||
return refs.slice(0, image.referenceMaxOf(model, mode)).filter(Boolean);
|
||||
}
|
||||
const a = video.activeInputsOf(model, mode);
|
||||
const out = [];
|
||||
if (a.first_frame && imgs.first_frame) out.push(imgs.first_frame);
|
||||
if (a.last_frame && imgs.last_frame) out.push(imgs.last_frame);
|
||||
return out.concat(refs.slice(0, a.reference_max)).filter(Boolean);
|
||||
};
|
||||
|
||||
/** 不同角色的候选模式(同一角色只保留第一个)。 */
|
||||
const roleChoicesOf = (modes) => {
|
||||
const choices = [];
|
||||
modes.forEach((m) => {
|
||||
const role = roleOfMode(m);
|
||||
if (role && !choices.some((c) => c.role === role)) {
|
||||
choices.push({ role, mode: m });
|
||||
}
|
||||
});
|
||||
return choices;
|
||||
};
|
||||
|
||||
/**
|
||||
* 切到 newMode 后重新排布已有图片:已有图片按顺序占据新模式的前几个槽,
|
||||
* 返回新的 images 与留给新图片的目标槽。当前模式不提交的旧图片保留在原位(新模式用到参考图时
|
||||
* 其中的旧参考图不再保留,避免超出上限)。
|
||||
*/
|
||||
const relayoutImages = (kind, model, newMode, images, existing, total) => {
|
||||
const imgs = images || {};
|
||||
const targets = freshTargets(kind, model, newMode, total);
|
||||
const moved = new Set(existing);
|
||||
const usesRefs = targets.some((tg) => tg.key === 'reference_images');
|
||||
const next = {
|
||||
first_frame:
|
||||
imgs.first_frame && !moved.has(imgs.first_frame)
|
||||
? imgs.first_frame
|
||||
: null,
|
||||
last_frame:
|
||||
imgs.last_frame && !moved.has(imgs.last_frame) ? imgs.last_frame : null,
|
||||
reference_images: usesRefs
|
||||
? []
|
||||
: (imgs.reference_images || []).filter((r) => r && !moved.has(r)),
|
||||
};
|
||||
existing.forEach((slot, i) => {
|
||||
const target = targets[i];
|
||||
if (!target) return;
|
||||
if (target.key === 'reference_images') next.reference_images.push(slot);
|
||||
else next[target.key] = slot;
|
||||
});
|
||||
return { images: next, targets: targets.slice(existing.length) };
|
||||
};
|
||||
|
||||
/**
|
||||
* 已在图片模式但空槽不够时,按"已有 + 新增"总张数重新推断(WP B-7):
|
||||
* 唯一合法模式 → 切换并重新排布;多种 → 沿用记住的角色,否则 choose;没有 → null。
|
||||
*/
|
||||
const planRegroup = ({ kind, model, mode, images, count, rememberedRole }) => {
|
||||
const existing = activeImagesOf(kind, model, mode, images);
|
||||
const total = existing.length + count;
|
||||
const legal = legalModesForCount(kind, model, total).filter(
|
||||
(m) => m !== mode,
|
||||
);
|
||||
if (!legal.length) return null;
|
||||
const pick = (m, extra = {}) => ({
|
||||
type: 'place',
|
||||
mode: m,
|
||||
...relayoutImages(kind, model, m, images, existing, total),
|
||||
regrouped: true,
|
||||
...extra,
|
||||
});
|
||||
const choices = roleChoicesOf(legal);
|
||||
if (choices.length <= 1) return pick(choices[0] ? choices[0].mode : legal[0]);
|
||||
const hit = choices.find((c) => c.role === rememberedRole);
|
||||
if (hit) return pick(hit.mode, { remembered: true });
|
||||
return { type: 'choose', choices, regroup: true };
|
||||
};
|
||||
|
||||
/**
|
||||
* 先上传图片时决定模式与放置位置(方案 §4.4)。
|
||||
*
|
||||
* - 当前已是图片模式且空槽够用 → 按槽位放置,模式不变;
|
||||
* - 否则按图片张数推断:只有一种合法模式 → 直接切换;多种 → 沿用该模型记住的角色,
|
||||
* 没有记忆则返回 choose 让界面弹出小选择器;
|
||||
* - 模型不接受图片 → unsupported(界面提示换模型,绝不自动换);
|
||||
* - 张数超过所有模式上限 → 选上限最大的模式放置前 max 张(truncated)。
|
||||
*
|
||||
* @returns {{ type: 'place', mode: string, targets: Array<{key, index?}>,
|
||||
* remembered?: boolean, truncated?: number,
|
||||
* images?: object, regrouped?: boolean } images:重新推断时已有图片的新排布,先写入再放新图
|
||||
* | { type: 'choose', choices: Array<{ role: string, mode: string }> }
|
||||
* | { type: 'unsupported' }}
|
||||
*/
|
||||
export const planImageUpload = ({
|
||||
kind,
|
||||
model,
|
||||
mode,
|
||||
images,
|
||||
count,
|
||||
rememberedRole = '',
|
||||
}) => {
|
||||
if (!model || !(count > 0)) return { type: 'unsupported' };
|
||||
if (!acceptsImages(kind, model)) return { type: 'unsupported' };
|
||||
|
||||
const current = modeCapacity(kind, model, mode);
|
||||
if (current.max > 0 && video.isModeEnabled(model, mode)) {
|
||||
// 已在图片模式:空槽够用 → 按槽位放置(用户先选模式再上传,不会有歧义)
|
||||
const empties = emptyTargetsOf(kind, model, mode, images, count);
|
||||
const rest = count - empties.length;
|
||||
if (rest <= 0) return { type: 'place', mode, targets: empties };
|
||||
// 空槽不够(WP B-7):按"已有 + 新增"的总张数重新推断模式,规则与先传图相同
|
||||
const regroup = planRegroup({
|
||||
kind,
|
||||
model,
|
||||
mode,
|
||||
images,
|
||||
count,
|
||||
rememberedRole,
|
||||
});
|
||||
if (regroup) return regroup;
|
||||
// 没有能容纳全部图片的模式:能放多少放多少,余下的提示超出上限(targets 可能为空)
|
||||
return { type: 'place', mode, targets: empties, truncated: rest };
|
||||
}
|
||||
|
||||
const legal = legalModesForCount(kind, model, count);
|
||||
if (legal.length === 1) {
|
||||
return {
|
||||
type: 'place',
|
||||
mode: legal[0],
|
||||
targets: freshTargets(kind, model, legal[0], count),
|
||||
};
|
||||
}
|
||||
if (legal.length > 1) {
|
||||
const choices = [];
|
||||
legal.forEach((m) => {
|
||||
const role = roleOfMode(m);
|
||||
if (role && !choices.some((c) => c.role === role)) {
|
||||
choices.push({ role, mode: m });
|
||||
}
|
||||
});
|
||||
if (choices.length === 1) {
|
||||
return {
|
||||
type: 'place',
|
||||
mode: choices[0].mode,
|
||||
targets: freshTargets(kind, model, choices[0].mode, count),
|
||||
};
|
||||
}
|
||||
const hit = choices.find((c) => c.role === rememberedRole);
|
||||
if (hit) {
|
||||
return {
|
||||
type: 'place',
|
||||
mode: hit.mode,
|
||||
targets: freshTargets(kind, model, hit.mode, count),
|
||||
remembered: true,
|
||||
};
|
||||
}
|
||||
return { type: 'choose', choices };
|
||||
}
|
||||
|
||||
// 超过所有模式的上限:取上限最大的模式
|
||||
let best = '';
|
||||
let bestMax = 0;
|
||||
modelModes(model).forEach((m) => {
|
||||
const c = modeCapacity(kind, model, m);
|
||||
if (c.max > bestMax) {
|
||||
best = m;
|
||||
bestMax = c.max;
|
||||
}
|
||||
});
|
||||
return {
|
||||
type: 'place',
|
||||
mode: best,
|
||||
targets: freshTargets(kind, model, best, bestMax),
|
||||
truncated: count - bestMax,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 模型不接受图片时建议切换的模型:未锁定、对 count 张图有合法模式;同系列优先。
|
||||
* 返回 null 表示没有可建议的模型。
|
||||
*/
|
||||
export const suggestImageModel = (kind, models, current, count = 1) => {
|
||||
const list = (Array.isArray(models) ? models : []).filter(
|
||||
(m) =>
|
||||
m &&
|
||||
!m.level_locked &&
|
||||
m.model !== (current && current.model) &&
|
||||
(legalModesForCount(kind, m, count).length > 0 || acceptsImages(kind, m)),
|
||||
);
|
||||
if (!list.length) return null;
|
||||
const series = current && (current.series || current.vendor);
|
||||
const exact = list.filter(
|
||||
(m) => legalModesForCount(kind, m, count).length > 0,
|
||||
);
|
||||
const pool = exact.length ? exact : list;
|
||||
return (
|
||||
(series && pool.find((m) => (m.series || m.vendor) === series)) || pool[0]
|
||||
);
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 首尾帧:缺图状态与一键切回图生
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 首尾帧模式下缺失的槽('first_frame' | 'last_frame'),两张都缺或不在首尾帧模式返回 ''。 */
|
||||
export const missingFrameOf = (kind, model, mode, images) => {
|
||||
if (kind !== 'video' || mode !== 'first_last_frame') return '';
|
||||
const a = video.activeInputsOf(model, mode);
|
||||
if (!a.first_frame || !a.last_frame) return '';
|
||||
const imgs = images || {};
|
||||
if (imgs.first_frame && !imgs.last_frame) return 'last_frame';
|
||||
if (!imgs.first_frame && imgs.last_frame) return 'first_frame';
|
||||
return '';
|
||||
};
|
||||
|
||||
/**
|
||||
* 首尾帧只剩一张时切回图生视频:剩下的那张作为首帧。模型不支持图生返回 null。
|
||||
* @returns {{ mode: 'image2video', images: object } | null}
|
||||
*/
|
||||
export const backToImage2Video = (model, images) => {
|
||||
if (!video.isModeEnabled(model, 'image2video')) return null;
|
||||
const imgs = images || {};
|
||||
const first = imgs.first_frame || imgs.last_frame || null;
|
||||
if (!first) return null;
|
||||
return {
|
||||
mode: 'image2video',
|
||||
images: {
|
||||
first_frame: first,
|
||||
last_frame: imgs.first_frame ? imgs.last_frame || null : null,
|
||||
reference_images: imgs.reference_images || [],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 角色记忆:按模型记住上次选择的图片角色(creation.<kind>.imageRoles)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const roleMemoryKeyOf = (kind) => `creation.${kind}.imageRoles`;
|
||||
|
||||
const ROLES = new Set([ROLE_FRAMES, ROLE_REFERENCE]);
|
||||
|
||||
export const loadRoleMemory = (storage, kind) => {
|
||||
if (!storage) return {};
|
||||
try {
|
||||
const raw = JSON.parse(storage.getItem(roleMemoryKeyOf(kind)) || '{}');
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const out = {};
|
||||
Object.keys(raw).forEach((k) => {
|
||||
if (ROLES.has(raw[k])) out[k] = raw[k];
|
||||
});
|
||||
return out;
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
/** 记住角色并返回新的记忆对象(存储失败时仍返回内存中的新值)。 */
|
||||
export const rememberRole = (storage, kind, memory, modelName, role) => {
|
||||
if (!modelName || !ROLES.has(role)) return memory || {};
|
||||
const next = { ...(memory || {}), [modelName]: role };
|
||||
if (storage) {
|
||||
try {
|
||||
storage.setItem(roleMemoryKeyOf(kind), JSON.stringify(next));
|
||||
} catch (e) {
|
||||
// 存储不可用时只保留内存中的记忆
|
||||
}
|
||||
}
|
||||
return next;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 「图N」引用:编号稳定,删除 / 调整顺序时改写提示词
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const REF_PATTERN = /(「?)图\s?(\d+)(」?)/g;
|
||||
|
||||
/** 第 n 张参考图(从 1 开始)在提示词中的写法。 */
|
||||
export const imageRefToken = (n) => `「图${n}」`;
|
||||
|
||||
/**
|
||||
* 按映射改写提示词中的「图N」。mapping[oldN] = newN(相同则不变)或 null(已删除,去掉该引用)。
|
||||
* 映射中没有的编号保持原样。
|
||||
*/
|
||||
export const rewriteImageRefs = (prompt, mapping) => {
|
||||
if (!prompt || !mapping) return prompt || '';
|
||||
let removed = false;
|
||||
const out = String(prompt).replace(REF_PATTERN, (all, open, num, close) => {
|
||||
const n = Number(num);
|
||||
if (!Object.prototype.hasOwnProperty.call(mapping, n)) return all;
|
||||
const next = mapping[n];
|
||||
if (next === null || next === undefined) {
|
||||
removed = true;
|
||||
return '';
|
||||
}
|
||||
if (next === n) return all;
|
||||
return open || close ? `「图${next}」` : `图${next}`;
|
||||
});
|
||||
return removed ? out.replace(/ {2,}/g, ' ') : out;
|
||||
};
|
||||
|
||||
/** 删除第 removedIndex(从 0 开始)张后的编号映射。 */
|
||||
export const mappingAfterRemove = (count, removedIndex) => {
|
||||
const map = {};
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
if (i === removedIndex) map[i + 1] = null;
|
||||
else map[i + 1] = i < removedIndex ? i + 1 : i;
|
||||
}
|
||||
return map;
|
||||
};
|
||||
|
||||
/** 把第 from 张移动到 to(均从 0 开始)后的编号映射。 */
|
||||
export const mappingAfterMove = (count, from, to) => {
|
||||
const order = Array.from({ length: count }, (_, i) => i);
|
||||
if (from < 0 || from >= count || to < 0 || to >= count) {
|
||||
const same = {};
|
||||
order.forEach((i) => {
|
||||
same[i + 1] = i + 1;
|
||||
});
|
||||
return same;
|
||||
}
|
||||
const [moved] = order.splice(from, 1);
|
||||
order.splice(to, 0, moved);
|
||||
const map = {};
|
||||
order.forEach((oldIndex, newIndex) => {
|
||||
map[oldIndex + 1] = newIndex + 1;
|
||||
});
|
||||
return map;
|
||||
};
|
||||
|
||||
/** 数组中把 from 移到 to(返回新数组)。 */
|
||||
export const moveItem = (list, from, to) => {
|
||||
const arr = [...(list || [])];
|
||||
if (from < 0 || from >= arr.length || to < 0 || to >= arr.length) return arr;
|
||||
const [item] = arr.splice(from, 1);
|
||||
arr.splice(to, 0, item);
|
||||
return arr;
|
||||
};
|
||||
|
||||
/** 在光标处插入文本,返回 { text, caret }。 */
|
||||
export const insertAt = (text, caret, insert) => {
|
||||
const src = String(text || '');
|
||||
const pos =
|
||||
Number.isInteger(caret) && caret >= 0 && caret <= src.length
|
||||
? caret
|
||||
: src.length;
|
||||
const before = src.slice(0, pos);
|
||||
const after = src.slice(pos);
|
||||
return { text: before + insert + after, caret: pos + insert.length };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 模板推荐参数:只套用当前模型支持且合法的值
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const parseRatioText = (v) => {
|
||||
const m = String(v || '').match(
|
||||
/^(\d+(?:\.\d+)?)\s*[::/]\s*(\d+(?:\.\d+)?)$/,
|
||||
);
|
||||
if (!m) return 0;
|
||||
const w = Number(m[1]);
|
||||
const h = Number(m[2]);
|
||||
return w > 0 && h > 0 ? w / h : 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 模板推荐参数 → 当前模型可用的参数取值。
|
||||
* - 有 options 的参数:只接受选项中存在的值;
|
||||
* - 图像 size:推荐 aspect_ratio 时取宽高比最接近的尺寸预设(误差 ≤ 3%);
|
||||
* - 其他类型(switch / textarea / seed / slider)原样套用同类型的值。
|
||||
* @returns {object} { [key]: value }
|
||||
*/
|
||||
export const templateParamsFor = (params, recommended) => {
|
||||
const out = {};
|
||||
const rec = recommended || {};
|
||||
const byKey = {};
|
||||
(params || []).forEach((p) => {
|
||||
if (p && p.key) byKey[p.key] = p;
|
||||
});
|
||||
Object.keys(rec).forEach((key) => {
|
||||
const p = byKey[key];
|
||||
if (!p) return;
|
||||
const want = rec[key];
|
||||
if (Array.isArray(p.options) && p.options.length) {
|
||||
const hit = p.options.find(
|
||||
(o) => String(optionValue(o)) === String(want),
|
||||
);
|
||||
if (hit !== undefined) out[key] = optionValue(hit);
|
||||
return;
|
||||
}
|
||||
if (p.type === 'switch' && typeof want === 'boolean') out[key] = want;
|
||||
else if (p.type === 'textarea' && typeof want === 'string') {
|
||||
out[key] = want;
|
||||
}
|
||||
});
|
||||
const sizeParam = byKey.size;
|
||||
const ratio = parseRatioText(rec.aspect_ratio);
|
||||
if (sizeParam && ratio && out.size === undefined) {
|
||||
let best = null;
|
||||
let bestDiff = Infinity;
|
||||
image.sizePresetsOf(sizeParam).forEach((s) => {
|
||||
const diff = Math.abs(s.width / s.height - ratio) / ratio;
|
||||
if (diff < bestDiff) {
|
||||
best = s;
|
||||
bestDiff = diff;
|
||||
}
|
||||
});
|
||||
if (best && bestDiff <= 0.03) out.size = best.value;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* 模板的推荐模型(WP B-7 模板墙):
|
||||
* 1. 模板指定的 model 可用(未锁定)→ 它;
|
||||
* 2. 当前模型可用且支持该 kind 的文生模式 → 保持当前模型(不悄悄改变价格);
|
||||
* 3. 否则:带"推荐"徽标且支持文生的模型 → 任一支持文生的模型 → 任一可用模型。
|
||||
* 返回 null 表示没有可用模型。
|
||||
*/
|
||||
export const templateModelFor = (kind, tpl, models, current) => {
|
||||
const list = (Array.isArray(models) ? models : []).filter(
|
||||
(m) => m && !m.level_locked,
|
||||
);
|
||||
if (!list.length) return null;
|
||||
const textMode = kind === 'video' ? 'text2video' : 'text2image';
|
||||
const supportsText = (m) => (m.modes || []).includes(textMode);
|
||||
if (tpl && tpl.model) {
|
||||
const hit = list.find((m) => m.model === tpl.model);
|
||||
if (hit) return hit;
|
||||
}
|
||||
if (current && !current.level_locked && supportsText(current)) {
|
||||
const stillThere = list.find((m) => m.model === current.model);
|
||||
if (stillThere) return stillThere;
|
||||
}
|
||||
return (
|
||||
list.find(
|
||||
(m) => supportsText(m) && (m.badges || []).includes('recommended'),
|
||||
) ||
|
||||
list.find(supportsText) ||
|
||||
list[0]
|
||||
);
|
||||
};
|
||||
|
||||
/** 模板推荐参数的简短说明("16:9 · 5s"),模板卡片上展示。 */
|
||||
export const templateParamsSummary = (tpl) => {
|
||||
const p = (tpl && tpl.params) || {};
|
||||
const parts = [];
|
||||
if (p.aspect_ratio) parts.push(String(p.aspect_ratio));
|
||||
if (p.duration) parts.push(`${p.duration}s`);
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 提示词历史(WP B-6 补齐旧图像表单的"提示词历史",按 kind 分开,最多 10 条)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const PROMPT_HISTORY_MAX = 10;
|
||||
|
||||
export const promptHistoryKeyOf = (kind) => `creation.${kind}.promptHistory`;
|
||||
|
||||
/** 读取提示词历史(无效数据返回 [])。 */
|
||||
export const loadPromptHistory = (storage, kind) => {
|
||||
if (!storage) return [];
|
||||
try {
|
||||
const list = JSON.parse(storage.getItem(promptHistoryKeyOf(kind)) || '[]');
|
||||
return Array.isArray(list)
|
||||
? list
|
||||
.filter((p) => typeof p === 'string' && p.trim())
|
||||
.slice(0, PROMPT_HISTORY_MAX)
|
||||
: [];
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** 把提示词放到最前(去重、去首尾空白、截断到上限)。 */
|
||||
export const pushPromptHistory = (list, prompt, max = PROMPT_HISTORY_MAX) => {
|
||||
const text = typeof prompt === 'string' ? prompt.trim() : '';
|
||||
const prev = Array.isArray(list) ? list : [];
|
||||
if (!text) return prev;
|
||||
return [text, ...prev.filter((p) => p !== text)].slice(0, max);
|
||||
};
|
||||
|
||||
/** 写入并返回新的历史(存储失败时仍返回内存中的新值)。 */
|
||||
export const savePromptHistory = (storage, kind, list, prompt) => {
|
||||
const next = pushPromptHistory(list, prompt);
|
||||
if (storage) {
|
||||
try {
|
||||
storage.setItem(promptHistoryKeyOf(kind), JSON.stringify(next));
|
||||
} catch (e) {
|
||||
// 存储不可用时只保留在内存
|
||||
}
|
||||
}
|
||||
return next;
|
||||
};
|
||||
@@ -0,0 +1,558 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
PROMPT_HISTORY_MAX,
|
||||
ROLE_FRAMES,
|
||||
ROLE_REFERENCE,
|
||||
acceptsImages,
|
||||
activeImagesOf,
|
||||
backToImage2Video,
|
||||
insertAt,
|
||||
legalModesForCount,
|
||||
loadPromptHistory,
|
||||
loadRoleMemory,
|
||||
mappingAfterMove,
|
||||
mappingAfterRemove,
|
||||
missingFrameOf,
|
||||
modeCapacity,
|
||||
moveItem,
|
||||
planImageUpload,
|
||||
promptHistoryKeyOf,
|
||||
pushPromptHistory,
|
||||
rememberRole,
|
||||
rewriteImageRefs,
|
||||
roleMemoryKeyOf,
|
||||
roleOfMode,
|
||||
savePromptHistory,
|
||||
suggestImageModel,
|
||||
templateModelFor,
|
||||
templateParamsFor,
|
||||
templateParamsSummary,
|
||||
usesImageRefs,
|
||||
} from './creationDock.js';
|
||||
|
||||
// 全能力视频模型:图生 / 首尾帧 / 参考图(≤3)
|
||||
const VIDEO_FULL = {
|
||||
model: 'seedance',
|
||||
series: 'Seedance',
|
||||
modes: ['text2video', 'image2video', 'first_last_frame', 'reference2video'],
|
||||
inputs: {
|
||||
first_frame: { modes: ['image2video', 'first_last_frame'] },
|
||||
last_frame: { modes: ['first_last_frame'] },
|
||||
reference_images: { modes: ['reference2video'], max: 3 },
|
||||
},
|
||||
};
|
||||
// 只支持图生的视频模型
|
||||
const VIDEO_I2V = {
|
||||
model: 'kling',
|
||||
series: 'Kling',
|
||||
modes: ['text2video', 'image2video'],
|
||||
inputs: { first_frame: { modes: ['image2video'] } },
|
||||
};
|
||||
const VIDEO_TEXT = { model: 'veo', series: 'Veo', modes: ['text2video'] };
|
||||
const IMAGE_EDIT = {
|
||||
model: 'gpt-image',
|
||||
modes: ['text2image', 'edit'],
|
||||
inputs: { reference_images: { modes: ['edit'], max: 4 } },
|
||||
};
|
||||
const IMAGE_TEXT = { model: 'dall-e', modes: ['text2image'] };
|
||||
|
||||
const memoryStorage = () => {
|
||||
const map = new Map();
|
||||
return {
|
||||
getItem: (k) => (map.has(k) ? map.get(k) : null),
|
||||
setItem: (k, v) => map.set(k, String(v)),
|
||||
map,
|
||||
};
|
||||
};
|
||||
|
||||
test('roles and ref modes', () => {
|
||||
assert.equal(roleOfMode('image2video'), ROLE_FRAMES);
|
||||
assert.equal(roleOfMode('first_last_frame'), ROLE_FRAMES);
|
||||
assert.equal(roleOfMode('reference2video'), ROLE_REFERENCE);
|
||||
assert.equal(roleOfMode('edit'), ROLE_REFERENCE);
|
||||
assert.equal(roleOfMode('text2video'), '');
|
||||
assert.equal(usesImageRefs('edit'), true);
|
||||
assert.equal(usesImageRefs('first_last_frame'), false);
|
||||
});
|
||||
|
||||
test('modeCapacity / legalModesForCount', () => {
|
||||
assert.deepEqual(modeCapacity('video', VIDEO_FULL, 'text2video'), {
|
||||
min: 0,
|
||||
max: 0,
|
||||
});
|
||||
assert.deepEqual(modeCapacity('video', VIDEO_FULL, 'first_last_frame'), {
|
||||
min: 2,
|
||||
max: 2,
|
||||
});
|
||||
assert.deepEqual(modeCapacity('video', VIDEO_FULL, 'reference2video'), {
|
||||
min: 1,
|
||||
max: 3,
|
||||
});
|
||||
assert.deepEqual(modeCapacity('image', IMAGE_EDIT, 'edit'), {
|
||||
min: 1,
|
||||
max: 4,
|
||||
});
|
||||
assert.deepEqual(legalModesForCount('video', VIDEO_FULL, 1), [
|
||||
'image2video',
|
||||
'reference2video',
|
||||
]);
|
||||
assert.deepEqual(legalModesForCount('video', VIDEO_FULL, 2), [
|
||||
'first_last_frame',
|
||||
'reference2video',
|
||||
]);
|
||||
assert.deepEqual(legalModesForCount('video', VIDEO_FULL, 3), [
|
||||
'reference2video',
|
||||
]);
|
||||
assert.deepEqual(legalModesForCount('video', VIDEO_I2V, 2), []);
|
||||
assert.equal(acceptsImages('video', VIDEO_TEXT), false);
|
||||
assert.equal(acceptsImages('image', IMAGE_EDIT), true);
|
||||
});
|
||||
|
||||
test('planImageUpload: single legal mode switches directly', () => {
|
||||
const r = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_I2V,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 1,
|
||||
});
|
||||
assert.deepEqual(r, {
|
||||
type: 'place',
|
||||
mode: 'image2video',
|
||||
targets: [{ key: 'first_frame' }],
|
||||
});
|
||||
const three = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 3,
|
||||
});
|
||||
assert.equal(three.mode, 'reference2video');
|
||||
assert.equal(three.targets.length, 3);
|
||||
const img = planImageUpload({
|
||||
kind: 'image',
|
||||
model: IMAGE_EDIT,
|
||||
mode: 'text2image',
|
||||
images: {},
|
||||
count: 2,
|
||||
});
|
||||
assert.equal(img.type, 'place');
|
||||
assert.equal(img.mode, 'edit');
|
||||
assert.equal(img.targets.length, 2);
|
||||
});
|
||||
|
||||
test('planImageUpload: ambiguous count asks, remembered role is reused', () => {
|
||||
const ask = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 2,
|
||||
});
|
||||
assert.deepEqual(ask, {
|
||||
type: 'choose',
|
||||
choices: [
|
||||
{ role: ROLE_FRAMES, mode: 'first_last_frame' },
|
||||
{ role: ROLE_REFERENCE, mode: 'reference2video' },
|
||||
],
|
||||
});
|
||||
const reuse = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 2,
|
||||
rememberedRole: ROLE_FRAMES,
|
||||
});
|
||||
assert.equal(reuse.mode, 'first_last_frame');
|
||||
assert.equal(reuse.remembered, true);
|
||||
assert.deepEqual(reuse.targets, [
|
||||
{ key: 'first_frame' },
|
||||
{ key: 'last_frame' },
|
||||
]);
|
||||
const one = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 1,
|
||||
rememberedRole: ROLE_REFERENCE,
|
||||
});
|
||||
assert.equal(one.mode, 'reference2video');
|
||||
});
|
||||
|
||||
test('planImageUpload: existing image mode fills empty slots only', () => {
|
||||
const r = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'first_last_frame',
|
||||
images: { first_frame: { id: 'a' } },
|
||||
count: 1,
|
||||
});
|
||||
assert.deepEqual(r, {
|
||||
type: 'place',
|
||||
mode: 'first_last_frame',
|
||||
targets: [{ key: 'last_frame' }],
|
||||
});
|
||||
// 首帧已有 + 再加 2 张 = 3 张:只有参考图模式合法 → 重新推断并切换
|
||||
const regroup = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'first_last_frame',
|
||||
images: { first_frame: { id: 'a' } },
|
||||
count: 2,
|
||||
});
|
||||
assert.equal(regroup.mode, 'reference2video');
|
||||
assert.equal(regroup.regrouped, true);
|
||||
const full = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_I2V,
|
||||
mode: 'image2video',
|
||||
images: { first_frame: { id: 'a' } },
|
||||
count: 1,
|
||||
});
|
||||
assert.deepEqual(full.targets, []);
|
||||
assert.equal(full.truncated, 1);
|
||||
});
|
||||
|
||||
test('planImageUpload: unsupported model and over-limit', () => {
|
||||
assert.deepEqual(
|
||||
planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_TEXT,
|
||||
mode: 'text2video',
|
||||
images: {},
|
||||
count: 1,
|
||||
}),
|
||||
{ type: 'unsupported' },
|
||||
);
|
||||
const over = planImageUpload({
|
||||
kind: 'image',
|
||||
model: IMAGE_EDIT,
|
||||
mode: 'text2image',
|
||||
images: {},
|
||||
count: 6,
|
||||
});
|
||||
assert.equal(over.mode, 'edit');
|
||||
assert.equal(over.targets.length, 4);
|
||||
assert.equal(over.truncated, 2);
|
||||
});
|
||||
|
||||
test('suggestImageModel prefers same series, never locked', () => {
|
||||
const models = [
|
||||
VIDEO_TEXT,
|
||||
{ ...VIDEO_FULL, model: 'locked', level_locked: true },
|
||||
VIDEO_I2V,
|
||||
{ ...VIDEO_FULL, model: 'veo-i2v', series: 'Veo' },
|
||||
];
|
||||
assert.equal(
|
||||
suggestImageModel('video', models, VIDEO_TEXT, 1).model,
|
||||
'veo-i2v',
|
||||
);
|
||||
assert.equal(
|
||||
suggestImageModel('video', [VIDEO_TEXT, VIDEO_I2V], VIDEO_TEXT, 2).model,
|
||||
'kling',
|
||||
);
|
||||
assert.equal(suggestImageModel('image', [IMAGE_TEXT], IMAGE_TEXT, 1), null);
|
||||
});
|
||||
|
||||
test('missingFrameOf / backToImage2Video', () => {
|
||||
const first = { id: 'f' };
|
||||
const last = { id: 'l' };
|
||||
assert.equal(
|
||||
missingFrameOf('video', VIDEO_FULL, 'first_last_frame', {
|
||||
first_frame: first,
|
||||
}),
|
||||
'last_frame',
|
||||
);
|
||||
assert.equal(
|
||||
missingFrameOf('video', VIDEO_FULL, 'first_last_frame', {
|
||||
last_frame: last,
|
||||
}),
|
||||
'first_frame',
|
||||
);
|
||||
assert.equal(missingFrameOf('video', VIDEO_FULL, 'first_last_frame', {}), '');
|
||||
assert.equal(
|
||||
missingFrameOf('video', VIDEO_FULL, 'image2video', { first_frame: first }),
|
||||
'',
|
||||
);
|
||||
assert.deepEqual(backToImage2Video(VIDEO_FULL, { last_frame: last }), {
|
||||
mode: 'image2video',
|
||||
images: { first_frame: last, last_frame: null, reference_images: [] },
|
||||
});
|
||||
assert.equal(
|
||||
backToImage2Video(VIDEO_FULL, { first_frame: first }).images.first_frame,
|
||||
first,
|
||||
);
|
||||
assert.equal(backToImage2Video(VIDEO_TEXT, { first_frame: first }), null);
|
||||
});
|
||||
|
||||
test('role memory roundtrip, invalid entries dropped, storage errors tolerated', () => {
|
||||
const storage = memoryStorage();
|
||||
let mem = loadRoleMemory(storage, 'video');
|
||||
assert.deepEqual(mem, {});
|
||||
mem = rememberRole(storage, 'video', mem, 'seedance', ROLE_REFERENCE);
|
||||
mem = rememberRole(storage, 'video', mem, 'x', 'bogus');
|
||||
assert.deepEqual(loadRoleMemory(storage, 'video'), {
|
||||
seedance: ROLE_REFERENCE,
|
||||
});
|
||||
storage.setItem(roleMemoryKeyOf('image'), '{"a":"frames","b":1}');
|
||||
assert.deepEqual(loadRoleMemory(storage, 'image'), { a: ROLE_FRAMES });
|
||||
storage.setItem(roleMemoryKeyOf('image'), 'not json');
|
||||
assert.deepEqual(loadRoleMemory(storage, 'image'), {});
|
||||
const broken = {
|
||||
getItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
};
|
||||
assert.deepEqual(loadRoleMemory(broken, 'video'), {});
|
||||
assert.deepEqual(rememberRole(broken, 'video', {}, 'm', ROLE_FRAMES), {
|
||||
m: ROLE_FRAMES,
|
||||
});
|
||||
});
|
||||
|
||||
test('prompt reference rewriting on remove and reorder', () => {
|
||||
assert.deepEqual(mappingAfterRemove(3, 0), { 1: null, 2: 1, 3: 2 });
|
||||
assert.deepEqual(mappingAfterRemove(3, 1), { 1: 1, 2: null, 3: 2 });
|
||||
assert.deepEqual(mappingAfterMove(3, 2, 0), { 3: 1, 1: 2, 2: 3 });
|
||||
assert.deepEqual(mappingAfterMove(2, 5, 0), { 1: 1, 2: 2 });
|
||||
|
||||
const p = '把「图1」的人物放进「图2」的场景,参考图3 的光线';
|
||||
assert.equal(
|
||||
rewriteImageRefs(p, mappingAfterRemove(3, 0)),
|
||||
'把的人物放进「图1」的场景,参考图2 的光线',
|
||||
);
|
||||
assert.equal(
|
||||
rewriteImageRefs(p, mappingAfterMove(3, 0, 1)),
|
||||
'把「图2」的人物放进「图1」的场景,参考图3 的光线',
|
||||
);
|
||||
// 两位数编号不被拆开;映射外的编号保持原样
|
||||
assert.equal(rewriteImageRefs('图12 和 图1', { 1: 2 }), '图12 和 图2');
|
||||
assert.equal(rewriteImageRefs('', { 1: 2 }), '');
|
||||
assert.equal(rewriteImageRefs('a b 图1', { 1: 1 }), 'a b 图1');
|
||||
});
|
||||
|
||||
test('moveItem / insertAt', () => {
|
||||
assert.deepEqual(moveItem(['a', 'b', 'c'], 2, 0), ['c', 'a', 'b']);
|
||||
assert.deepEqual(moveItem(['a'], 3, 0), ['a']);
|
||||
assert.deepEqual(insertAt('ab', 1, 'X'), { text: 'aXb', caret: 2 });
|
||||
assert.deepEqual(insertAt('ab', undefined, 'X'), { text: 'abX', caret: 3 });
|
||||
});
|
||||
|
||||
test('templateParamsFor keeps only legal values', () => {
|
||||
const params = [
|
||||
{ key: 'aspect_ratio', type: 'ratio', options: ['16:9', '9:16'] },
|
||||
{ key: 'duration', type: 'segmented', options: [5, 10] },
|
||||
{ key: 'generate_audio', type: 'switch' },
|
||||
];
|
||||
assert.deepEqual(
|
||||
templateParamsFor(params, {
|
||||
aspect_ratio: '1:1',
|
||||
duration: '10',
|
||||
generate_audio: true,
|
||||
unknown: 1,
|
||||
}),
|
||||
{ duration: 10, generate_audio: true },
|
||||
);
|
||||
const sizeParams = [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: ['1024x1024', '1536x1024', '1024x1536'],
|
||||
},
|
||||
];
|
||||
assert.deepEqual(templateParamsFor(sizeParams, { aspect_ratio: '3:2' }), {
|
||||
size: '1536x1024',
|
||||
});
|
||||
assert.deepEqual(templateParamsFor(sizeParams, { aspect_ratio: '16:9' }), {});
|
||||
});
|
||||
|
||||
test('prompt history keeps the latest unique prompts', () => {
|
||||
const storage = (() => {
|
||||
const data = {};
|
||||
return {
|
||||
getItem: (k) => (k in data ? data[k] : null),
|
||||
setItem: (k, v) => {
|
||||
data[k] = String(v);
|
||||
},
|
||||
};
|
||||
})();
|
||||
assert.deepEqual(loadPromptHistory(storage, 'image'), []);
|
||||
let list = savePromptHistory(storage, 'image', [], ' a cat ');
|
||||
list = savePromptHistory(storage, 'image', list, 'dog');
|
||||
list = savePromptHistory(storage, 'image', list, 'a cat');
|
||||
assert.deepEqual(list, ['a cat', 'dog']);
|
||||
assert.deepEqual(loadPromptHistory(storage, 'image'), ['a cat', 'dog']);
|
||||
assert.deepEqual(loadPromptHistory(storage, 'video'), []);
|
||||
assert.deepEqual(pushPromptHistory(list, ' '), list);
|
||||
const many = Array.from({ length: 15 }, (_, i) => `p${i}`).reduce(
|
||||
(acc, p) => pushPromptHistory(acc, p),
|
||||
[],
|
||||
);
|
||||
assert.equal(many.length, PROMPT_HISTORY_MAX);
|
||||
assert.equal(many[0], 'p14');
|
||||
storage.setItem(promptHistoryKeyOf('image'), '{bad');
|
||||
assert.deepEqual(loadPromptHistory(storage, 'image'), []);
|
||||
});
|
||||
|
||||
test('planImageUpload: overflow in image mode re-runs mode inference', () => {
|
||||
const a = { id: 'a' };
|
||||
// 图生(首帧已有)再加 1 张 → 首尾帧 / 参考图都合法 → 询问
|
||||
const ask = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'image2video',
|
||||
images: { first_frame: a },
|
||||
count: 1,
|
||||
});
|
||||
assert.deepEqual(ask, {
|
||||
type: 'choose',
|
||||
choices: [
|
||||
{ role: ROLE_FRAMES, mode: 'first_last_frame' },
|
||||
{ role: ROLE_REFERENCE, mode: 'reference2video' },
|
||||
],
|
||||
regroup: true,
|
||||
});
|
||||
// 选"作为首尾帧":已有图保持首帧,新图放尾帧
|
||||
const frames = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'image2video',
|
||||
images: { first_frame: a },
|
||||
count: 1,
|
||||
rememberedRole: ROLE_FRAMES,
|
||||
});
|
||||
assert.equal(frames.mode, 'first_last_frame');
|
||||
assert.equal(frames.remembered, true);
|
||||
assert.deepEqual(frames.images, {
|
||||
first_frame: a,
|
||||
last_frame: null,
|
||||
reference_images: [],
|
||||
});
|
||||
assert.deepEqual(frames.targets, [{ key: 'last_frame' }]);
|
||||
// 选"作为参考图":已有首帧变成参考图 1,新图追加为参考图 2
|
||||
const refs = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'image2video',
|
||||
images: { first_frame: a },
|
||||
count: 1,
|
||||
rememberedRole: ROLE_REFERENCE,
|
||||
});
|
||||
assert.equal(refs.mode, 'reference2video');
|
||||
assert.deepEqual(refs.images, {
|
||||
first_frame: null,
|
||||
last_frame: null,
|
||||
reference_images: [a],
|
||||
});
|
||||
assert.deepEqual(refs.targets, [{ key: 'reference_images' }]);
|
||||
// 首尾帧已满再加 1 张 → 3 张只有参考图合法 → 直接切换,两张帧图变参考图 1、2
|
||||
const b = { id: 'b' };
|
||||
const three = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'first_last_frame',
|
||||
images: { first_frame: a, last_frame: b },
|
||||
count: 1,
|
||||
});
|
||||
assert.equal(three.type, 'place');
|
||||
assert.equal(three.mode, 'reference2video');
|
||||
assert.deepEqual(three.images.reference_images, [a, b]);
|
||||
assert.deepEqual(three.targets, [{ key: 'reference_images' }]);
|
||||
});
|
||||
|
||||
test('planImageUpload: overflow with no legal mode keeps toast behaviour', () => {
|
||||
const full = planImageUpload({
|
||||
kind: 'video',
|
||||
model: VIDEO_FULL,
|
||||
mode: 'reference2video',
|
||||
images: { reference_images: [{ id: 1 }, { id: 2 }, { id: 3 }] },
|
||||
count: 1,
|
||||
});
|
||||
assert.deepEqual(full, {
|
||||
type: 'place',
|
||||
mode: 'reference2video',
|
||||
targets: [],
|
||||
truncated: 1,
|
||||
});
|
||||
const img = planImageUpload({
|
||||
kind: 'image',
|
||||
model: IMAGE_EDIT,
|
||||
mode: 'edit',
|
||||
images: { reference_images: [{ id: 1 }, { id: 2 }, { id: 3 }] },
|
||||
count: 3,
|
||||
});
|
||||
assert.equal(img.mode, 'edit');
|
||||
assert.equal(img.targets.length, 1);
|
||||
assert.equal(img.truncated, 2);
|
||||
});
|
||||
|
||||
test('activeImagesOf lists submitted images in slot order', () => {
|
||||
const a = { id: 'a' };
|
||||
const b = { id: 'b' };
|
||||
assert.deepEqual(
|
||||
activeImagesOf('video', VIDEO_FULL, 'first_last_frame', {
|
||||
first_frame: a,
|
||||
last_frame: b,
|
||||
reference_images: [{ id: 'x' }],
|
||||
}),
|
||||
[a, b],
|
||||
);
|
||||
assert.deepEqual(
|
||||
activeImagesOf('image', IMAGE_EDIT, 'text2image', {
|
||||
reference_images: [a],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('templateModelFor / templateParamsSummary', () => {
|
||||
const rec = {
|
||||
model: 'rec',
|
||||
modes: ['text2video'],
|
||||
badges: ['recommended'],
|
||||
};
|
||||
const models = [{ ...VIDEO_FULL, level_locked: true }, VIDEO_I2V, rec];
|
||||
// 模板指定可用模型 → 它
|
||||
assert.equal(
|
||||
templateModelFor('video', { model: 'kling' }, models, rec).model,
|
||||
'kling',
|
||||
);
|
||||
// 当前模型可用且支持文生 → 保持
|
||||
assert.equal(templateModelFor('video', {}, models, VIDEO_I2V).model, 'kling');
|
||||
// 当前模型锁定 → 推荐模型
|
||||
assert.equal(
|
||||
templateModelFor('video', { model: 'seedance' }, models, models[0]).model,
|
||||
'rec',
|
||||
);
|
||||
assert.equal(templateModelFor('video', {}, [models[0]], null), null);
|
||||
assert.equal(
|
||||
templateParamsSummary({ params: { aspect_ratio: '16:9', duration: 5 } }),
|
||||
'16:9 · 5s',
|
||||
);
|
||||
assert.equal(templateParamsSummary({}), '');
|
||||
});
|
||||
@@ -0,0 +1,498 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 新创作台(CreationStudio,WP B-2)图像 / 视频共用的表单状态机纯函数。
|
||||
// 无 React / i18n 依赖,可直接 node --test。
|
||||
//
|
||||
// 统一表单形状(两种 kind 相同,图像只使用 images.reference_images):
|
||||
// { modelName, mode, preferredMode, prompt, params, images, paramMemory }
|
||||
// images = { first_frame, last_frame, reference_images[] }
|
||||
//
|
||||
// 模式 / 图片槽 / 参数合成 / 请求体全部委托给旧页面已有的纯函数
|
||||
// (hooks/video/videoCreation.js、hooks/image/imageCreation.js),这里只做形状适配与优先级编排。
|
||||
|
||||
import * as video from '../video/videoCreation.js';
|
||||
import * as image from '../image/imageCreation.js';
|
||||
|
||||
export const STORAGE_VERSION = 'v3';
|
||||
|
||||
/** 新创作台的本地存储 key:creation.<kind>.v3(与旧页面草稿分开,首次进入从旧草稿迁移)。 */
|
||||
export const storageKeyOf = (kind) => `creation.${kind}.${STORAGE_VERSION}`;
|
||||
|
||||
export const EMPTY_IMAGES = Object.freeze({
|
||||
first_frame: null,
|
||||
last_frame: null,
|
||||
reference_images: [],
|
||||
});
|
||||
|
||||
export const modelNameOf = video.modelNameOf;
|
||||
|
||||
const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
const normalizeImages = (images) => {
|
||||
const src = isPlainObject(images) ? images : {};
|
||||
return {
|
||||
first_frame: src.first_frame || null,
|
||||
last_frame: src.last_frame || null,
|
||||
reference_images: Array.isArray(src.reference_images)
|
||||
? src.reference_images.filter(Boolean)
|
||||
: [],
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// kind 适配器:把统一形状翻译成旧纯函数的入参
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const VIDEO_ADAPTER = {
|
||||
kind: 'video',
|
||||
defaultMode: 'text2video',
|
||||
textMode: 'text2video',
|
||||
modeLabels: video.MODE_LABEL_KEYS,
|
||||
legacyDraftKey: video.DRAFT_STORAGE_KEY,
|
||||
requestParamsOf: video.requestParamsOf,
|
||||
paramsForMode: video.requestParamsForMode,
|
||||
composeParams: video.composeParams,
|
||||
composePrefillParams: video.composePrefillParams,
|
||||
modeOptionsOf: video.modeOptionsOf,
|
||||
isModeEnabled: video.isModeEnabled,
|
||||
pickMode: (model, mode, images) =>
|
||||
video.pickModeForModel(model, mode, normalizeImages(images)),
|
||||
slotsOf: (model, mode, images) =>
|
||||
video.imageSlotsOf(model, mode, normalizeImages(images)),
|
||||
blockReason: (model, mode, images) =>
|
||||
video.imageBlockReason(model, mode, normalizeImages(images)),
|
||||
buildPayload: (model, form) => ({
|
||||
model: modelNameOf(model),
|
||||
...video.buildVideoRequest(model, {
|
||||
...form,
|
||||
images: normalizeImages(form.images),
|
||||
}),
|
||||
}),
|
||||
quoteRequest: (model, payload) => ({
|
||||
kind: 'video',
|
||||
items: [
|
||||
{
|
||||
model: modelNameOf(model),
|
||||
mode: payload.mode,
|
||||
params: video.quoteParamsOf(payload),
|
||||
},
|
||||
],
|
||||
}),
|
||||
toNative: (form) => ({
|
||||
...video.DEFAULT_VIDEO_FORM,
|
||||
mode: form.mode,
|
||||
prompt: form.prompt,
|
||||
modelName: form.modelName,
|
||||
params: form.params,
|
||||
paramMemory: form.paramMemory,
|
||||
images: normalizeImages(form.images),
|
||||
}),
|
||||
fromNative: (native) => ({
|
||||
modelName: native.modelName || '',
|
||||
mode: native.mode || 'text2video',
|
||||
preferredMode: native.preferredMode || '',
|
||||
// 旧视频页的模板内容拼在提示词前(与旧页面提交口径一致)
|
||||
prompt: native.selectedTemplate
|
||||
? native.selectedTemplate + (native.prompt ? `\n${native.prompt}` : '')
|
||||
: native.prompt || '',
|
||||
params: native.params || {},
|
||||
paramMemory: native.paramMemory || {},
|
||||
images: normalizeImages(native.images),
|
||||
}),
|
||||
serializeDraft: video.serializeDraft,
|
||||
parseDraft: video.parseDraft,
|
||||
loadLegacyDraft: video.loadDraft,
|
||||
};
|
||||
|
||||
const IMAGE_ADAPTER = {
|
||||
kind: 'image',
|
||||
defaultMode: 'text2image',
|
||||
textMode: 'text2image',
|
||||
modeLabels: image.MODE_LABEL_KEYS,
|
||||
legacyDraftKey: image.DRAFT_STORAGE_KEY,
|
||||
requestParamsOf: image.requestParamsOf,
|
||||
paramsForMode: image.requestParamsForMode,
|
||||
composeParams: image.composeParams,
|
||||
composePrefillParams: image.composePrefillParams,
|
||||
modeOptionsOf: image.modeOptionsOf,
|
||||
isModeEnabled: image.isModeEnabled,
|
||||
pickMode: (model, mode, images) =>
|
||||
image.pickModeForModel(
|
||||
model,
|
||||
mode,
|
||||
normalizeImages(images).reference_images,
|
||||
),
|
||||
slotsOf: (model, mode, images) =>
|
||||
image
|
||||
.imageSlotsOf(model, mode, normalizeImages(images).reference_images)
|
||||
.map((s) => ({ ...s, key: 'reference_images' })),
|
||||
blockReason: (model, mode, images) =>
|
||||
image.imageBlockReason(
|
||||
model,
|
||||
mode,
|
||||
normalizeImages(images).reference_images,
|
||||
),
|
||||
// buildImageRequest 自带 model 与 source: "creation_studio"
|
||||
buildPayload: (model, form) =>
|
||||
image.buildImageRequest(model, {
|
||||
...form,
|
||||
references: normalizeImages(form.images).reference_images,
|
||||
}),
|
||||
quoteRequest: (model, payload) => image.quoteRequestOf(model, payload),
|
||||
toNative: (form) => ({
|
||||
...image.DEFAULT_IMAGE_FORM,
|
||||
mode: form.mode,
|
||||
preferredMode: form.preferredMode || '',
|
||||
prompt: form.prompt,
|
||||
modelName: form.modelName,
|
||||
params: form.params,
|
||||
paramMemory: form.paramMemory,
|
||||
references: normalizeImages(form.images).reference_images,
|
||||
}),
|
||||
fromNative: (native) => ({
|
||||
modelName: native.modelName || '',
|
||||
mode: native.mode || 'text2image',
|
||||
preferredMode: native.preferredMode || '',
|
||||
prompt: native.prompt || '',
|
||||
params: native.params || {},
|
||||
paramMemory: native.paramMemory || {},
|
||||
images: { ...EMPTY_IMAGES, reference_images: native.references || [] },
|
||||
}),
|
||||
serializeDraft: image.serializeDraft,
|
||||
parseDraft: image.parseDraft,
|
||||
loadLegacyDraft: image.loadDraft,
|
||||
};
|
||||
|
||||
/** @param {'image'|'video'} kind */
|
||||
export const adapterOf = (kind) =>
|
||||
kind === 'image' ? IMAGE_ADAPTER : VIDEO_ADAPTER;
|
||||
|
||||
export const emptyForm = (kind) => ({
|
||||
modelName: '',
|
||||
mode: adapterOf(kind).defaultMode,
|
||||
preferredMode: '',
|
||||
prompt: '',
|
||||
params: {},
|
||||
paramMemory: {},
|
||||
images: { ...EMPTY_IMAGES, reference_images: [] },
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 参数优先级与吸附(方案 §4.3)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 切换到 nextModel 后的表单。参数优先级:
|
||||
* 1. 本次会话用户手动设置的值(sessionValues,且新模型支持);
|
||||
* 2. 该模型上次使用时记住的值(paramMemory[model]);
|
||||
* 3. schema 默认值。
|
||||
* 不合法的值吸附到最近的合法值并记入 adjustments。
|
||||
* 图片不删除:新模型用不到的图片由 slotsOf 标为 inactive(置灰保留)。
|
||||
*
|
||||
* @returns {{ form: object, adjustments: Array<{key, from, to}>,
|
||||
* modeChange: { from: string, to: string } | null }}
|
||||
*/
|
||||
export const switchModel = (kind, form, nextModel, { sessionValues } = {}) => {
|
||||
const adapter = adapterOf(kind);
|
||||
const prev = form || emptyForm(kind);
|
||||
const name = modelNameOf(nextModel);
|
||||
const paramMemory = { ...(prev.paramMemory || {}) };
|
||||
if (prev.modelName && prev.modelName !== name && prev.params) {
|
||||
paramMemory[prev.modelName] = prev.params;
|
||||
}
|
||||
const memory =
|
||||
name === prev.modelName ? prev.params || {} : paramMemory[name] || {};
|
||||
const { values, adjustments } = adapter.composeParams(nextModel, {
|
||||
sessionValues: sessionValues || {},
|
||||
memory,
|
||||
});
|
||||
const mode = adapter.pickMode(
|
||||
nextModel,
|
||||
prev.preferredMode || prev.mode,
|
||||
prev.images,
|
||||
);
|
||||
return {
|
||||
form: { ...prev, modelName: name, params: values, mode, paramMemory },
|
||||
adjustments,
|
||||
modeChange:
|
||||
prev.mode && mode !== prev.mode ? { from: prev.mode, to: mode } : null,
|
||||
};
|
||||
};
|
||||
|
||||
/** 当前模式下创作台显示的参数(schema 参数 modes 不含当前模式的隐藏,也不随请求提交)。 */
|
||||
export const visibleParamsOf = (kind, model, mode) =>
|
||||
model ? adapterOf(kind).paramsForMode(model, mode) : [];
|
||||
|
||||
/** 首次可用的模型:草稿中的模型仍可调用则沿用,否则第一个未锁定的模型。 */
|
||||
export const initialModelOf = (models, preferredName) => {
|
||||
const list = Array.isArray(models) ? models : [];
|
||||
const current = list.find((m) => m && m.model === preferredName);
|
||||
if (current && !current.level_locked) return current;
|
||||
return list.find((m) => m && !m.level_locked) || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 外部回填(复用参数 / 再生成):filled = { modelName, mode, prompt, params, images }。
|
||||
* 原模型可用时切过去;不可用时保留当前模型(fallback=true);都不可用返回 error。
|
||||
* 任务快照对请求参数是权威的:只按 src.params 合成(快照里缺省的可选参数 = 随机种子 / 空 /
|
||||
* schema 默认),不合并此前的会话值与按模型记忆,避免上一次"换种子"的固定种子等泄漏进来。
|
||||
* 回填参数随后视同本次会话手动设置(sessionValues = src.params),切换模型时仍优先保留。
|
||||
*
|
||||
* @returns {{ error?: 'model_unavailable', form?, adjustments?, modeChange?,
|
||||
* sessionValues?, fallback?: boolean, originalName: string }}
|
||||
*/
|
||||
export const applyPrefill = (kind, form, filled, models) => {
|
||||
const adapter = adapterOf(kind);
|
||||
const prev = form || emptyForm(kind);
|
||||
const src = filled || {};
|
||||
const originalName = src.modelName || '';
|
||||
const list = Array.isArray(models) ? models : [];
|
||||
const original = list.find((m) => m && m.model === originalName);
|
||||
let target = original && !original.level_locked ? original : null;
|
||||
let fallback = false;
|
||||
if (!target) {
|
||||
target =
|
||||
list.find((m) => m && m.model === prev.modelName && !m.level_locked) ||
|
||||
null;
|
||||
if (!target) return { error: 'model_unavailable', originalName };
|
||||
fallback = Boolean(originalName);
|
||||
}
|
||||
const nextSession = { ...(src.params || {}) };
|
||||
const name = modelNameOf(target);
|
||||
const paramMemory = { ...(prev.paramMemory || {}) };
|
||||
if (prev.modelName && prev.modelName !== name && prev.params) {
|
||||
paramMemory[prev.modelName] = prev.params;
|
||||
}
|
||||
const { values, adjustments } = adapter.composePrefillParams(
|
||||
target,
|
||||
nextSession,
|
||||
);
|
||||
const images = normalizeImages(src.images);
|
||||
const wanted = src.mode || prev.mode;
|
||||
const mode = adapter.pickMode(target, wanted, images);
|
||||
return {
|
||||
form: {
|
||||
...prev,
|
||||
modelName: name,
|
||||
mode,
|
||||
preferredMode: src.mode || prev.preferredMode || '',
|
||||
prompt: typeof src.prompt === 'string' ? src.prompt : prev.prompt,
|
||||
params: values,
|
||||
images,
|
||||
paramMemory,
|
||||
},
|
||||
adjustments,
|
||||
modeChange: wanted && mode !== wanted ? { from: wanted, to: mode } : null,
|
||||
sessionValues: nextSession,
|
||||
fallback,
|
||||
originalName,
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 图片槽(统一形状)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 写入(slot 为 null 时移除)一个图片槽;参考图 index 缺省或越界时追加。 */
|
||||
export const writeImageSlot = (images, key, index, slot) => {
|
||||
const base = normalizeImages(images);
|
||||
if (key === 'reference_images') {
|
||||
const list = [...base.reference_images];
|
||||
if (slot) {
|
||||
if (index === undefined || index === null || index >= list.length) {
|
||||
list.push(slot);
|
||||
} else {
|
||||
list[index] = slot;
|
||||
}
|
||||
} else if (index !== undefined && index !== null) {
|
||||
list.splice(index, 1);
|
||||
}
|
||||
return { ...base, reference_images: list.filter(Boolean) };
|
||||
}
|
||||
if (key !== 'first_frame' && key !== 'last_frame') return base;
|
||||
return { ...base, [key]: slot || null };
|
||||
};
|
||||
|
||||
/** 按槽 id 合并字段(异步上传完成时槽位下标可能已变化)。 */
|
||||
export const patchImageSlotById = (images, id, patch) => {
|
||||
const base = normalizeImages(images);
|
||||
const apply = (slot) =>
|
||||
slot && slot.id === id ? { ...slot, ...patch } : slot;
|
||||
return {
|
||||
first_frame: apply(base.first_frame),
|
||||
last_frame: apply(base.last_frame),
|
||||
reference_images: base.reference_images.map(apply),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 提交返回"原图已失效"时标记可能失效的引用槽(方案 §4.6):后端不指明是哪一张,
|
||||
* 优先标记引用历史作品的 task:// 槽,没有时标记 cos:// 槽;内联图片不会失效。
|
||||
* @returns {{ images: object, count: number }}
|
||||
*/
|
||||
export const markExpiredSlots = (images) => {
|
||||
const base = normalizeImages(images);
|
||||
const all = [base.first_frame, base.last_frame, ...base.reference_images];
|
||||
const refOf = (slot) => String((slot && slot.ref) || '');
|
||||
const pick = (scheme) =>
|
||||
all.filter(
|
||||
(slot) =>
|
||||
slot &&
|
||||
(slot.status || 'ready') === 'ready' &&
|
||||
refOf(slot).startsWith(scheme),
|
||||
);
|
||||
let targets = pick('task://');
|
||||
if (!targets.length) targets = pick('cos://');
|
||||
if (!targets.length) return { images: base, count: 0 };
|
||||
const ids = new Set(targets);
|
||||
const apply = (slot) =>
|
||||
ids.has(slot) ? { ...slot, status: 'expired', error: null } : slot;
|
||||
return {
|
||||
images: {
|
||||
first_frame: apply(base.first_frame),
|
||||
last_frame: apply(base.last_frame),
|
||||
reference_images: base.reference_images.map(apply),
|
||||
},
|
||||
count: targets.length,
|
||||
};
|
||||
};
|
||||
|
||||
/** 表单中的全部图片槽(含当前不提交的)。 */
|
||||
export const allImageSlots = (images) => {
|
||||
const base = normalizeImages(images);
|
||||
return [base.first_frame, base.last_frame, ...base.reference_images].filter(
|
||||
Boolean,
|
||||
);
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 请求体 / 估价
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 提交请求体(含 model;图像带 source: "creation_studio")。无模型返回 null。 */
|
||||
export const buildPayload = (kind, model, form) => {
|
||||
if (!model || !form) return null;
|
||||
return adapterOf(kind).buildPayload(model, form);
|
||||
};
|
||||
|
||||
/** 估价请求;模型锁定 / 无请求体时返回 null(不估价)。 */
|
||||
export const buildQuoteRequest = (kind, model, payload) => {
|
||||
if (!model || model.level_locked || !payload) return null;
|
||||
return adapterOf(kind).quoteRequest(model, payload);
|
||||
};
|
||||
|
||||
/** 提示词以外的提交阻断(i18n key + 插值),无阻断返回 null。 */
|
||||
export const formBlockReason = (kind, model, form) => {
|
||||
if (!model) return { key: '请选择模型' };
|
||||
if (model.level_locked) return { key: '当前等级无权调用此模型' };
|
||||
if (!form.prompt || !String(form.prompt).trim()) {
|
||||
return { key: '请输入提示词' };
|
||||
}
|
||||
return adapterOf(kind).blockReason(model, form.mode, form.images);
|
||||
};
|
||||
|
||||
/**
|
||||
* 提交失败的统一结构。429 too_many_running_tasks 时带 running / max(来自 data)。
|
||||
* @returns {{ code: string, message: string, running: number, max: number }}
|
||||
*/
|
||||
export const normalizeSubmitError = (error) => {
|
||||
const body = error?.response?.data || error?.data || error || {};
|
||||
const data = isPlainObject(body.data) ? body.data : {};
|
||||
const status = error?.response?.status || error?.status || 0;
|
||||
let code = body.code || '';
|
||||
if (!code && status === 429) code = 'too_many_running_tasks';
|
||||
return {
|
||||
code,
|
||||
message: body.message || body.error?.message || error?.message || '',
|
||||
running: Number(data.running_tasks) || 0,
|
||||
max: Number(data.max_running_tasks) || 0,
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 本地记忆(creation.<kind>.v3,读写全部 try/catch)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 序列化:当前模型的参数同时写入 paramMemory,下次进入按模型恢复。 */
|
||||
export const serializeForm = (kind, form, { keepInline = true } = {}) => {
|
||||
const adapter = adapterOf(kind);
|
||||
const paramMemory = { ...(form.paramMemory || {}) };
|
||||
if (form.modelName && form.params) paramMemory[form.modelName] = form.params;
|
||||
const raw = JSON.parse(
|
||||
adapter.serializeDraft(adapter.toNative({ ...form, paramMemory }), {
|
||||
keepInline,
|
||||
}),
|
||||
);
|
||||
raw.preferredMode = form.preferredMode || '';
|
||||
return JSON.stringify(raw);
|
||||
};
|
||||
|
||||
export const parseForm = (kind, raw) => {
|
||||
if (!raw) return null;
|
||||
const adapter = adapterOf(kind);
|
||||
const native = adapter.parseDraft(raw);
|
||||
if (!native) return null;
|
||||
const data = JSON.parse(raw);
|
||||
const out = { ...emptyForm(kind), ...adapter.fromNative(native) };
|
||||
const modes = Object.keys(adapter.modeLabels);
|
||||
out.preferredMode = modes.includes(data.preferredMode)
|
||||
? data.preferredMode
|
||||
: '';
|
||||
return out;
|
||||
};
|
||||
|
||||
/** 读取记忆;v3 不存在时从旧页面草稿迁移(提示词 / 模型 / 参数记忆 / 图片)。 */
|
||||
export const loadForm = (kind, storage) => {
|
||||
if (!storage) return emptyForm(kind);
|
||||
try {
|
||||
const hit = parseForm(kind, storage.getItem(storageKeyOf(kind)));
|
||||
if (hit) return hit;
|
||||
} catch (e) {
|
||||
// 损坏时忽略
|
||||
}
|
||||
try {
|
||||
const adapter = adapterOf(kind);
|
||||
return {
|
||||
...emptyForm(kind),
|
||||
...adapter.fromNative(adapter.loadLegacyDraft(storage)),
|
||||
};
|
||||
} catch (e) {
|
||||
return emptyForm(kind);
|
||||
}
|
||||
};
|
||||
|
||||
/** 保存记忆;配额不足时退而不存内联 base64 图片,仍失败则放弃。 */
|
||||
export const saveForm = (kind, storage, form) => {
|
||||
if (!storage) return false;
|
||||
try {
|
||||
storage.setItem(storageKeyOf(kind), serializeForm(kind, form));
|
||||
return true;
|
||||
} catch (e) {
|
||||
try {
|
||||
storage.setItem(
|
||||
storageKeyOf(kind),
|
||||
serializeForm(kind, form, { keepInline: false }),
|
||||
);
|
||||
return true;
|
||||
} catch (e2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,417 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
applyPrefill,
|
||||
buildPayload,
|
||||
buildQuoteRequest,
|
||||
emptyForm,
|
||||
formBlockReason,
|
||||
initialModelOf,
|
||||
loadForm,
|
||||
normalizeSubmitError,
|
||||
patchImageSlotById,
|
||||
saveForm,
|
||||
storageKeyOf,
|
||||
switchModel,
|
||||
writeImageSlot,
|
||||
markExpiredSlots,
|
||||
} from './creationForm.js';
|
||||
|
||||
const memoryStorage = (init = {}) => {
|
||||
const data = { ...init };
|
||||
return {
|
||||
data,
|
||||
getItem: (k) => (k in data ? data[k] : null),
|
||||
setItem: (k, v) => {
|
||||
data[k] = String(v);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const seedance = {
|
||||
model: 'seedance',
|
||||
modes: ['text2video', 'image2video', 'first_last_frame'],
|
||||
params: [
|
||||
{
|
||||
key: 'aspect_ratio',
|
||||
type: 'ratio',
|
||||
options: ['16:9', '9:16', '1:1'],
|
||||
default: '16:9',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'duration',
|
||||
type: 'segmented',
|
||||
options: [5, 10],
|
||||
default: 5,
|
||||
placement: 'dock',
|
||||
},
|
||||
{ key: 'seed', type: 'seed', placement: 'advanced' },
|
||||
],
|
||||
inputs: {
|
||||
first_frame: { label: '首帧', modes: ['image2video', 'first_last_frame'] },
|
||||
last_frame: { label: '尾帧', modes: ['first_last_frame'] },
|
||||
},
|
||||
};
|
||||
|
||||
const kling = {
|
||||
model: 'kling',
|
||||
modes: ['text2video', 'image2video'],
|
||||
params: [
|
||||
{
|
||||
key: 'aspect_ratio',
|
||||
type: 'ratio',
|
||||
options: ['16:9', '9:16'],
|
||||
default: '9:16',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'duration',
|
||||
type: 'segmented',
|
||||
options: [5, 8],
|
||||
default: 5,
|
||||
placement: 'dock',
|
||||
},
|
||||
],
|
||||
inputs: { first_frame: { label: '首帧', modes: ['image2video'] } },
|
||||
};
|
||||
|
||||
const gptImage = {
|
||||
model: 'gpt-image-1',
|
||||
modes: ['text2image', 'edit'],
|
||||
params: [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: ['1024x1024', '1536x1024', '1024x1536'],
|
||||
default: '1024x1024',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'quality',
|
||||
type: 'chips',
|
||||
options: ['low', 'high'],
|
||||
default: 'high',
|
||||
placement: 'dock',
|
||||
},
|
||||
{ key: 'n', type: 'segmented', options: [1, 2, 4], default: 1 },
|
||||
],
|
||||
inputs: { reference_images: { label: '参考图', modes: ['edit'], max: 2 } },
|
||||
};
|
||||
|
||||
const slot = (id, ref = `cos://playground/1/${id}.png`) => ({
|
||||
id,
|
||||
ref,
|
||||
status: 'ready',
|
||||
previewUrl: `https://x/${id}.png`,
|
||||
});
|
||||
|
||||
test('参数优先级:本次会话 > 按模型记忆 > schema 默认值', () => {
|
||||
const form = {
|
||||
...emptyForm('video'),
|
||||
modelName: 'kling',
|
||||
params: { aspect_ratio: '9:16', duration: 8 },
|
||||
paramMemory: { seedance: { aspect_ratio: '1:1', duration: 10 } },
|
||||
};
|
||||
// 无会话值:取 seedance 的记忆
|
||||
let r = switchModel('video', form, seedance, { sessionValues: {} });
|
||||
assert.deepEqual(r.form.params, { aspect_ratio: '1:1', duration: 10 });
|
||||
assert.deepEqual(r.adjustments, []);
|
||||
// 切走时记住 kling 的参数
|
||||
assert.deepEqual(r.form.paramMemory.kling, {
|
||||
aspect_ratio: '9:16',
|
||||
duration: 8,
|
||||
});
|
||||
// 会话值优先于记忆
|
||||
r = switchModel('video', form, seedance, {
|
||||
sessionValues: { aspect_ratio: '16:9' },
|
||||
});
|
||||
assert.equal(r.form.params.aspect_ratio, '16:9');
|
||||
assert.equal(r.form.params.duration, 10);
|
||||
// 无记忆、无会话值:schema 默认
|
||||
r = switchModel('video', { ...form, paramMemory: {} }, seedance, {});
|
||||
assert.deepEqual(r.form.params, { aspect_ratio: '16:9', duration: 5 });
|
||||
});
|
||||
|
||||
test('不合法的会话值吸附到最近合法值并记录调整', () => {
|
||||
const form = { ...emptyForm('video'), modelName: 'kling' };
|
||||
const r = switchModel('video', form, seedance, {
|
||||
sessionValues: { duration: 8 },
|
||||
});
|
||||
assert.equal(r.form.params.duration, 10);
|
||||
assert.deepEqual(r.adjustments, [{ key: 'duration', from: 8, to: 10 }]);
|
||||
});
|
||||
|
||||
test('切换模型:不支持的模式退回,图片保留(不删除)', () => {
|
||||
const images = {
|
||||
first_frame: slot('a'),
|
||||
last_frame: slot('b'),
|
||||
reference_images: [],
|
||||
};
|
||||
const form = {
|
||||
...emptyForm('video'),
|
||||
modelName: 'seedance',
|
||||
mode: 'first_last_frame',
|
||||
images,
|
||||
};
|
||||
const r = switchModel('video', form, kling, {});
|
||||
assert.equal(r.form.mode, 'image2video');
|
||||
assert.deepEqual(r.modeChange, {
|
||||
from: 'first_last_frame',
|
||||
to: 'image2video',
|
||||
});
|
||||
assert.equal(r.form.images.last_frame.id, 'b');
|
||||
// 切回时按 preferredMode 恢复
|
||||
const back = switchModel(
|
||||
'video',
|
||||
{ ...r.form, preferredMode: 'first_last_frame' },
|
||||
seedance,
|
||||
{},
|
||||
);
|
||||
assert.equal(back.form.mode, 'first_last_frame');
|
||||
});
|
||||
|
||||
test('初始模型:沿用记忆中的可用模型,否则第一个未锁定的模型', () => {
|
||||
const locked = { ...seedance, level_locked: true };
|
||||
assert.equal(initialModelOf([locked, kling], 'seedance').model, 'kling');
|
||||
assert.equal(initialModelOf([seedance, kling], 'kling').model, 'kling');
|
||||
assert.equal(initialModelOf([locked], 'x'), null);
|
||||
});
|
||||
|
||||
test('回填:原模型可用时切换,不可用时保留当前模型,都不可用返回错误', () => {
|
||||
const form = { ...emptyForm('video'), modelName: 'kling' };
|
||||
const filled = {
|
||||
modelName: 'seedance',
|
||||
mode: 'image2video',
|
||||
prompt: '海浪',
|
||||
params: { duration: 10 },
|
||||
images: { first_frame: slot('f') },
|
||||
};
|
||||
let r = applyPrefill('video', form, filled, [seedance, kling]);
|
||||
assert.equal(r.form.modelName, 'seedance');
|
||||
assert.equal(r.form.mode, 'image2video');
|
||||
assert.equal(r.form.params.duration, 10);
|
||||
assert.equal(r.form.prompt, '海浪');
|
||||
assert.equal(r.fallback, false);
|
||||
assert.equal(r.sessionValues.duration, 10);
|
||||
|
||||
r = applyPrefill('video', form, filled, [kling]);
|
||||
assert.equal(r.form.modelName, 'kling');
|
||||
assert.equal(r.fallback, true);
|
||||
assert.deepEqual(r.adjustments, [{ key: 'duration', from: 10, to: 8 }]);
|
||||
|
||||
r = applyPrefill('video', { ...form, modelName: '' }, filled, [
|
||||
{ ...kling, level_locked: true },
|
||||
]);
|
||||
assert.equal(r.error, 'model_unavailable');
|
||||
});
|
||||
|
||||
test('图片槽写入 / 删除 / 按 id 合并', () => {
|
||||
let images = writeImageSlot(
|
||||
undefined,
|
||||
'reference_images',
|
||||
undefined,
|
||||
slot('r1'),
|
||||
);
|
||||
images = writeImageSlot(images, 'reference_images', undefined, slot('r2'));
|
||||
images = writeImageSlot(images, 'first_frame', 0, slot('f'));
|
||||
assert.deepEqual(
|
||||
images.reference_images.map((s) => s.id),
|
||||
['r1', 'r2'],
|
||||
);
|
||||
images = writeImageSlot(images, 'reference_images', 0, null);
|
||||
assert.deepEqual(
|
||||
images.reference_images.map((s) => s.id),
|
||||
['r2'],
|
||||
);
|
||||
images = patchImageSlotById(images, 'r2', { status: 'error' });
|
||||
assert.equal(images.reference_images[0].status, 'error');
|
||||
assert.equal(images.first_frame.id, 'f');
|
||||
// 未知 key 不改动
|
||||
assert.deepEqual(writeImageSlot(images, 'bogus', 0, slot('x')), images);
|
||||
});
|
||||
|
||||
test('视频请求体:带 model,只提交当前模式用到的图片', () => {
|
||||
const form = {
|
||||
...emptyForm('video'),
|
||||
modelName: 'seedance',
|
||||
mode: 'image2video',
|
||||
prompt: '日出',
|
||||
params: { aspect_ratio: '9:16', duration: 10 },
|
||||
images: { first_frame: slot('f'), last_frame: slot('l') },
|
||||
};
|
||||
const payload = buildPayload('video', seedance, form);
|
||||
assert.equal(payload.model, 'seedance');
|
||||
assert.equal(payload.mode, 'image2video');
|
||||
assert.equal(payload.image, 'cos://playground/1/f.png');
|
||||
assert.equal(payload.last_image, undefined);
|
||||
assert.equal(payload.duration, 10);
|
||||
const quote = buildQuoteRequest('video', seedance, payload);
|
||||
assert.deepEqual(quote, {
|
||||
kind: 'video',
|
||||
items: [
|
||||
{
|
||||
model: 'seedance',
|
||||
mode: 'image2video',
|
||||
params: { duration: 10, aspect_ratio: '9:16' },
|
||||
},
|
||||
],
|
||||
});
|
||||
assert.equal(
|
||||
buildQuoteRequest('video', { ...seedance, level_locked: true }, payload),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('图像请求体:source=creation_studio,编辑模式按上限带参考图', () => {
|
||||
const form = {
|
||||
...emptyForm('image'),
|
||||
modelName: 'gpt-image-1',
|
||||
mode: 'edit',
|
||||
prompt: '换成夜景',
|
||||
params: { size: '1536x1024', quality: 'low', n: 2 },
|
||||
images: {
|
||||
reference_images: [slot('a'), slot('b'), slot('c')],
|
||||
},
|
||||
};
|
||||
const payload = buildPayload('image', gptImage, form);
|
||||
assert.equal(payload.source, 'creation_studio');
|
||||
assert.equal(payload.model, 'gpt-image-1');
|
||||
assert.deepEqual(payload.image, [
|
||||
'cos://playground/1/a.png',
|
||||
'cos://playground/1/b.png',
|
||||
]);
|
||||
assert.equal(payload.n, 2);
|
||||
const quote = buildQuoteRequest('image', gptImage, payload);
|
||||
assert.equal(quote.items[0].mode, 'edit');
|
||||
assert.equal(quote.items[0].n, 2);
|
||||
});
|
||||
|
||||
test('提交阻断:模型 / 锁定 / 提示词 / 图片', () => {
|
||||
const form = { ...emptyForm('video'), prompt: '' };
|
||||
assert.equal(formBlockReason('video', null, form).key, '请选择模型');
|
||||
assert.equal(
|
||||
formBlockReason('video', { ...kling, level_locked: true }, form).key,
|
||||
'当前等级无权调用此模型',
|
||||
);
|
||||
assert.equal(formBlockReason('video', kling, form).key, '请输入提示词');
|
||||
assert.equal(
|
||||
formBlockReason('video', kling, {
|
||||
...form,
|
||||
prompt: 'x',
|
||||
mode: 'image2video',
|
||||
}).key,
|
||||
'请上传首帧图片',
|
||||
);
|
||||
assert.equal(formBlockReason('video', kling, { ...form, prompt: 'x' }), null);
|
||||
});
|
||||
|
||||
test('提交错误:429 too_many_running_tasks 带进行中数量', () => {
|
||||
const e = normalizeSubmitError({
|
||||
response: {
|
||||
status: 429,
|
||||
data: {
|
||||
success: false,
|
||||
message: 'too many',
|
||||
data: { running_tasks: 3, max_running_tasks: 3 },
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(e, {
|
||||
code: 'too_many_running_tasks',
|
||||
message: 'too many',
|
||||
running: 3,
|
||||
max: 3,
|
||||
});
|
||||
assert.equal(normalizeSubmitError({ data: { code: 'x' } }).code, 'x');
|
||||
});
|
||||
|
||||
test('本地记忆:creation.<kind>.v3 往返,当前模型参数写入按模型记忆', () => {
|
||||
const storage = memoryStorage();
|
||||
const form = {
|
||||
...emptyForm('video'),
|
||||
modelName: 'seedance',
|
||||
mode: 'image2video',
|
||||
preferredMode: 'first_last_frame',
|
||||
prompt: '雪山',
|
||||
params: { duration: 10 },
|
||||
images: { first_frame: slot('f'), last_frame: null, reference_images: [] },
|
||||
};
|
||||
assert.equal(saveForm('video', storage, form), true);
|
||||
assert.ok(storage.data[storageKeyOf('video')]);
|
||||
const back = loadForm('video', storage);
|
||||
assert.equal(back.modelName, 'seedance');
|
||||
assert.equal(back.prompt, '雪山');
|
||||
assert.equal(back.preferredMode, 'first_last_frame');
|
||||
assert.deepEqual(back.paramMemory.seedance, { duration: 10 });
|
||||
assert.equal(back.images.first_frame.ref, 'cos://playground/1/f.png');
|
||||
});
|
||||
|
||||
test('本地记忆:v3 缺失时从旧页面草稿迁移;损坏 / 存储异常不抛错', () => {
|
||||
const storage = memoryStorage({
|
||||
'expCenter.imageGen.draft.v3': JSON.stringify({
|
||||
mode: 'edit',
|
||||
prompt: '猫',
|
||||
modelName: 'gpt-image-1',
|
||||
params: { size: '1024x1024' },
|
||||
references: [slot('a')],
|
||||
}),
|
||||
});
|
||||
const migrated = loadForm('image', storage);
|
||||
assert.equal(migrated.prompt, '猫');
|
||||
assert.equal(migrated.mode, 'edit');
|
||||
assert.equal(migrated.images.reference_images[0].id, 'a');
|
||||
|
||||
storage.data[storageKeyOf('image')] = '{oops';
|
||||
assert.equal(loadForm('image', storage).prompt, '猫');
|
||||
|
||||
const throwing = {
|
||||
getItem: () => {
|
||||
throw new Error('denied');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('quota');
|
||||
},
|
||||
};
|
||||
assert.deepEqual(loadForm('video', throwing), emptyForm('video'));
|
||||
assert.equal(saveForm('video', throwing, emptyForm('video')), false);
|
||||
assert.deepEqual(loadForm('video', null), emptyForm('video'));
|
||||
});
|
||||
|
||||
test('markExpiredSlots prefers task:// refs, then cos://, never inline', () => {
|
||||
const task = { id: 't', status: 'ready', ref: 'task://abc' };
|
||||
const cos = { id: 'c', status: 'ready', ref: 'cos://playground/1/a.png' };
|
||||
const inline = { id: 'i', status: 'ready', ref: 'data:image/png;base64,x' };
|
||||
const r = markExpiredSlots({
|
||||
first_frame: cos,
|
||||
last_frame: null,
|
||||
reference_images: [task, inline],
|
||||
});
|
||||
assert.equal(r.count, 1);
|
||||
assert.equal(r.images.reference_images[0].status, 'expired');
|
||||
assert.equal(r.images.first_frame.status, 'ready');
|
||||
assert.equal(r.images.reference_images[1].status, 'ready');
|
||||
const onlyCos = markExpiredSlots({ first_frame: cos });
|
||||
assert.equal(onlyCos.count, 1);
|
||||
assert.equal(onlyCos.images.first_frame.status, 'expired');
|
||||
assert.equal(markExpiredSlots({ reference_images: [inline] }).count, 0);
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 回归测试:
|
||||
// - 手动提交不能用上一次参数的估价跳过多张确认(manualSubmitDecision);
|
||||
// - 复用参数 / 再生成 / 换种子:任务快照对请求参数是权威的,不泄漏此前会话值 / 模型记忆;
|
||||
// - schema 参数 modes:不适用于当前模式的参数不显示、不提交、不进对比交集。
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
paramSupportsMode,
|
||||
paramsForMode,
|
||||
} from '../../components/creation/params/constraints.js';
|
||||
import {
|
||||
buildImageRequest,
|
||||
composePrefillParams as composeImagePrefill,
|
||||
requestParamsForMode as imageParamsForMode,
|
||||
} from '../image/imageCreation.js';
|
||||
import {
|
||||
buildVideoRequest,
|
||||
composePrefillParams as composeVideoPrefill,
|
||||
} from '../video/videoCreation.js';
|
||||
import { applyPrefill, emptyForm, visibleParamsOf } from './creationForm.js';
|
||||
import { manualSubmitDecision, sharedParamsOf } from './creationCompare.js';
|
||||
|
||||
const gptImage = {
|
||||
model: 'gpt-image-1',
|
||||
modes: ['text2image', 'edit'],
|
||||
params: [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: ['1024x1024', '1536x1024'],
|
||||
default: '1024x1024',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'background',
|
||||
type: 'chips',
|
||||
options: ['auto', 'transparent', 'opaque'],
|
||||
default: 'auto',
|
||||
placement: 'advanced',
|
||||
modes: ['text2image'],
|
||||
},
|
||||
{
|
||||
key: 'negative_prompt',
|
||||
type: 'textarea',
|
||||
placement: 'advanced',
|
||||
modes: ['text2image'],
|
||||
},
|
||||
{ key: 'seed', type: 'seed', placement: 'advanced', modes: [] },
|
||||
],
|
||||
inputs: { reference_images: { max: 4, modes: ['edit'] } },
|
||||
};
|
||||
|
||||
const seedream = {
|
||||
model: 'seedream',
|
||||
modes: ['text2image', 'edit'],
|
||||
params: [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: ['1024x1024', '1536x1024'],
|
||||
default: '1024x1024',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'background',
|
||||
type: 'chips',
|
||||
options: ['auto', 'transparent'],
|
||||
default: 'auto',
|
||||
placement: 'advanced',
|
||||
},
|
||||
],
|
||||
inputs: { reference_images: { max: 4, modes: ['edit'] } },
|
||||
};
|
||||
|
||||
const seedance = {
|
||||
model: 'seedance',
|
||||
modes: ['text2video', 'image2video'],
|
||||
params: [
|
||||
{
|
||||
key: 'duration',
|
||||
type: 'segmented',
|
||||
options: [5, 10],
|
||||
default: 5,
|
||||
placement: 'dock',
|
||||
},
|
||||
{ key: 'seed', type: 'seed', placement: 'advanced' },
|
||||
{
|
||||
key: 'camera',
|
||||
type: 'select',
|
||||
options: ['', 'pan'],
|
||||
placement: 'advanced',
|
||||
modes: ['text2video'],
|
||||
},
|
||||
],
|
||||
inputs: { first_frame: { label: '首帧', modes: ['image2video'] } },
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUG 1:手动提交的多张确认
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('手动提交:多张且估价未对应当前参数时等待,不用旧估价跳过确认', () => {
|
||||
const stale = { total: 10 }; // n=1 时的旧估价(低于阈值)
|
||||
assert.equal(
|
||||
manualSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 100,
|
||||
quote: stale,
|
||||
quoteFresh: false,
|
||||
}),
|
||||
'wait',
|
||||
);
|
||||
assert.equal(
|
||||
manualSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 100,
|
||||
quote: { total: 400 },
|
||||
quoteFresh: true,
|
||||
}),
|
||||
'confirm',
|
||||
);
|
||||
assert.equal(
|
||||
manualSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 100,
|
||||
quote: { total: 40 },
|
||||
quoteFresh: true,
|
||||
}),
|
||||
'submit',
|
||||
);
|
||||
// 估价失败:手动提交照常(估价永远不阻止手动提交)
|
||||
assert.equal(
|
||||
manualSubmitDecision({
|
||||
n: 4,
|
||||
threshold: 100,
|
||||
quote: null,
|
||||
quoteFresh: true,
|
||||
quoteFailed: true,
|
||||
}),
|
||||
'submit',
|
||||
);
|
||||
// 单张 / 阈值关闭:不等估价
|
||||
assert.equal(
|
||||
manualSubmitDecision({ n: 1, threshold: 100, quoteFresh: false }),
|
||||
'submit',
|
||||
);
|
||||
assert.equal(
|
||||
manualSubmitDecision({ n: 4, threshold: 0, quoteFresh: false }),
|
||||
'submit',
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUG 2:回填不泄漏此前的会话值 / 模型记忆
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('composePrefillParams:只按快照合成,缺省的种子保持随机', () => {
|
||||
const img = composeImagePrefill(gptImage, { size: '1536x1024' });
|
||||
assert.equal(img.values.size, '1536x1024');
|
||||
assert.equal(img.values.seed, undefined);
|
||||
assert.equal(img.values.background, 'auto');
|
||||
|
||||
const vid = composeVideoPrefill(seedance, { duration: 10 });
|
||||
assert.equal(vid.values.duration, 10);
|
||||
assert.equal(vid.values.seed, undefined);
|
||||
const empty = composeVideoPrefill(seedance, undefined).values;
|
||||
assert.equal(empty.duration, 5);
|
||||
assert.equal(empty.seed, undefined);
|
||||
});
|
||||
|
||||
test('applyPrefill:换种子后再生成随机种子的任务,不带上一次的固定种子', () => {
|
||||
// 先"换种子"回填任务 B(固定种子 X),表单与按模型记忆里都留有该种子
|
||||
const prev = {
|
||||
...emptyForm('video'),
|
||||
modelName: 'seedance',
|
||||
params: { duration: 10, seed: 12345 },
|
||||
paramMemory: { seedance: { duration: 10, seed: 12345 } },
|
||||
};
|
||||
// 再生成任务 A:快照未带种子(随机)
|
||||
const r = applyPrefill(
|
||||
'video',
|
||||
prev,
|
||||
{
|
||||
modelName: 'seedance',
|
||||
mode: 'text2video',
|
||||
prompt: 'A',
|
||||
params: { duration: 5 },
|
||||
},
|
||||
[seedance],
|
||||
);
|
||||
assert.equal(r.form.params.seed, undefined);
|
||||
assert.equal(r.form.params.duration, 5);
|
||||
assert.deepEqual(r.sessionValues, { duration: 5 });
|
||||
const payload = buildVideoRequest(seedance, r.form);
|
||||
assert.equal(payload.seed, undefined);
|
||||
|
||||
// 从另一模型回填时也不读该模型的按模型记忆
|
||||
const fromOther = applyPrefill(
|
||||
'image',
|
||||
{
|
||||
...emptyForm('image'),
|
||||
modelName: 'seedream',
|
||||
paramMemory: { 'gpt-image-1': { seed: 7, background: 'opaque' } },
|
||||
},
|
||||
{ modelName: 'gpt-image-1', mode: 'text2image', prompt: 'p', params: {} },
|
||||
[gptImage, seedream],
|
||||
);
|
||||
assert.equal(fromOther.form.params.seed, undefined);
|
||||
assert.equal(fromOther.form.params.background, 'auto');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BUG 3:参数 modes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test('paramSupportsMode:缺省 / 空 modes 适用所有模式', () => {
|
||||
assert.equal(paramSupportsMode({ key: 'a' }, 'edit'), true);
|
||||
assert.equal(paramSupportsMode({ key: 'a', modes: [] }, 'edit'), true);
|
||||
assert.equal(
|
||||
paramSupportsMode({ key: 'a', modes: ['text2image'] }, 'edit'),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
paramSupportsMode({ key: 'a', modes: ['text2image'] }, 'text2image'),
|
||||
true,
|
||||
);
|
||||
assert.equal(paramSupportsMode({ key: 'a', modes: ['x'] }, ''), true);
|
||||
assert.deepEqual(
|
||||
paramsForMode(gptImage.params, 'edit').map((p) => p.key),
|
||||
['size', 'seed'],
|
||||
);
|
||||
});
|
||||
|
||||
test('图像:图生图模式不显示也不提交仅文生图可用的参数', () => {
|
||||
assert.deepEqual(
|
||||
imageParamsForMode(gptImage, 'edit').map((p) => p.key),
|
||||
['size', 'seed'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
visibleParamsOf('image', gptImage, 'text2image').map((p) => p.key),
|
||||
['size', 'background', 'negative_prompt', 'seed'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
visibleParamsOf('image', gptImage, 'edit').map((p) => p.key),
|
||||
['size', 'seed'],
|
||||
);
|
||||
assert.deepEqual(visibleParamsOf('image', null, 'edit'), []);
|
||||
|
||||
const params = {
|
||||
size: '1024x1024',
|
||||
background: 'transparent',
|
||||
negative_prompt: 'blur',
|
||||
};
|
||||
const t2i = buildImageRequest(gptImage, {
|
||||
mode: 'text2image',
|
||||
prompt: 'p',
|
||||
params,
|
||||
});
|
||||
assert.equal(t2i.background, 'transparent');
|
||||
assert.equal(t2i.negative_prompt, 'blur');
|
||||
|
||||
const edit = buildImageRequest(gptImage, {
|
||||
mode: 'edit',
|
||||
prompt: 'p',
|
||||
params,
|
||||
references: [{ status: 'ready', ref: 'cos://a.png' }],
|
||||
});
|
||||
assert.equal(edit.background, undefined);
|
||||
assert.equal(edit.negative_prompt, undefined);
|
||||
assert.equal(edit.size, '1024x1024');
|
||||
assert.equal(edit.image, 'cos://a.png');
|
||||
});
|
||||
|
||||
test('视频:参数 modes 不含当前模式时不提交', () => {
|
||||
const form = {
|
||||
mode: 'image2video',
|
||||
prompt: 'p',
|
||||
params: { duration: 10, camera: 'pan' },
|
||||
};
|
||||
assert.equal(buildVideoRequest(seedance, form).camera, undefined);
|
||||
assert.equal(
|
||||
buildVideoRequest(seedance, { ...form, mode: 'text2video' }).camera,
|
||||
'pan',
|
||||
);
|
||||
assert.deepEqual(
|
||||
visibleParamsOf('video', seedance, 'image2video').map((p) => p.key),
|
||||
['duration', 'seed'],
|
||||
);
|
||||
});
|
||||
|
||||
test('对比交集:任一模型在当前模式下不支持的参数不进交集', () => {
|
||||
assert.deepEqual(
|
||||
sharedParamsOf([gptImage, seedream], { mode: 'text2image' }).map(
|
||||
(p) => p.key,
|
||||
),
|
||||
['size', 'background'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
sharedParamsOf([gptImage, seedream], { mode: 'edit' }).map((p) => p.key),
|
||||
['size'],
|
||||
);
|
||||
// 以支持全部模式的模型为基准时同样排除
|
||||
assert.deepEqual(
|
||||
sharedParamsOf([seedream, gptImage], { mode: 'edit' }).map((p) => p.key),
|
||||
['size'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,621 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 作品流(WP B-6)纯函数:任务归一化、日期分组、轮询结果合并、退避、筛选参数。
|
||||
// 不依赖 React / 浏览器,node --test 覆盖(creationTasks.test.js)。
|
||||
|
||||
import { pollDelay } from '../video/videoCreation.js';
|
||||
|
||||
export { pollDelay };
|
||||
|
||||
/** ids= 批量查询上限(后端 parseTaskIDsQuery 限制 20)。 */
|
||||
export const IDS_QUERY_LIMIT = 20;
|
||||
/** 列表每页条数(后端 GetPageQuery:p= / page_size=)。 */
|
||||
export const PAGE_SIZE = 20;
|
||||
|
||||
/** 旧图像页 localStorage 收藏(B-5 一次性同步到服务端)。 */
|
||||
export const LEGACY_FAVORITES_KEY = 'expCenter.imageGen.favorites.v1';
|
||||
export const FAVORITES_SYNCED_KEY = 'creation.favorites.synced.v1';
|
||||
|
||||
export const LIST_ENDPOINTS = {
|
||||
image: '/api/images/tasks',
|
||||
video: '/api/video/tasks',
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 状态与时间
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const QUEUED = new Set(['NOT_START', 'SUBMITTED', 'QUEUED']);
|
||||
|
||||
/** 后端任务状态 → queued | running | success | failed。未知状态视为进行中(继续轮询以服务端为准)。 */
|
||||
export const taskStatusOf = (raw) => {
|
||||
const s = String(raw || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (s === 'SUCCESS') return 'success';
|
||||
if (s === 'FAILURE' || s === 'FAILED' || s === 'CANCELED') return 'failed';
|
||||
if (QUEUED.has(s)) return 'queued';
|
||||
return 'running';
|
||||
};
|
||||
|
||||
export const isActiveTask = (task) =>
|
||||
task?.status === 'queued' || task?.status === 'running';
|
||||
|
||||
/** 时间戳归一为毫秒:秒级整数(< 1e12)× 1000,数字字符串、ISO 字符串均可;无效为 0。 */
|
||||
export const toMs = (value) => {
|
||||
if (value === null || value === undefined || value === '') return 0;
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value) || value <= 0) return 0;
|
||||
return value < 1e12 ? value * 1000 : value;
|
||||
}
|
||||
const str = String(value).trim();
|
||||
if (/^\d+(\.\d+)?$/.test(str)) return toMs(Number(str));
|
||||
const parsed = Date.parse(str);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
};
|
||||
|
||||
/** 进度字符串("42%")→ 0~100 的整数。 */
|
||||
export const progressOf = (value) => {
|
||||
const n = parseInt(String(value ?? '').replace('%', ''), 10);
|
||||
if (!Number.isFinite(n)) return 0;
|
||||
return Math.max(0, Math.min(100, n));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 归一化:图像 / 视频任务 → 作品流统一结构
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const parseJSON = (value) => {
|
||||
if (!value) return {};
|
||||
if (typeof value === 'object') return value;
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const str = (v) => (typeof v === 'string' ? v : '');
|
||||
|
||||
const parseSizeText = (size) => {
|
||||
const m = /^(\d+)\s*[x×*]\s*(\d+)$/i.exec(String(size || '').trim());
|
||||
return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 图像任务(GET /api/images/tasks 列表项 / ids= / 详情)→ 作品。
|
||||
* images[i] = { url, reusable, hasB64 }:url 为空且 hasB64 时可经 refresh-url 转存后显示。
|
||||
*/
|
||||
export const normalizeImageTask = (raw) => {
|
||||
const r = raw || {};
|
||||
const data = parseJSON(r.data);
|
||||
const props = r.properties || {};
|
||||
const results = Array.isArray(data.data) ? data.data : [];
|
||||
const images = results.map((item) => ({
|
||||
url: str(item?.url),
|
||||
reusable: item?.reusable_as_input === true,
|
||||
hasB64: Boolean(item?.b64_json),
|
||||
}));
|
||||
const request = r.request || null;
|
||||
const size = str(request?.size) || str(data.size);
|
||||
const dims = parseSizeText(size);
|
||||
const status = taskStatusOf(r.status);
|
||||
const n = Number(request?.n || data.n) || images.length || 1;
|
||||
return {
|
||||
kind: 'image',
|
||||
id: String(r.task_id || r.id || ''),
|
||||
backendId: r.id,
|
||||
status,
|
||||
rawStatus: r.status || '',
|
||||
progress: progressOf(r.progress),
|
||||
prompt: str(request?.prompt) || str(data.prompt) || str(props.input),
|
||||
model:
|
||||
str(request?.model) ||
|
||||
str(data.model) ||
|
||||
str(props.origin_model_name) ||
|
||||
str(props.upstream_model_name),
|
||||
mode: str(request?.mode) || str(data.mode) || str(props.mode),
|
||||
size,
|
||||
width: dims?.width || 0,
|
||||
height: dims?.height || 0,
|
||||
quality: str(request?.quality) || str(data.quality),
|
||||
n,
|
||||
images,
|
||||
createdAt: toMs(r.created_at) || toMs(r.submit_time),
|
||||
startedAt: toMs(r.start_time) || toMs(r.submit_time) || toMs(r.created_at),
|
||||
finishedAt: toMs(r.finish_time),
|
||||
failReason: str(r.fail_reason),
|
||||
quota: Number(r.quota) || 0,
|
||||
refundedQuota: Number(r.refunded_quota) || 0,
|
||||
quotedQuota: Number(r.quoted_quota) || 0,
|
||||
cancelable: r.cancelable === true,
|
||||
favorited: r.favorited === true,
|
||||
// 对比生成批次(WP C-2):同批次的多模型作品在作品流中成组
|
||||
batchId: str(r.batch_id),
|
||||
request,
|
||||
regenerateSupported:
|
||||
r.regenerate_supported === undefined
|
||||
? null
|
||||
: r.regenerate_supported === true,
|
||||
// 旧任务回填(formFromLegacyTask)需要的原始数据
|
||||
taskData: data,
|
||||
sourceImageUrl: str(data.source_image) || str(data.source_image_base64),
|
||||
};
|
||||
};
|
||||
|
||||
/** 视频任务(ExperienceVideoTaskDTO)→ 作品。列表项不含 data / request,以 ids= / 详情补全。 */
|
||||
export const normalizeVideoTask = (raw) => {
|
||||
const r = raw || {};
|
||||
const request = r.request || null;
|
||||
const videoUrl = str(r.data?.video_url).trim();
|
||||
return {
|
||||
kind: 'video',
|
||||
id: String(r.task_id || r.id || ''),
|
||||
backendId: r.id,
|
||||
status: taskStatusOf(r.status),
|
||||
rawStatus: r.status || '',
|
||||
progress: progressOf(r.progress),
|
||||
prompt: str(r.prompt) || str(request?.prompt),
|
||||
model: str(r.model) || str(request?.model),
|
||||
mode: str(request?.mode) || str(r.action),
|
||||
duration: Number(request?.duration) || 0,
|
||||
ratio: str(request?.aspect_ratio) || str(request?.ratio),
|
||||
resolution: str(request?.resolution),
|
||||
videoUrl,
|
||||
lastFrameUrl: str(r.last_frame_url),
|
||||
reusableAsInput:
|
||||
r.reusable_as_input === undefined ? null : r.reusable_as_input === true,
|
||||
createdAt: toMs(r.created_at) || toMs(r.submit_time),
|
||||
startedAt: toMs(r.start_time) || toMs(r.submit_time) || toMs(r.created_at),
|
||||
finishedAt: toMs(r.finish_time),
|
||||
failReason: str(r.fail_reason),
|
||||
quota: Number(r.quota) || 0,
|
||||
refundedQuota: Number(r.refunded_quota) || 0,
|
||||
quotedQuota: Number(r.quoted_quota) || 0,
|
||||
cancelable: r.cancelable === true,
|
||||
favorited: r.favorited === true,
|
||||
request,
|
||||
regenerateSupported: r.regenerate_supported === true,
|
||||
// 列表口径(无 data / request)标记:需要 ids= 补全播放地址与时长
|
||||
hydrated: Boolean(request || videoUrl || r.data),
|
||||
};
|
||||
};
|
||||
|
||||
export const normalizeTask = (kind, raw) =>
|
||||
kind === 'video' ? normalizeVideoTask(raw) : normalizeImageTask(raw);
|
||||
|
||||
/** 刚提交成功的任务(提交响应 + 请求体)→ 作品,乐观插入作品流顶部。 */
|
||||
export const optimisticTask = (kind, response, payload) => {
|
||||
const res = response || {};
|
||||
const body = payload || {};
|
||||
const base = {
|
||||
id: res.id,
|
||||
task_id: res.task_id,
|
||||
status: res.status || 'NOT_START',
|
||||
progress: res.progress || '0%',
|
||||
created_at: res.created_at || res.submit_time || Date.now(),
|
||||
submit_time: res.submit_time,
|
||||
batch_id: body.batch_id,
|
||||
};
|
||||
if (kind === 'video') {
|
||||
return {
|
||||
...normalizeVideoTask({
|
||||
...base,
|
||||
model: body.model,
|
||||
prompt: body.prompt,
|
||||
request: null,
|
||||
}),
|
||||
mode: str(body.mode),
|
||||
duration: Number(body.duration) || 0,
|
||||
ratio: str(body.aspect_ratio) || str(body.ratio),
|
||||
resolution: str(body.resolution),
|
||||
optimistic: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...normalizeImageTask({
|
||||
...base,
|
||||
data: {
|
||||
model: body.model,
|
||||
prompt: body.prompt,
|
||||
size: body.size,
|
||||
n: body.n,
|
||||
quality: body.quality,
|
||||
mode: body.mode,
|
||||
},
|
||||
}),
|
||||
optimistic: true,
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 合并:分页追加、轮询更新、乐观插入
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 用新数据覆盖旧作品,保留新数据缺失的详情字段(列表 / 轮询口径不含 request;
|
||||
* 视频列表不含播放地址)。
|
||||
*/
|
||||
export const mergeTask = (prev, next) => {
|
||||
if (!prev) return next;
|
||||
if (!next) return prev;
|
||||
const merged = { ...prev, ...next, optimistic: false };
|
||||
if (!next.request && prev.request) merged.request = prev.request;
|
||||
if (next.regenerateSupported === null && prev.regenerateSupported !== null) {
|
||||
merged.regenerateSupported = prev.regenerateSupported;
|
||||
}
|
||||
if (next.kind === 'video') {
|
||||
if (!next.videoUrl && prev.videoUrl) merged.videoUrl = prev.videoUrl;
|
||||
if (!next.lastFrameUrl && prev.lastFrameUrl) {
|
||||
merged.lastFrameUrl = prev.lastFrameUrl;
|
||||
}
|
||||
if (!next.duration && prev.duration) merged.duration = prev.duration;
|
||||
if (!next.ratio && prev.ratio) merged.ratio = prev.ratio;
|
||||
if (!next.resolution && prev.resolution) {
|
||||
merged.resolution = prev.resolution;
|
||||
}
|
||||
if (next.reusableAsInput === null && prev.reusableAsInput !== null) {
|
||||
merged.reusableAsInput = prev.reusableAsInput;
|
||||
}
|
||||
merged.hydrated = Boolean(next.hydrated || prev.hydrated);
|
||||
}
|
||||
if (!next.prompt && prev.prompt) merged.prompt = prev.prompt;
|
||||
if (!next.model && prev.model) merged.model = prev.model;
|
||||
if (!next.batchId && prev.batchId) merged.batchId = prev.batchId;
|
||||
return merged;
|
||||
};
|
||||
|
||||
/** 按 id 应用一批更新(保持原顺序;列表中没有的忽略)。 */
|
||||
export const applyUpdates = (list, updates) => {
|
||||
const byId = new Map((updates || []).map((task) => [task.id, task]));
|
||||
if (byId.size === 0) return list;
|
||||
let changed = false;
|
||||
const next = list.map((task) => {
|
||||
const update = byId.get(task.id);
|
||||
if (!update) return task;
|
||||
changed = true;
|
||||
return mergeTask(task, update);
|
||||
});
|
||||
return changed ? next : list;
|
||||
};
|
||||
|
||||
/** 追加一页(按 id 去重;已存在的就地合并)。 */
|
||||
export const appendPage = (list, items) => {
|
||||
const index = new Map(list.map((task, i) => [task.id, i]));
|
||||
const next = [...list];
|
||||
(items || []).forEach((task) => {
|
||||
if (!task?.id) return;
|
||||
if (index.has(task.id)) {
|
||||
const i = index.get(task.id);
|
||||
next[i] = mergeTask(next[i], task);
|
||||
} else {
|
||||
index.set(task.id, next.length);
|
||||
next.push(task);
|
||||
}
|
||||
});
|
||||
return next;
|
||||
};
|
||||
|
||||
/** 把作品放到顶部(已存在则合并后移到顶部)。 */
|
||||
export const upsertTop = (list, task) => {
|
||||
if (!task?.id) return list;
|
||||
const existing = list.find((item) => item.id === task.id);
|
||||
const rest = list.filter((item) => item.id !== task.id);
|
||||
return [existing ? mergeTask(existing, task) : task, ...rest];
|
||||
};
|
||||
|
||||
export const removeTask = (list, id) => list.filter((task) => task.id !== id);
|
||||
|
||||
/** 状态签名(status|progress),轮询结果无变化时逐步退避。 */
|
||||
export const taskSignature = (task) => `${task?.status}|${task?.progress}`;
|
||||
|
||||
/** 两次结果之间进入终态的作品(供 aria-live 播报 / 提示)。 */
|
||||
export const finishedTransitions = (prevList, updates) => {
|
||||
const before = new Map((prevList || []).map((task) => [task.id, task]));
|
||||
return (updates || []).filter((task) => {
|
||||
const old = before.get(task.id);
|
||||
return old && isActiveTask(old) && !isActiveTask(task);
|
||||
});
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 轮询:批次轮转与退避
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 从进行中 id 集合中取本次查询的一批(≤ limit),超过上限时按游标轮转,保证每个任务都能被轮到。
|
||||
* @returns {{ batch: string[], cursor: number }}
|
||||
*/
|
||||
export const pickPollBatch = (ids, cursor = 0, limit = IDS_QUERY_LIMIT) => {
|
||||
const list = [...new Set((ids || []).filter(Boolean))];
|
||||
if (list.length <= limit) return { batch: list, cursor: 0 };
|
||||
const start = ((cursor % list.length) + list.length) % list.length;
|
||||
const batch = [];
|
||||
for (let i = 0; i < limit; i += 1) {
|
||||
batch.push(list[(start + i) % list.length]);
|
||||
}
|
||||
return { batch, cursor: (start + limit) % list.length };
|
||||
};
|
||||
|
||||
/** 退避步进:有变化回到 3s,否则 3s → 5s → 10s。 */
|
||||
export const nextPollStep = (step, changed) =>
|
||||
changed ? 0 : Math.min((Number(step) || 0) + 1, 10);
|
||||
|
||||
/** 下一次轮询的等待时间:页面隐藏时降频(pollDelay 内为 30s)。 */
|
||||
export const nextPollDelay = (step, hidden) => pollDelay(step, hidden);
|
||||
|
||||
/** 把 id 列表切为 ≤ limit 的批次(视频列表补全播放地址用)。 */
|
||||
export const chunkIds = (ids, limit = IDS_QUERY_LIMIT) => {
|
||||
const out = [];
|
||||
const list = (ids || []).filter(Boolean);
|
||||
for (let i = 0; i < list.length; i += limit) {
|
||||
out.push(list.slice(i, i + limit));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 筛选
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const DEFAULT_FILTERS = Object.freeze({
|
||||
status: 'all', // all | active | success | failed
|
||||
model: 'all',
|
||||
size: 'all',
|
||||
keyword: '',
|
||||
favoritesOnly: false,
|
||||
});
|
||||
|
||||
const SERVER_STATUS = { success: 'SUCCESS', failed: 'FAILURE' };
|
||||
|
||||
/**
|
||||
* 列表请求参数:分页用 p=(后端 GetPageQuery,旧图像页的 page= 会被忽略);
|
||||
* 成功 / 失败与只看收藏走服务端过滤,"进行中"(多个状态值)、模型、尺寸、关键词在本地过滤。
|
||||
*/
|
||||
export const buildListParams = (filters, page = 1, pageSize = PAGE_SIZE) => {
|
||||
const f = { ...DEFAULT_FILTERS, ...(filters || {}) };
|
||||
const params = { p: Math.max(1, Number(page) || 1), page_size: pageSize };
|
||||
if (SERVER_STATUS[f.status]) params.status = SERVER_STATUS[f.status];
|
||||
if (f.favoritesOnly) params.favorited = 'true';
|
||||
return params;
|
||||
};
|
||||
|
||||
/** 影响服务端查询的筛选键(变化时需要从第 1 页重新加载)。 */
|
||||
export const serverFilterKey = (filters) => {
|
||||
const params = buildListParams(filters, 1);
|
||||
return `${params.status || ''}|${params.favorited || ''}`;
|
||||
};
|
||||
|
||||
/** 本地过滤(服务端已过滤的条件这里再校验一遍,保证乐观更新后视图一致)。 */
|
||||
export const filterTasks = (list, filters) => {
|
||||
const f = { ...DEFAULT_FILTERS, ...(filters || {}) };
|
||||
const keyword = String(f.keyword || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return (list || []).filter((task) => {
|
||||
if (f.favoritesOnly && !task.favorited) return false;
|
||||
if (f.status === 'active' && !isActiveTask(task)) return false;
|
||||
if (f.status === 'success' && task.status !== 'success') return false;
|
||||
if (f.status === 'failed' && task.status !== 'failed') return false;
|
||||
if (f.model !== 'all' && task.model !== f.model) return false;
|
||||
if (f.size !== 'all' && task.size !== f.size) return false;
|
||||
if (keyword) {
|
||||
const hay = `${task.prompt || ''}\n${task.model || ''}`.toLowerCase();
|
||||
if (!hay.includes(keyword)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 是否有只能在本地过滤的条件(进行中 / 模型 / 尺寸 / 关键词;列表接口不支持这些参数,
|
||||
* 见 controller 的列表处理与 model.SyncTaskQueryParams)。
|
||||
*/
|
||||
export const hasClientFilter = (filters) => {
|
||||
const f = { ...DEFAULT_FILTERS, ...(filters || {}) };
|
||||
return (
|
||||
f.status === 'active' ||
|
||||
f.model !== 'all' ||
|
||||
f.size !== 'all' ||
|
||||
Boolean(String(f.keyword || '').trim())
|
||||
);
|
||||
};
|
||||
|
||||
/** 本地过滤时连续多少页没有新命中后停止自动翻页,改为"加载更多"按钮。 */
|
||||
export const CLIENT_FILTER_EMPTY_PAGE_LIMIT = 3;
|
||||
|
||||
/** 一页加载完成后更新"连续无新命中页数"。 */
|
||||
export const nextEmptyStreak = (streak, matchesBefore, matchesAfter) =>
|
||||
matchesAfter > matchesBefore ? 0 : (Number(streak) || 0) + 1;
|
||||
|
||||
/** 本地过滤时是否继续自动翻页。 */
|
||||
export const shouldAutoLoad = (filters, streak) =>
|
||||
!hasClientFilter(filters) || streak < CLIENT_FILTER_EMPTY_PAGE_LIMIT;
|
||||
|
||||
/** 生效中的筛选条件数量(移动端"筛选"图标角标)。 */
|
||||
export const activeFilterCount = (filters) => {
|
||||
const f = { ...DEFAULT_FILTERS, ...(filters || {}) };
|
||||
let n = 0;
|
||||
if (f.status !== 'all') n += 1;
|
||||
if (f.model !== 'all') n += 1;
|
||||
if (f.size !== 'all') n += 1;
|
||||
if (f.favoritesOnly) n += 1;
|
||||
if (String(f.keyword || '').trim()) n += 1;
|
||||
return n;
|
||||
};
|
||||
|
||||
/** 已加载作品中出现过的模型 / 尺寸(筛选下拉选项)。 */
|
||||
export const facetsOf = (list) => {
|
||||
const models = new Set();
|
||||
const sizes = new Set();
|
||||
(list || []).forEach((task) => {
|
||||
if (task.model) models.add(task.model);
|
||||
if (task.size) sizes.add(task.size);
|
||||
});
|
||||
return { models: [...models].sort(), sizes: [...sizes].sort() };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 日期分组:进行中置顶,其余按 今天 / 昨天 / 近 7 天 / 更早
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const GROUP_LABEL_KEYS = {
|
||||
active: '进行中',
|
||||
today: '今天',
|
||||
yesterday: '昨天',
|
||||
week: '近 7 天',
|
||||
older: '更早',
|
||||
};
|
||||
|
||||
const DAY_MS = 24 * 3600 * 1000;
|
||||
|
||||
const startOfDay = (ms) => {
|
||||
const d = new Date(ms);
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns {{ key: string, tasks: object[] }[]} 组内按创建时间倒序。
|
||||
*/
|
||||
export const groupTasksByDate = (list, now = Date.now()) => {
|
||||
const today = startOfDay(now);
|
||||
const buckets = { active: [], today: [], yesterday: [], week: [], older: [] };
|
||||
(list || []).forEach((task) => {
|
||||
if (isActiveTask(task)) {
|
||||
buckets.active.push(task);
|
||||
return;
|
||||
}
|
||||
const ts = task.createdAt || 0;
|
||||
if (ts >= today) buckets.today.push(task);
|
||||
else if (ts >= today - DAY_MS) buckets.yesterday.push(task);
|
||||
else if (ts >= today - 6 * DAY_MS) buckets.week.push(task);
|
||||
else buckets.older.push(task);
|
||||
});
|
||||
const byTimeDesc = (a, b) => (b.createdAt || 0) - (a.createdAt || 0);
|
||||
return Object.keys(buckets)
|
||||
.filter((key) => buckets[key].length > 0)
|
||||
.map((key) => ({ key, tasks: buckets[key].sort(byTimeDesc) }));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 进度 / 时长展示
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 已用时(秒)。 */
|
||||
export const elapsedSeconds = (task, now = Date.now()) => {
|
||||
const start = task?.startedAt || task?.createdAt || 0;
|
||||
if (!start) return 0;
|
||||
return Math.max(0, Math.floor((now - start) / 1000));
|
||||
};
|
||||
|
||||
/**
|
||||
* 慢任务(WP C-4,方案 §4.5):进行中且已用时超过该模型预计耗时 p90 时提示
|
||||
* "比平时慢,可以切到其他页面,完成后会提醒你"。没有 p90 时不提示。
|
||||
*/
|
||||
export const isSlowTask = (task, p90, now = Date.now()) => {
|
||||
const limit = Number(p90) || 0;
|
||||
if (!isActiveTask(task) || limit <= 0) return false;
|
||||
return elapsedSeconds(task, now) > limit;
|
||||
};
|
||||
|
||||
/** 秒 → "42s" / "1:05" / "1:02:03"。 */
|
||||
export const formatSeconds = (value) => {
|
||||
const s = Math.max(0, Math.round(Number(value) || 0));
|
||||
if (s < 60) return `${s}s`;
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const sec = String(s % 60).padStart(2, '0');
|
||||
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`;
|
||||
};
|
||||
|
||||
/** 卡片 / 播放器的宽高比(限制在 3:4 ~ 16:9 之间,避免极端比例撑破网格)。 */
|
||||
export const aspectRatioOf = (task) => {
|
||||
let ratio = 1;
|
||||
if (task?.kind === 'video') {
|
||||
const m = /^(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)$/.exec(task.ratio || '');
|
||||
ratio = m ? Number(m[1]) / Number(m[2]) : 16 / 9;
|
||||
} else if (task?.width > 0 && task?.height > 0) {
|
||||
ratio = task.width / task.height;
|
||||
}
|
||||
if (!Number.isFinite(ratio) || ratio <= 0) ratio = 1;
|
||||
return Math.min(16 / 9, Math.max(3 / 4, ratio));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 旧收藏同步(localStorage → POST /api/creation/favorites/sync)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 解析旧收藏(JSON 数组,元素为 task_id 或数字 id);无效返回 [],最多 500 个。 */
|
||||
export const parseLegacyFavorites = (raw) => {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const list = JSON.parse(raw);
|
||||
if (!Array.isArray(list)) return [];
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
list.forEach((v) => {
|
||||
const id =
|
||||
typeof v === 'string'
|
||||
? v.trim()
|
||||
: typeof v === 'number' && Number.isInteger(v) && v > 0
|
||||
? String(v)
|
||||
: '';
|
||||
if (id && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
out.push(id);
|
||||
}
|
||||
});
|
||||
return out.slice(0, 500);
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** 结果图片的 task:// 引用(index 从 0 开始,首张省略片段)。 */
|
||||
export const taskImageRef = (taskId, index = 0) =>
|
||||
index > 0 ? `task://${taskId}#${index}` : `task://${taskId}`;
|
||||
|
||||
/** 视频结果尾帧的 task:// 引用(续写下一段,WP C-3;后端优先使用已转存的尾帧)。 */
|
||||
export const taskLastFrameRef = (taskId) => `task://${taskId}#last_frame`;
|
||||
|
||||
const MAX_SEED = 2147483647;
|
||||
|
||||
/**
|
||||
* 换种子再来(WP C-3):回填参数中的种子换成新的随机值(按 schema 的 min / max,缺省 0 ~ 2^31-1),
|
||||
* 且保证与原种子不同。
|
||||
* @param {object} params 回填参数
|
||||
* @param {object|null} seedParam 模型 schema 中的 seed 参数(可为空)
|
||||
* @param {() => number} [rand]
|
||||
*/
|
||||
export const variationParams = (params, seedParam, rand = Math.random) => {
|
||||
const min = Number.isFinite(Number(seedParam?.min))
|
||||
? Number(seedParam.min)
|
||||
: 0;
|
||||
const max = Number.isFinite(Number(seedParam?.max))
|
||||
? Number(seedParam.max)
|
||||
: MAX_SEED;
|
||||
const prev = Number(params?.seed);
|
||||
const span = Math.max(0, max - min);
|
||||
let seed = min + Math.floor(rand() * (span + 1));
|
||||
if (seed === prev)
|
||||
seed = span > 0 ? min + ((seed - min + 1) % (span + 1)) : seed;
|
||||
return { ...(params || {}), seed };
|
||||
};
|
||||
@@ -0,0 +1,444 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
activeFilterCount,
|
||||
appendPage,
|
||||
applyUpdates,
|
||||
aspectRatioOf,
|
||||
buildListParams,
|
||||
chunkIds,
|
||||
elapsedSeconds,
|
||||
facetsOf,
|
||||
filterTasks,
|
||||
finishedTransitions,
|
||||
formatSeconds,
|
||||
groupTasksByDate,
|
||||
mergeTask,
|
||||
nextPollDelay,
|
||||
nextPollStep,
|
||||
normalizeImageTask,
|
||||
normalizeVideoTask,
|
||||
optimisticTask,
|
||||
parseLegacyFavorites,
|
||||
pickPollBatch,
|
||||
serverFilterKey,
|
||||
taskImageRef,
|
||||
taskStatusOf,
|
||||
toMs,
|
||||
upsertTop,
|
||||
CLIENT_FILTER_EMPTY_PAGE_LIMIT,
|
||||
hasClientFilter,
|
||||
nextEmptyStreak,
|
||||
shouldAutoLoad,
|
||||
isSlowTask,
|
||||
taskLastFrameRef,
|
||||
variationParams,
|
||||
} from './creationTasks.js';
|
||||
|
||||
test('taskStatusOf maps backend statuses', () => {
|
||||
assert.equal(taskStatusOf('NOT_START'), 'queued');
|
||||
assert.equal(taskStatusOf('SUBMITTED'), 'queued');
|
||||
assert.equal(taskStatusOf('QUEUED'), 'queued');
|
||||
assert.equal(taskStatusOf('IN_PROGRESS'), 'running');
|
||||
assert.equal(taskStatusOf('SUCCESS'), 'success');
|
||||
assert.equal(taskStatusOf('FAILURE'), 'failed');
|
||||
assert.equal(taskStatusOf('UNKNOWN'), 'running');
|
||||
});
|
||||
|
||||
test('toMs accepts seconds, ms, numeric strings and ISO', () => {
|
||||
assert.equal(toMs(1700000000), 1700000000000);
|
||||
assert.equal(toMs(1700000000000), 1700000000000);
|
||||
assert.equal(toMs('1700000000'), 1700000000000);
|
||||
assert.equal(
|
||||
toMs('2024-01-01T00:00:00Z'),
|
||||
Date.parse('2024-01-01T00:00:00Z'),
|
||||
);
|
||||
assert.equal(toMs(0), 0);
|
||||
assert.equal(toMs('bad'), 0);
|
||||
});
|
||||
|
||||
test('normalizeImageTask reads results, refunds and favorites', () => {
|
||||
const task = normalizeImageTask({
|
||||
id: 7,
|
||||
task_id: 'img_1',
|
||||
status: 'SUCCESS',
|
||||
progress: '100%',
|
||||
created_at: 1700000000,
|
||||
properties: { input: 'from props', origin_model_name: 'gpt-image-1' },
|
||||
data: JSON.stringify({
|
||||
size: '1024x1536',
|
||||
n: 2,
|
||||
data: [
|
||||
{ url: 'https://a/1.png', reusable_as_input: true },
|
||||
{ b64_json: 'xx' },
|
||||
],
|
||||
}),
|
||||
refunded_quota: 0,
|
||||
quoted_quota: 500,
|
||||
favorited: true,
|
||||
});
|
||||
assert.equal(task.id, 'img_1');
|
||||
assert.equal(task.status, 'success');
|
||||
assert.equal(task.prompt, 'from props');
|
||||
assert.equal(task.model, 'gpt-image-1');
|
||||
assert.equal(task.width, 1024);
|
||||
assert.equal(task.height, 1536);
|
||||
assert.equal(task.n, 2);
|
||||
assert.deepEqual(task.images, [
|
||||
{ url: 'https://a/1.png', reusable: true, hasB64: false },
|
||||
{ url: '', reusable: false, hasB64: true },
|
||||
]);
|
||||
assert.equal(task.favorited, true);
|
||||
assert.equal(task.quotedQuota, 500);
|
||||
assert.equal(task.createdAt, 1700000000000);
|
||||
});
|
||||
|
||||
test('normalizeVideoTask reads detail fields', () => {
|
||||
const list = normalizeVideoTask({
|
||||
task_id: 'v1',
|
||||
status: 'SUCCESS',
|
||||
model: 'seedance',
|
||||
prompt: 'p',
|
||||
created_at: 1700000000,
|
||||
});
|
||||
assert.equal(list.hydrated, false);
|
||||
assert.equal(list.videoUrl, '');
|
||||
const detail = normalizeVideoTask({
|
||||
task_id: 'v1',
|
||||
status: 'SUCCESS',
|
||||
data: { video_url: ' https://v/1.mp4 ' },
|
||||
request: { duration: 5, aspect_ratio: '9:16', resolution: '720p' },
|
||||
refunded_quota: 120,
|
||||
cancelable: false,
|
||||
reusable_as_input: true,
|
||||
});
|
||||
assert.equal(detail.hydrated, true);
|
||||
assert.equal(detail.videoUrl, 'https://v/1.mp4');
|
||||
assert.equal(detail.duration, 5);
|
||||
assert.equal(detail.ratio, '9:16');
|
||||
assert.equal(detail.refundedQuota, 120);
|
||||
assert.equal(detail.reusableAsInput, true);
|
||||
});
|
||||
|
||||
test('optimisticTask builds a queued card from the submit response', () => {
|
||||
const img = optimisticTask(
|
||||
'image',
|
||||
{ id: 1, task_id: 'img_9', status: 'NOT_START', created_at: 1700000000 },
|
||||
{ model: 'm', prompt: 'cat', size: '512x512', n: 4 },
|
||||
);
|
||||
assert.equal(img.id, 'img_9');
|
||||
assert.equal(img.status, 'queued');
|
||||
assert.equal(img.n, 4);
|
||||
assert.equal(img.prompt, 'cat');
|
||||
assert.equal(img.optimistic, true);
|
||||
const vid = optimisticTask(
|
||||
'video',
|
||||
{ task_id: 'v9', status: 'SUBMITTED' },
|
||||
{ model: 'k', prompt: 'run', duration: 5, aspect_ratio: '16:9' },
|
||||
);
|
||||
assert.equal(vid.id, 'v9');
|
||||
assert.equal(vid.duration, 5);
|
||||
assert.equal(vid.ratio, '16:9');
|
||||
assert.equal(vid.model, 'k');
|
||||
});
|
||||
|
||||
test('mergeTask keeps detail fields that the poll result lacks', () => {
|
||||
const prev = normalizeVideoTask({
|
||||
task_id: 'v1',
|
||||
status: 'IN_PROGRESS',
|
||||
request: { duration: 5, prompt: 'p' },
|
||||
data: { video_url: 'https://v/old.mp4' },
|
||||
});
|
||||
const next = normalizeVideoTask({
|
||||
task_id: 'v1',
|
||||
status: 'SUCCESS',
|
||||
progress: '100%',
|
||||
});
|
||||
const merged = mergeTask(prev, next);
|
||||
assert.equal(merged.status, 'success');
|
||||
assert.equal(merged.duration, 5);
|
||||
assert.equal(merged.videoUrl, 'https://v/old.mp4');
|
||||
assert.deepEqual(merged.request, { duration: 5, prompt: 'p' });
|
||||
assert.equal(merged.hydrated, true);
|
||||
});
|
||||
|
||||
test('applyUpdates / appendPage / upsertTop keep order and dedupe', () => {
|
||||
const a = { id: 'a', kind: 'image', status: 'running', progress: 0 };
|
||||
const b = { id: 'b', kind: 'image', status: 'success', progress: 100 };
|
||||
const list = [a, b];
|
||||
assert.equal(applyUpdates(list, []), list);
|
||||
const updated = applyUpdates(list, [
|
||||
{ ...a, status: 'success' },
|
||||
{ id: 'zzz', kind: 'image', status: 'success' },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
updated.map((t) => [t.id, t.status]),
|
||||
[
|
||||
['a', 'success'],
|
||||
['b', 'success'],
|
||||
],
|
||||
);
|
||||
const appended = appendPage(list, [{ ...b, prompt: 'x' }, { id: 'c' }]);
|
||||
assert.deepEqual(
|
||||
appended.map((t) => t.id),
|
||||
['a', 'b', 'c'],
|
||||
);
|
||||
assert.equal(appended[1].prompt, 'x');
|
||||
const top = upsertTop(list, { ...b, status: 'queued' });
|
||||
assert.deepEqual(
|
||||
top.map((t) => t.id),
|
||||
['b', 'a'],
|
||||
);
|
||||
assert.equal(top[0].status, 'queued');
|
||||
});
|
||||
|
||||
test('finishedTransitions reports tasks that left the active state', () => {
|
||||
const prev = [
|
||||
{ id: 'a', status: 'running' },
|
||||
{ id: 'b', status: 'queued' },
|
||||
{ id: 'c', status: 'success' },
|
||||
];
|
||||
const out = finishedTransitions(prev, [
|
||||
{ id: 'a', status: 'success' },
|
||||
{ id: 'b', status: 'running' },
|
||||
{ id: 'c', status: 'success' },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
out.map((t) => t.id),
|
||||
['a'],
|
||||
);
|
||||
});
|
||||
|
||||
test('pickPollBatch rotates when more than the limit are active', () => {
|
||||
const ids = Array.from({ length: 25 }, (_, i) => `t${i}`);
|
||||
const first = pickPollBatch(ids, 0, 20);
|
||||
assert.equal(first.batch.length, 20);
|
||||
assert.equal(first.batch[0], 't0');
|
||||
const second = pickPollBatch(ids, first.cursor, 20);
|
||||
assert.equal(second.batch[0], 't20');
|
||||
assert.ok(second.batch.includes('t24'));
|
||||
assert.ok(second.batch.includes('t0'));
|
||||
const small = pickPollBatch(['a', 'a', 'b'], 5, 20);
|
||||
assert.deepEqual(small, { batch: ['a', 'b'], cursor: 0 });
|
||||
});
|
||||
|
||||
test('backoff schedule is 3s → 5s → 10s, slow when hidden', () => {
|
||||
let step = 0;
|
||||
const delays = [];
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
delays.push(nextPollDelay(step, false));
|
||||
step = nextPollStep(step, false);
|
||||
}
|
||||
assert.deepEqual(delays, [3000, 5000, 10000, 10000]);
|
||||
assert.equal(nextPollStep(3, true), 0);
|
||||
assert.equal(nextPollDelay(0, true), 30000);
|
||||
});
|
||||
|
||||
test('chunkIds splits into batches of 20', () => {
|
||||
const ids = Array.from({ length: 41 }, (_, i) => String(i));
|
||||
assert.deepEqual(
|
||||
chunkIds(ids).map((c) => c.length),
|
||||
[20, 20, 1],
|
||||
);
|
||||
});
|
||||
|
||||
test('buildListParams uses p= and server-side filters', () => {
|
||||
assert.deepEqual(buildListParams({}, 2), { p: 2, page_size: 20 });
|
||||
assert.deepEqual(
|
||||
buildListParams({ status: 'success', favoritesOnly: true }, 1, 10),
|
||||
{ p: 1, page_size: 10, status: 'SUCCESS', favorited: 'true' },
|
||||
);
|
||||
assert.deepEqual(buildListParams({ status: 'failed' }, 0), {
|
||||
p: 1,
|
||||
page_size: 20,
|
||||
status: 'FAILURE',
|
||||
});
|
||||
// "进行中" 包含多个后端状态,只在本地过滤
|
||||
assert.deepEqual(buildListParams({ status: 'active' }), {
|
||||
p: 1,
|
||||
page_size: 20,
|
||||
});
|
||||
assert.equal(
|
||||
serverFilterKey({ status: 'active', keyword: 'x' }),
|
||||
serverFilterKey({}),
|
||||
);
|
||||
assert.notEqual(
|
||||
serverFilterKey({ favoritesOnly: true }),
|
||||
serverFilterKey({}),
|
||||
);
|
||||
});
|
||||
|
||||
test('filterTasks applies status, model, size, keyword and favorites', () => {
|
||||
const list = [
|
||||
{ id: '1', status: 'running', model: 'a', size: '1x1', prompt: 'Cat' },
|
||||
{ id: '2', status: 'success', model: 'b', size: '2x2', prompt: 'dog' },
|
||||
{
|
||||
id: '3',
|
||||
status: 'failed',
|
||||
model: 'a',
|
||||
size: '2x2',
|
||||
prompt: 'bird',
|
||||
favorited: true,
|
||||
},
|
||||
];
|
||||
const ids = (f) => filterTasks(list, f).map((t) => t.id);
|
||||
assert.deepEqual(ids({}), ['1', '2', '3']);
|
||||
assert.deepEqual(ids({ status: 'active' }), ['1']);
|
||||
assert.deepEqual(ids({ model: 'a' }), ['1', '3']);
|
||||
assert.deepEqual(ids({ size: '2x2' }), ['2', '3']);
|
||||
assert.deepEqual(ids({ keyword: ' CAT ' }), ['1']);
|
||||
assert.deepEqual(ids({ keyword: 'b' }), ['2', '3']); // 匹配模型名
|
||||
assert.deepEqual(ids({ favoritesOnly: true }), ['3']);
|
||||
assert.equal(activeFilterCount({ status: 'failed', keyword: 'x' }), 2);
|
||||
assert.deepEqual(facetsOf(list), {
|
||||
models: ['a', 'b'],
|
||||
sizes: ['1x1', '2x2'],
|
||||
});
|
||||
});
|
||||
|
||||
test('groupTasksByDate puts active tasks first then by day', () => {
|
||||
const now = new Date(2026, 10, 1, 15, 0, 0).getTime();
|
||||
const day = 24 * 3600 * 1000;
|
||||
const list = [
|
||||
{ id: 'old', status: 'success', createdAt: now - 30 * day },
|
||||
{ id: 'run', status: 'running', createdAt: now - 3 * day },
|
||||
{ id: 'today1', status: 'success', createdAt: now - 3600 * 1000 },
|
||||
{ id: 'today2', status: 'failed', createdAt: now - 60 * 1000 },
|
||||
{ id: 'yday', status: 'success', createdAt: now - day },
|
||||
{ id: 'week', status: 'success', createdAt: now - 4 * day },
|
||||
];
|
||||
const groups = groupTasksByDate(list, now);
|
||||
assert.deepEqual(
|
||||
groups.map((g) => [g.key, g.tasks.map((t) => t.id)]),
|
||||
[
|
||||
['active', ['run']],
|
||||
['today', ['today2', 'today1']],
|
||||
['yesterday', ['yday']],
|
||||
['week', ['week']],
|
||||
['older', ['old']],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(groupTasksByDate([], now), []);
|
||||
});
|
||||
|
||||
test('elapsed / format helpers', () => {
|
||||
assert.equal(elapsedSeconds({ startedAt: 1000 }, 43500), 42);
|
||||
assert.equal(elapsedSeconds({}, 5000), 0);
|
||||
assert.equal(formatSeconds(42), '42s');
|
||||
assert.equal(formatSeconds(65), '1:05');
|
||||
assert.equal(formatSeconds(3723), '1:02:03');
|
||||
});
|
||||
|
||||
test('aspectRatioOf clamps extreme ratios', () => {
|
||||
assert.equal(aspectRatioOf({ kind: 'image', width: 1024, height: 1024 }), 1);
|
||||
assert.equal(aspectRatioOf({ kind: 'video', ratio: '16:9' }), 16 / 9);
|
||||
assert.equal(aspectRatioOf({ kind: 'video', ratio: '9:16' }), 3 / 4);
|
||||
assert.equal(aspectRatioOf({ kind: 'video', ratio: '' }), 16 / 9);
|
||||
assert.equal(
|
||||
aspectRatioOf({ kind: 'image', width: 4000, height: 1000 }),
|
||||
16 / 9,
|
||||
);
|
||||
});
|
||||
|
||||
test('parseLegacyFavorites tolerates bad data', () => {
|
||||
assert.deepEqual(parseLegacyFavorites(null), []);
|
||||
assert.deepEqual(parseLegacyFavorites('{oops'), []);
|
||||
assert.deepEqual(parseLegacyFavorites('{"a":1}'), []);
|
||||
assert.deepEqual(
|
||||
parseLegacyFavorites('["a", " a ", 12, 1.5, -1, null, "b"]'),
|
||||
['a', '12', 'b'],
|
||||
);
|
||||
});
|
||||
|
||||
test('taskImageRef uses 0-based fragments', () => {
|
||||
assert.equal(taskImageRef('t1'), 'task://t1');
|
||||
assert.equal(taskImageRef('t1', 2), 'task://t1#2');
|
||||
});
|
||||
|
||||
test('client-side filters stop auto-loading after empty pages', () => {
|
||||
assert.equal(hasClientFilter({}), false);
|
||||
assert.equal(
|
||||
hasClientFilter({ status: 'success', favoritesOnly: true }),
|
||||
false,
|
||||
);
|
||||
assert.equal(hasClientFilter({ status: 'active' }), true);
|
||||
assert.equal(hasClientFilter({ keyword: ' cat ' }), true);
|
||||
assert.equal(hasClientFilter({ model: 'm' }), true);
|
||||
assert.equal(hasClientFilter({ size: '1024x1024' }), true);
|
||||
assert.equal(nextEmptyStreak(2, 5, 6), 0);
|
||||
assert.equal(nextEmptyStreak(2, 5, 5), 3);
|
||||
const f = { keyword: 'cat' };
|
||||
assert.equal(shouldAutoLoad(f, CLIENT_FILTER_EMPTY_PAGE_LIMIT - 1), true);
|
||||
assert.equal(shouldAutoLoad(f, CLIENT_FILTER_EMPTY_PAGE_LIMIT), false);
|
||||
// 服务端筛选不受限制
|
||||
assert.equal(shouldAutoLoad({ status: 'failed' }, 99), true);
|
||||
});
|
||||
|
||||
test('C-2 batch_id:列表项归一化、乐观插入、合并保留', () => {
|
||||
const task = normalizeImageTask({
|
||||
task_id: 't',
|
||||
status: 'SUCCESS',
|
||||
batch_id: 'b-1',
|
||||
});
|
||||
assert.equal(task.batchId, 'b-1');
|
||||
assert.equal(normalizeImageTask({ task_id: 't' }).batchId, '');
|
||||
const optimistic = optimisticTask(
|
||||
'image',
|
||||
{ task_id: 'o' },
|
||||
{ model: 'm', batch_id: 'b-2' },
|
||||
);
|
||||
assert.equal(optimistic.batchId, 'b-2');
|
||||
// 轮询口径没带 batch_id 时保留
|
||||
assert.equal(
|
||||
mergeTask(optimistic, { ...optimistic, batchId: '' }).batchId,
|
||||
'b-2',
|
||||
);
|
||||
});
|
||||
|
||||
test('C-4 isSlowTask:进行中且超过 p90', () => {
|
||||
const now = 1_800_000_000_000;
|
||||
const running = { status: 'running', startedAt: now - 100_000 };
|
||||
assert.equal(isSlowTask(running, 90, now), true);
|
||||
assert.equal(isSlowTask(running, 120, now), false);
|
||||
assert.equal(isSlowTask(running, 0, now), false);
|
||||
assert.equal(isSlowTask({ ...running, status: 'success' }, 10, now), false);
|
||||
});
|
||||
|
||||
test('C-3 variationParams / taskLastFrameRef', () => {
|
||||
const seq = [0.5, 0.5];
|
||||
const rand = () => seq.shift() ?? 0;
|
||||
const r = variationParams(
|
||||
{ seed: 7, size: '1x1' },
|
||||
{ min: 0, max: 100 },
|
||||
rand,
|
||||
);
|
||||
assert.equal(r.size, '1x1');
|
||||
assert.equal(r.seed, 50);
|
||||
// 与原种子相同时换一个
|
||||
assert.notEqual(
|
||||
variationParams({ seed: 50 }, { min: 0, max: 100 }, () => 0.5).seed,
|
||||
50,
|
||||
);
|
||||
const d = variationParams({}, null, () => 0.999999);
|
||||
assert.ok(d.seed >= 0 && d.seed <= 2147483647);
|
||||
assert.equal(taskLastFrameRef('v1'), 'task://v1#last_frame');
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 完成提醒(WP C-4,方案 §4.5)纯函数:进行中任务登记、完成结算、未读角标计数、已读时间。
|
||||
//
|
||||
// 状态(localStorage creation.watch.v1,读写全部 try/catch):
|
||||
// pending[kind] = [{ id, at }] 提交后登记的进行中任务(只记 id,不做额外的重轮询)
|
||||
// finished[kind] = [{ id, at, status }] 用户不在该创作页时完成的任务
|
||||
// seen[kind] = 毫秒时间戳 用户最近一次查看该创作页的时间
|
||||
// 未读 = finished 中完成时间晚于 seen 的条数。
|
||||
// 不依赖 React / 浏览器,node --test 覆盖(creationWatch.test.js)。
|
||||
|
||||
export const WATCH_STORAGE_KEY = 'creation.watch.v1';
|
||||
export const WATCH_KINDS = ['image', 'video'];
|
||||
/** 登记超过 24 小时仍未结算的任务视为过期(任务被删除 / 跨设备),不再轮询。 */
|
||||
export const PENDING_MAX_AGE_MS = 24 * 3600 * 1000;
|
||||
/** 未读记录保留 7 天。 */
|
||||
export const FINISHED_MAX_AGE_MS = 7 * 24 * 3600 * 1000;
|
||||
export const PENDING_LIMIT = 50;
|
||||
export const FINISHED_LIMIT = 50;
|
||||
/** 不在创作页时的轻量轮询间隔。 */
|
||||
export const WATCH_POLL_MS = 30 * 1000;
|
||||
|
||||
const isKind = (kind) => WATCH_KINDS.includes(kind);
|
||||
|
||||
export const emptyWatchState = () => ({
|
||||
pending: { image: [], video: [] },
|
||||
finished: { image: [], video: [] },
|
||||
seen: { image: 0, video: 0 },
|
||||
});
|
||||
|
||||
const cleanEntries = (list, limit) =>
|
||||
(Array.isArray(list) ? list : [])
|
||||
.filter(
|
||||
(e) =>
|
||||
e && typeof e.id === 'string' && e.id && Number.isFinite(Number(e.at)),
|
||||
)
|
||||
.map((e) => ({ ...e, at: Number(e.at) }))
|
||||
.slice(-limit);
|
||||
|
||||
/** 解析存储内容;损坏 / 缺字段时回到空状态。 */
|
||||
export const parseWatchState = (raw) => {
|
||||
const out = emptyWatchState();
|
||||
if (!raw) return out;
|
||||
let data;
|
||||
try {
|
||||
data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
||||
} catch (e) {
|
||||
return out;
|
||||
}
|
||||
if (!data || typeof data !== 'object') return out;
|
||||
WATCH_KINDS.forEach((kind) => {
|
||||
out.pending[kind] = cleanEntries(data.pending?.[kind], PENDING_LIMIT);
|
||||
out.finished[kind] = cleanEntries(data.finished?.[kind], FINISHED_LIMIT);
|
||||
const seen = Number(data.seen?.[kind]);
|
||||
out.seen[kind] = Number.isFinite(seen) && seen > 0 ? seen : 0;
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
const withKind = (state, field, kind, list) => ({
|
||||
...state,
|
||||
[field]: { ...state[field], [kind]: list },
|
||||
});
|
||||
|
||||
/** 登记进行中任务(已登记的保持原登记时间不变;最多 50 个)。 */
|
||||
export const trackPending = (state, kind, id, now = Date.now()) => {
|
||||
if (!isKind(kind) || !id) return state;
|
||||
const key = String(id);
|
||||
if (state.pending[kind].some((e) => e.id === key)) return state;
|
||||
const list = [...state.pending[kind], { id: key, at: now }];
|
||||
return withKind(state, 'pending', kind, list.slice(-PENDING_LIMIT));
|
||||
};
|
||||
|
||||
/** 当前需要轮询的进行中 id(剔除过期登记)。 */
|
||||
export const pendingIdsOf = (state, kind, now = Date.now()) =>
|
||||
isKind(kind)
|
||||
? state.pending[kind]
|
||||
.filter((e) => now - e.at <= PENDING_MAX_AGE_MS)
|
||||
.map((e) => e.id)
|
||||
: [];
|
||||
|
||||
/**
|
||||
* 结算一批轮询结果(作品流统一结构:{ id, status }):进入终态的移出 pending;
|
||||
* 用户不在该创作页(seen=false)时记入 finished 产生未读。
|
||||
* @returns {{ state, finished: object[] }} finished 为本次新进入终态的作品(供浏览器通知)
|
||||
*/
|
||||
export const settleTasks = (
|
||||
state,
|
||||
kind,
|
||||
updates,
|
||||
{ now = Date.now(), seen = false } = {},
|
||||
) => {
|
||||
if (!isKind(kind)) return { state, finished: [] };
|
||||
const pending = new Set(state.pending[kind].map((e) => e.id));
|
||||
const done = (updates || []).filter(
|
||||
(task) =>
|
||||
task &&
|
||||
pending.has(String(task.id)) &&
|
||||
(task.status === 'success' || task.status === 'failed'),
|
||||
);
|
||||
if (!done.length) return { state, finished: [] };
|
||||
const doneIds = new Set(done.map((task) => String(task.id)));
|
||||
let next = withKind(
|
||||
state,
|
||||
'pending',
|
||||
kind,
|
||||
state.pending[kind].filter((e) => !doneIds.has(e.id)),
|
||||
);
|
||||
if (!seen) {
|
||||
const kept = next.finished[kind].filter((e) => !doneIds.has(e.id));
|
||||
done.forEach((task) =>
|
||||
kept.push({ id: String(task.id), at: now, status: task.status }),
|
||||
);
|
||||
next = withKind(next, 'finished', kind, kept.slice(-FINISHED_LIMIT));
|
||||
}
|
||||
return { state: next, finished: done };
|
||||
};
|
||||
|
||||
/** 移除登记(查询不到 = 已删除)。 */
|
||||
export const dropPending = (state, kind, ids) => {
|
||||
if (!isKind(kind) || !ids || !ids.length) return state;
|
||||
const drop = new Set(ids.map(String));
|
||||
const list = state.pending[kind].filter((e) => !drop.has(e.id));
|
||||
return list.length === state.pending[kind].length
|
||||
? state
|
||||
: withKind(state, 'pending', kind, list);
|
||||
};
|
||||
|
||||
/** 用户查看了该创作页:记录时间并清空未读。 */
|
||||
export const markSeen = (state, kind, now = Date.now()) => {
|
||||
if (!isKind(kind)) return state;
|
||||
return {
|
||||
...state,
|
||||
seen: { ...state.seen, [kind]: now },
|
||||
finished: { ...state.finished, [kind]: [] },
|
||||
};
|
||||
};
|
||||
|
||||
/** 侧边栏角标数字。 */
|
||||
export const unreadCount = (state, kind) => {
|
||||
if (!isKind(kind)) return 0;
|
||||
const seen = state.seen[kind] || 0;
|
||||
return state.finished[kind].filter((e) => e.at > seen).length;
|
||||
};
|
||||
|
||||
/** 角标文案:超过 99 显示 99+。 */
|
||||
export const badgeText = (count) => {
|
||||
const n = Number(count) || 0;
|
||||
if (n <= 0) return '';
|
||||
return n > 99 ? '99+' : String(n);
|
||||
};
|
||||
|
||||
/** 清理过期的登记与未读记录。 */
|
||||
export const pruneWatchState = (state, now = Date.now()) => {
|
||||
const next = emptyWatchState();
|
||||
WATCH_KINDS.forEach((kind) => {
|
||||
next.pending[kind] = state.pending[kind].filter(
|
||||
(e) => now - e.at <= PENDING_MAX_AGE_MS,
|
||||
);
|
||||
next.finished[kind] = state.finished[kind].filter(
|
||||
(e) => now - e.at <= FINISHED_MAX_AGE_MS,
|
||||
);
|
||||
next.seen[kind] = state.seen[kind] || 0;
|
||||
});
|
||||
return next;
|
||||
};
|
||||
|
||||
/** 哪些 kind 需要后台轮询:有进行中登记,且用户当前不在该创作页(创作页自己会轮询)。 */
|
||||
export const kindsToPoll = (state, activeKinds, now = Date.now()) =>
|
||||
WATCH_KINDS.filter(
|
||||
(kind) =>
|
||||
!(activeKinds && activeKinds.has(kind)) &&
|
||||
pendingIdsOf(state, kind, now).length > 0,
|
||||
);
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
FINISHED_MAX_AGE_MS,
|
||||
PENDING_LIMIT,
|
||||
PENDING_MAX_AGE_MS,
|
||||
badgeText,
|
||||
dropPending,
|
||||
emptyWatchState,
|
||||
kindsToPoll,
|
||||
markSeen,
|
||||
parseWatchState,
|
||||
pendingIdsOf,
|
||||
pruneWatchState,
|
||||
settleTasks,
|
||||
trackPending,
|
||||
unreadCount,
|
||||
} from './creationWatch.js';
|
||||
|
||||
const NOW = 1_800_000_000_000;
|
||||
|
||||
test('parseWatchState:损坏 / 缺字段回到空状态,过滤非法条目', () => {
|
||||
assert.deepEqual(parseWatchState(''), emptyWatchState());
|
||||
assert.deepEqual(parseWatchState('{bad'), emptyWatchState());
|
||||
assert.deepEqual(parseWatchState('[]'), emptyWatchState());
|
||||
const s = parseWatchState(
|
||||
JSON.stringify({
|
||||
pending: {
|
||||
image: [{ id: 'a', at: 1 }, { id: '', at: 2 }, { at: 3 }, null],
|
||||
},
|
||||
finished: { video: [{ id: 'v', at: '5', status: 'success' }] },
|
||||
seen: { image: 9, video: -1 },
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(s.pending.image, [{ id: 'a', at: 1 }]);
|
||||
assert.deepEqual(s.finished.video, [{ id: 'v', at: 5, status: 'success' }]);
|
||||
assert.deepEqual(s.seen, { image: 9, video: 0 });
|
||||
});
|
||||
|
||||
test('trackPending:去重保留原时间,上限 50,非法 kind 忽略', () => {
|
||||
let s = trackPending(emptyWatchState(), 'image', 'a', NOW);
|
||||
s = trackPending(s, 'image', 'a', NOW + 10);
|
||||
assert.deepEqual(s.pending.image, [{ id: 'a', at: NOW }]);
|
||||
assert.equal(trackPending(s, 'text', 'x', NOW), s);
|
||||
for (let i = 0; i < 60; i += 1) s = trackPending(s, 'video', `v${i}`, NOW);
|
||||
assert.equal(s.pending.video.length, PENDING_LIMIT);
|
||||
assert.equal(s.pending.video[0].id, 'v10');
|
||||
});
|
||||
|
||||
test('settleTasks:不在页面时完成计入未读;在页面时只移出登记', () => {
|
||||
let s = trackPending(emptyWatchState(), 'image', 'a', NOW);
|
||||
s = trackPending(s, 'image', 'b', NOW);
|
||||
s = trackPending(s, 'image', 'c', NOW);
|
||||
const updates = [
|
||||
{ id: 'a', status: 'success' },
|
||||
{ id: 'b', status: 'running' },
|
||||
{ id: 'c', status: 'failed' },
|
||||
{ id: 'z', status: 'success' }, // 未登记
|
||||
];
|
||||
const away = settleTasks(s, 'image', updates, { now: NOW + 5, seen: false });
|
||||
assert.deepEqual(
|
||||
away.finished.map((t) => t.id),
|
||||
['a', 'c'],
|
||||
);
|
||||
assert.deepEqual(pendingIdsOf(away.state, 'image', NOW + 5), ['b']);
|
||||
assert.equal(unreadCount(away.state, 'image'), 2);
|
||||
assert.equal(unreadCount(away.state, 'video'), 0);
|
||||
|
||||
const here = settleTasks(s, 'image', updates, { now: NOW + 5, seen: true });
|
||||
assert.equal(here.finished.length, 2, '仍返回完成的作品供浏览器通知');
|
||||
assert.equal(unreadCount(here.state, 'image'), 0);
|
||||
|
||||
const none = settleTasks(s, 'image', [{ id: 'a', status: 'queued' }]);
|
||||
assert.equal(none.state, s);
|
||||
assert.deepEqual(none.finished, []);
|
||||
});
|
||||
|
||||
test('markSeen 清空未读;dropPending 移除登记', () => {
|
||||
let s = trackPending(emptyWatchState(), 'video', 'v', NOW);
|
||||
s = settleTasks(s, 'video', [{ id: 'v', status: 'success' }], {
|
||||
now: NOW,
|
||||
}).state;
|
||||
assert.equal(unreadCount(s, 'video'), 1);
|
||||
s = markSeen(s, 'video', NOW + 1);
|
||||
assert.equal(unreadCount(s, 'video'), 0);
|
||||
assert.equal(s.seen.video, NOW + 1);
|
||||
|
||||
s = trackPending(s, 'image', 'x', NOW);
|
||||
assert.deepEqual(
|
||||
pendingIdsOf(dropPending(s, 'image', ['x']), 'image', NOW),
|
||||
[],
|
||||
);
|
||||
assert.equal(dropPending(s, 'image', ['nope']), s);
|
||||
});
|
||||
|
||||
test('pendingIdsOf / pruneWatchState:过期登记与旧未读', () => {
|
||||
let s = trackPending(
|
||||
emptyWatchState(),
|
||||
'image',
|
||||
'old',
|
||||
NOW - PENDING_MAX_AGE_MS - 1,
|
||||
);
|
||||
s = trackPending(s, 'image', 'new', NOW);
|
||||
assert.deepEqual(pendingIdsOf(s, 'image', NOW), ['new']);
|
||||
s = {
|
||||
...s,
|
||||
finished: {
|
||||
image: [
|
||||
{ id: 'f', at: NOW - FINISHED_MAX_AGE_MS - 1, status: 'success' },
|
||||
],
|
||||
video: [],
|
||||
},
|
||||
};
|
||||
const pruned = pruneWatchState(s, NOW);
|
||||
assert.deepEqual(
|
||||
pruned.pending.image.map((e) => e.id),
|
||||
['new'],
|
||||
);
|
||||
assert.deepEqual(pruned.finished.image, []);
|
||||
});
|
||||
|
||||
test('kindsToPoll:只轮询有登记且不在当前创作页的 kind', () => {
|
||||
let s = trackPending(emptyWatchState(), 'image', 'a', NOW);
|
||||
s = trackPending(s, 'video', 'v', NOW);
|
||||
assert.deepEqual(kindsToPoll(s, new Set(), NOW), ['image', 'video']);
|
||||
assert.deepEqual(kindsToPoll(s, new Set(['image']), NOW), ['video']);
|
||||
assert.deepEqual(kindsToPoll(emptyWatchState(), new Set(), NOW), []);
|
||||
});
|
||||
|
||||
test('badgeText', () => {
|
||||
assert.equal(badgeText(0), '');
|
||||
assert.equal(badgeText(3), '3');
|
||||
assert.equal(badgeText(120), '99+');
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useCallback, useContext, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showInfo, showSuccess } from '../../helpers';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { trackCreationEvent } from '../../helpers/creationEvents';
|
||||
import { imageBlockReason } from '../image/imageCreation';
|
||||
import {
|
||||
COMPARE_MAX,
|
||||
COMPARE_MIN,
|
||||
compareBlockOf,
|
||||
compareQuoteRequest,
|
||||
needsBatchConfirm,
|
||||
newBatchId,
|
||||
resolveCompareEntries,
|
||||
selectedCompareModels,
|
||||
sharedParamsOf,
|
||||
sharedValuesOf,
|
||||
toggleCompareModel,
|
||||
} from './creationCompare';
|
||||
import { normalizeSubmitError } from './creationForm';
|
||||
import { useCreationQuote } from './useCreationQuote';
|
||||
|
||||
const isReady = (slot) =>
|
||||
Boolean(slot && slot.ref && (slot.status || 'ready') === 'ready');
|
||||
|
||||
/**
|
||||
* 图像对比生成(WP C-2,方案 §4.2):在 ModelPicker 中勾选 2~4 个模型;创作台只显示共同参数;
|
||||
* 提交前摘要(模型 · 实际参数 · 价格 + 合计,quote items[]);用同一个 batch_id 逐个提交。
|
||||
*
|
||||
* @param {object} form useCreationForm(kind) 的返回值
|
||||
* @param {{ onSubmitted?: (result, payload) => void }} [options]
|
||||
*/
|
||||
export const useCreationCompare = (form, { onSubmitted } = {}) => {
|
||||
const { t } = useTranslation();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const supported = form.kind === 'image';
|
||||
const [active, setActive] = useState(false);
|
||||
const [names, setNames] = useState([]);
|
||||
const [values, setValues] = useState({});
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const refList = form.form.images?.reference_images;
|
||||
const refs = useMemo(() => refList || [], [refList]);
|
||||
const refCount = form.mode === 'edit' ? refs.filter(isReady).length : 0;
|
||||
const ctx = useMemo(
|
||||
() => ({ mode: form.mode, refCount }),
|
||||
[form.mode, refCount],
|
||||
);
|
||||
|
||||
const blockOf = useCallback((model) => compareBlockOf(model, ctx), [ctx]);
|
||||
const models = useMemo(
|
||||
() => (active ? selectedCompareModels(form.models, names, ctx) : []),
|
||||
[active, form.models, names, ctx],
|
||||
);
|
||||
const shared = useMemo(
|
||||
() => sharedParamsOf(models, { mode: form.mode }),
|
||||
[models, form.mode],
|
||||
);
|
||||
const sharedValues = useMemo(
|
||||
() => sharedValuesOf(shared, values, form.params),
|
||||
[shared, values, form.params],
|
||||
);
|
||||
const entries = useMemo(
|
||||
() =>
|
||||
models.length >= COMPARE_MIN
|
||||
? resolveCompareEntries(models, form.form, sharedValues, '')
|
||||
: [],
|
||||
[models, form.form, sharedValues],
|
||||
);
|
||||
const quoteRequest = useMemo(
|
||||
() => (active ? compareQuoteRequest(entries) : null),
|
||||
[active, entries],
|
||||
);
|
||||
const quoteState = useCreationQuote(quoteRequest);
|
||||
|
||||
const threshold =
|
||||
statusState?.status?.experience_center_batch_confirm_threshold;
|
||||
const overThreshold = needsBatchConfirm(quoteState.quote?.total, threshold, {
|
||||
batch: true,
|
||||
});
|
||||
|
||||
const blockReason = useMemo(() => {
|
||||
if (!active) return '';
|
||||
if (models.length < COMPARE_MIN) {
|
||||
return t('请选择 {{min}}~{{max}} 个模型进行对比', {
|
||||
min: COMPARE_MIN,
|
||||
max: COMPARE_MAX,
|
||||
});
|
||||
}
|
||||
if (!String(form.prompt || '').trim()) return t('请输入提示词');
|
||||
for (const model of models) {
|
||||
const reason = imageBlockReason(model, form.mode, refs);
|
||||
if (reason) return t(reason.key);
|
||||
}
|
||||
const max = Number(form.maxRunning) || 0;
|
||||
if (max > 0 && (Number(form.runningCount) || 0) + models.length > max) {
|
||||
return t('进行中任务最多 {{max}} 个,本次对比需要 {{n}} 个名额', {
|
||||
max,
|
||||
n: models.length,
|
||||
});
|
||||
}
|
||||
return '';
|
||||
}, [
|
||||
active,
|
||||
models,
|
||||
form.prompt,
|
||||
form.mode,
|
||||
form.maxRunning,
|
||||
form.runningCount,
|
||||
refs,
|
||||
t,
|
||||
]);
|
||||
|
||||
const enter = useCallback(() => {
|
||||
if (!supported) return;
|
||||
setActive(true);
|
||||
setNames((prev) => {
|
||||
if (prev.length) return prev;
|
||||
const current = form.selectedModel;
|
||||
return current && !compareBlockOf(current, ctx) ? [current.model] : [];
|
||||
});
|
||||
}, [supported, form.selectedModel, ctx]);
|
||||
|
||||
const exit = useCallback(() => setActive(false), []);
|
||||
const setEnabled = useCallback(
|
||||
(on) => (on ? enter() : exit()),
|
||||
[enter, exit],
|
||||
);
|
||||
|
||||
const toggleModel = useCallback(
|
||||
(model) => {
|
||||
if (!model) return;
|
||||
const reason = compareBlockOf(model, ctx);
|
||||
if (reason) {
|
||||
showInfo(t(reason.key, reason.values));
|
||||
return;
|
||||
}
|
||||
setNames((prev) => {
|
||||
const r = toggleCompareModel(prev, model.model, COMPARE_MAX);
|
||||
if (r.full) {
|
||||
showInfo(t('最多选择 {{n}} 个模型', { n: COMPARE_MAX }));
|
||||
}
|
||||
return r.selected;
|
||||
});
|
||||
},
|
||||
[ctx, t],
|
||||
);
|
||||
|
||||
const setValue = useCallback((key, value) => {
|
||||
setValues((prev) => ({ ...prev, [key]: value }));
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 逐个提交(同一 batch_id)。部分失败时成功的照常出现在作品流,失败的汇总提示。
|
||||
* @returns {Promise<boolean>} 至少一个成功
|
||||
*/
|
||||
const submit = useCallback(async () => {
|
||||
if (submitting || blockReason || !entries.length) {
|
||||
if (blockReason) showError(blockReason);
|
||||
return false;
|
||||
}
|
||||
setSubmitting(true);
|
||||
const batchId = newBatchId();
|
||||
const list = resolveCompareEntries(
|
||||
models,
|
||||
form.form,
|
||||
sharedValues,
|
||||
batchId,
|
||||
);
|
||||
let ok = 0;
|
||||
const failures = [];
|
||||
try {
|
||||
for (const entry of list) {
|
||||
try {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const res = await API.post('/api/images/generations', entry.payload, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success) throw { data: res?.data };
|
||||
ok += 1;
|
||||
if (onSubmitted) {
|
||||
onSubmitted({ ok: true, data: res.data.data }, entry.payload);
|
||||
}
|
||||
} catch (error) {
|
||||
const e = normalizeSubmitError(error);
|
||||
failures.push(
|
||||
`${entry.payload.model}:${e.message || t('提交失败')}`,
|
||||
);
|
||||
// 并发上限:后面的模型也会被拒绝,停止提交
|
||||
if (e.code === 'too_many_running_tasks') break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
trackCreationEvent('submit', {
|
||||
kind: 'image',
|
||||
model: list.map((e) => e.payload.model).join(','),
|
||||
mode: form.mode,
|
||||
batch_size: list.length,
|
||||
compare: true,
|
||||
});
|
||||
if (failures.length) {
|
||||
showError(
|
||||
t('{{ok}} 个模型已提交,{{n}} 个失败:{{list}}', {
|
||||
ok,
|
||||
n: list.length - ok,
|
||||
list: failures.join(';'),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
showSuccess(t('已提交 {{n}} 个模型的对比生成', { n: ok }));
|
||||
}
|
||||
return ok > 0;
|
||||
}, [
|
||||
submitting,
|
||||
blockReason,
|
||||
entries.length,
|
||||
models,
|
||||
form.form,
|
||||
form.mode,
|
||||
sharedValues,
|
||||
onSubmitted,
|
||||
t,
|
||||
]);
|
||||
|
||||
return {
|
||||
supported,
|
||||
active,
|
||||
setEnabled,
|
||||
names,
|
||||
models,
|
||||
blockOf,
|
||||
toggleModel,
|
||||
shared,
|
||||
values: sharedValues,
|
||||
setValue,
|
||||
entries,
|
||||
quote: quoteState.quote,
|
||||
quoteLoading: quoteState.loading,
|
||||
quoteFailed: quoteState.failed,
|
||||
overThreshold,
|
||||
blockReason,
|
||||
submitting,
|
||||
submit,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCreationCompare;
|
||||
@@ -0,0 +1,806 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showInfo } from '../../helpers';
|
||||
import {
|
||||
getExperienceCenterBool,
|
||||
getExperienceCenterPositiveInt,
|
||||
} from '../../helpers/experienceCenter';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import {
|
||||
budgetShortfallOf,
|
||||
classifyCreationError,
|
||||
describeCreationError,
|
||||
} from '../../helpers/creationError';
|
||||
import { trackCreationEvent } from '../../helpers/creationEvents';
|
||||
import {
|
||||
optionLabel,
|
||||
paramLabel,
|
||||
} from '../../components/creation/params/labels';
|
||||
import { useCreationModels } from './useCreationModels';
|
||||
import { useCreationQuote } from './useCreationQuote';
|
||||
import { autoSubmitDecision } from './creationCompare';
|
||||
import { openBatchConfirm } from '../../components/creation/batchConfirm';
|
||||
import {
|
||||
adapterOf,
|
||||
allImageSlots,
|
||||
applyPrefill,
|
||||
buildPayload,
|
||||
buildQuoteRequest,
|
||||
formBlockReason,
|
||||
initialModelOf,
|
||||
loadForm,
|
||||
markExpiredSlots,
|
||||
modelNameOf,
|
||||
normalizeSubmitError,
|
||||
patchImageSlotById,
|
||||
saveForm,
|
||||
switchModel,
|
||||
visibleParamsOf,
|
||||
writeImageSlot,
|
||||
} from './creationForm';
|
||||
import { templateModelFor, templateParamsFor } from './creationDock';
|
||||
|
||||
// 不经上传接口、内联 base64 提交时的单张图片上限(与旧图像表单一致)
|
||||
const INLINE_MAX_MB = 20;
|
||||
|
||||
const SUBMIT_ENDPOINTS = {
|
||||
image: '/api/images/generations',
|
||||
video: '/api/video/generate',
|
||||
};
|
||||
|
||||
const getStorage = () => {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const newSlotId = () =>
|
||||
`slot-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
const readAsDataURL = (file) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.onerror = () => reject(reader.error || new Error('read failed'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
/** 默认提交:直接调用既有接口,返回与 useImageTaskManagement.addTask 相同的结构。 */
|
||||
const defaultSubmitter = (kind) => async (payload) => {
|
||||
try {
|
||||
const res = await API.post(SUBMIT_ENDPOINTS[kind], payload, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success) throw { data: res?.data };
|
||||
return { ok: true, data: res.data.data };
|
||||
} catch (error) {
|
||||
const e = normalizeSubmitError(error);
|
||||
return {
|
||||
ok: false,
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
status: Number(error?.response?.status) || 0,
|
||||
data: { running_tasks: e.running, max_running_tasks: e.max },
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 新创作台共用的表单状态机(WP B-2):模型 / 模式 / 提示词 / 参数 / 图片槽、按模型记忆、
|
||||
* 参数优先级与吸附(方案 §4.3)、估价、提交与并发上限。
|
||||
*
|
||||
* @param {'image'|'video'} kind
|
||||
* @param {{
|
||||
* submitter?: (payload) => Promise<{ ok: boolean, code?: string, message?: string, data?: object }>,
|
||||
* 默认直接 POST 既有接口;图像作品流可传 useImageTaskManagement.addTask 以便列表即时出现新任务。
|
||||
* onSubmitted?: (result, payload) => void, 提交成功后回调(作品流乐观插入新任务)
|
||||
* localRunning?: number, 作品流中进行中的任务数(与服务端数字取大)
|
||||
* }} [options]
|
||||
*/
|
||||
export const useCreationForm = (
|
||||
kind,
|
||||
{ submitter, onSubmitted, localRunning = 0 } = {},
|
||||
) => {
|
||||
const { t } = useTranslation();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const status = statusState?.status;
|
||||
const adapter = adapterOf(kind);
|
||||
|
||||
const {
|
||||
data: creationData,
|
||||
models,
|
||||
loading: modelsLoading,
|
||||
error: modelsError,
|
||||
reload: reloadModels,
|
||||
} = useCreationModels(kind);
|
||||
|
||||
const [form, setForm] = useState(() => loadForm(kind, getStorage()));
|
||||
const formRef = useRef(form);
|
||||
formRef.current = form;
|
||||
const commit = useCallback((next) => {
|
||||
formRef.current = next;
|
||||
setForm(next);
|
||||
}, []);
|
||||
|
||||
// 本次会话用户手动设置过的参数(优先级 1)
|
||||
const sessionValuesRef = useRef({});
|
||||
const schemaAppliedRef = useRef(false);
|
||||
const fileStoreRef = useRef(new Map()); // slotId → File(重试用,不进存储)
|
||||
// 最近一次吸附的明细,供界面展示(同时会 toast)
|
||||
const [adjustments, setAdjustments] = useState([]);
|
||||
// 请求创作台展开并聚焦提示词(复用参数 / 编辑此图等外部操作后递增,CreationDock 监听)
|
||||
const [focusTick, setFocusTick] = useState(0);
|
||||
const requestFocus = useCallback(() => setFocusTick((n) => n + 1), []);
|
||||
// 再生成:回填后待提交(下一次渲染 payload 更新后执行)
|
||||
const autoSubmitRef = useRef(false);
|
||||
|
||||
const selectedModel = useMemo(
|
||||
() => models.find((m) => m.model === form.modelName) || null,
|
||||
[models, form.modelName],
|
||||
);
|
||||
// 全部模型都被等级锁定(方案 §4.6):卡片可见,创作台给出升级入口
|
||||
const allLocked =
|
||||
models.length > 0 && models.every((m) => m && m.level_locked);
|
||||
|
||||
// 记忆写入(防抖)
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => saveForm(kind, getStorage(), form), 800);
|
||||
return () => clearTimeout(timer);
|
||||
}, [kind, form]);
|
||||
|
||||
const notifyAdjustments = useCallback(
|
||||
(model, list, modeChange) => {
|
||||
const params = adapter.requestParamsOf(model);
|
||||
const items = (list || []).map((a) => {
|
||||
const param = params.find((p) => p.key === a.key) || { key: a.key };
|
||||
return `${paramLabel(t, param)} ${optionLabel(t, param, a.from)} → ${optionLabel(t, param, a.to)}`;
|
||||
});
|
||||
if (modeChange) {
|
||||
const labels = adapter.modeLabels;
|
||||
items.unshift(
|
||||
`${t('生成模式')} ${t(labels[modeChange.from] || modeChange.from)} → ${t(labels[modeChange.to] || modeChange.to)}`,
|
||||
);
|
||||
}
|
||||
setAdjustments(items);
|
||||
if (items.length) {
|
||||
showInfo(
|
||||
t('已按新模型调整:{{list}}(该模型不支持原取值)', {
|
||||
list: items.join(';'),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[adapter, t],
|
||||
);
|
||||
|
||||
const applyModel = useCallback(
|
||||
(next, { silent = false } = {}) => {
|
||||
if (!next) return;
|
||||
const from = formRef.current.modelName || '';
|
||||
const r = switchModel(kind, formRef.current, next, {
|
||||
sessionValues: sessionValuesRef.current,
|
||||
});
|
||||
commit(r.form);
|
||||
if (!silent) {
|
||||
notifyAdjustments(next, r.adjustments, r.modeChange);
|
||||
trackCreationEvent('model_switch', {
|
||||
kind,
|
||||
from,
|
||||
to: next.model,
|
||||
migrated_params: (r.adjustments || []).map((a) => a.key),
|
||||
});
|
||||
}
|
||||
},
|
||||
[kind, commit, notifyAdjustments],
|
||||
);
|
||||
|
||||
// schema 加载后:沿用记忆中的模型(仍可调用时)并按最新 schema 静默吸附一次
|
||||
useEffect(() => {
|
||||
if (modelsLoading || models.length === 0) return;
|
||||
const current = models.find((m) => m.model === formRef.current.modelName);
|
||||
if (current && !current.level_locked && schemaAppliedRef.current) return;
|
||||
const target = initialModelOf(models, formRef.current.modelName);
|
||||
if (target) {
|
||||
schemaAppliedRef.current = true;
|
||||
applyModel(target, { silent: true });
|
||||
}
|
||||
}, [models, modelsLoading, applyModel]);
|
||||
|
||||
const selectModel = useCallback(
|
||||
(modelOrName) => {
|
||||
const name = modelNameOf(modelOrName);
|
||||
const next = models.find((m) => m.model === name);
|
||||
if (!next) return false;
|
||||
if (next.level_locked) {
|
||||
showError(t('当前等级无权调用此模型,请选择其他模型'));
|
||||
return false;
|
||||
}
|
||||
if (name === formRef.current.modelName) return true;
|
||||
applyModel(next);
|
||||
return true;
|
||||
},
|
||||
[models, applyModel, t],
|
||||
);
|
||||
|
||||
const setMode = useCallback(
|
||||
(mode) => {
|
||||
if (selectedModel && !adapter.isModeEnabled(selectedModel, mode)) return;
|
||||
commit({ ...formRef.current, mode, preferredMode: mode });
|
||||
},
|
||||
[adapter, selectedModel, commit],
|
||||
);
|
||||
|
||||
const setPrompt = useCallback(
|
||||
(prompt) => commit({ ...formRef.current, prompt: prompt || '' }),
|
||||
[commit],
|
||||
);
|
||||
|
||||
const setParam = useCallback(
|
||||
(key, value) => {
|
||||
sessionValuesRef.current = { ...sessionValuesRef.current, [key]: value };
|
||||
const prev = formRef.current;
|
||||
commit({ ...prev, params: { ...prev.params, [key]: value } });
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 图片槽:COS + 上传开关都开启时先上传按 cos:// 引用提交,否则内联 base64
|
||||
// ---------------------------------------------------------------------------
|
||||
const cosEnabled =
|
||||
status?.experience_center_cos_enabled === true ||
|
||||
(kind === 'video' && creationData.image_input_enabled === true);
|
||||
let fileUploadEnabled = false;
|
||||
let uploadMaxMB = 10;
|
||||
try {
|
||||
fileUploadEnabled = getExperienceCenterBool(
|
||||
status,
|
||||
'experience_center_enable_file_upload',
|
||||
'experience_center_enable_file_upload',
|
||||
false,
|
||||
);
|
||||
uploadMaxMB = getExperienceCenterPositiveInt(
|
||||
status,
|
||||
'experience_center_upload_max_size',
|
||||
'experience_center_upload_max_size',
|
||||
10,
|
||||
);
|
||||
} catch (e) {
|
||||
// localStorage 不可用时按默认值
|
||||
}
|
||||
const uploadByReference = cosEnabled && fileUploadEnabled;
|
||||
const maxFileMB =
|
||||
uploadByReference || kind === 'video' ? uploadMaxMB : INLINE_MAX_MB;
|
||||
|
||||
const patchSlot = useCallback(
|
||||
(id, patch) => {
|
||||
const prev = formRef.current;
|
||||
commit({ ...prev, images: patchImageSlotById(prev.images, id, patch) });
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
const uploadSlotFile = useCallback(
|
||||
async (id, file) => {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
try {
|
||||
const res = await API.post('/api/user/upload/file', fd, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
const data = res?.data?.data;
|
||||
if (!res?.data?.success || !data?.cos_path) {
|
||||
throw new Error(res?.data?.message || t('上传失败'));
|
||||
}
|
||||
fileStoreRef.current.delete(id);
|
||||
const current = allImageSlots(formRef.current.images).find(
|
||||
(s) => s.id === id,
|
||||
);
|
||||
patchSlot(id, {
|
||||
status: 'ready',
|
||||
ref: `cos://${data.cos_path}`,
|
||||
previewUrl: data.url || current?.previewUrl,
|
||||
error: null,
|
||||
});
|
||||
} catch (err) {
|
||||
patchSlot(id, {
|
||||
status: 'error',
|
||||
error: err?.response?.data?.message || err?.message || t('上传失败'),
|
||||
});
|
||||
}
|
||||
},
|
||||
[patchSlot, t],
|
||||
);
|
||||
|
||||
/** 选择 / 拖入 / 粘贴图片放入槽位(参考图 index 缺省为追加)。 */
|
||||
const pickImage = useCallback(
|
||||
async (key, index, file) => {
|
||||
if (!file) return false;
|
||||
if (file.type && !file.type.startsWith('image/')) {
|
||||
showError(t('请上传图片'));
|
||||
return false;
|
||||
}
|
||||
if (maxFileMB > 0 && file.size > maxFileMB * 1024 * 1024) {
|
||||
showError(t('图片不能超过 {{size}}MB', { size: maxFileMB }));
|
||||
return false;
|
||||
}
|
||||
let dataUrl;
|
||||
try {
|
||||
dataUrl = await readAsDataURL(file);
|
||||
} catch (e) {
|
||||
showError(t('读取图片失败,请重新选择'));
|
||||
return false;
|
||||
}
|
||||
const id = newSlotId();
|
||||
const base = {
|
||||
id,
|
||||
name: file.name,
|
||||
previewUrl: dataUrl,
|
||||
identityType: 'aigc',
|
||||
};
|
||||
const slot = uploadByReference
|
||||
? { ...base, status: 'uploading', source: 'upload' }
|
||||
: { ...base, status: 'ready', ref: dataUrl, source: 'inline' };
|
||||
const prev = formRef.current;
|
||||
commit({
|
||||
...prev,
|
||||
images: writeImageSlot(prev.images, key, index, slot),
|
||||
});
|
||||
if (uploadByReference) {
|
||||
fileStoreRef.current.set(id, file);
|
||||
uploadSlotFile(id, file);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[t, maxFileMB, uploadByReference, uploadSlotFile, commit],
|
||||
);
|
||||
|
||||
/** 放入一张可直接引用的图片(task:// / cos:// / 内联),不经上传。 */
|
||||
const setImageRef = useCallback(
|
||||
(key, index, { ref, previewUrl, source = 'task' }) => {
|
||||
if (!ref) return;
|
||||
const prev = formRef.current;
|
||||
commit({
|
||||
...prev,
|
||||
images: writeImageSlot(prev.images, key, index, {
|
||||
id: newSlotId(),
|
||||
status: 'ready',
|
||||
ref,
|
||||
previewUrl: previewUrl || null,
|
||||
source,
|
||||
identityType: 'aigc',
|
||||
}),
|
||||
});
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
const removeImage = useCallback(
|
||||
(key, index) => {
|
||||
const prev = formRef.current;
|
||||
const target =
|
||||
key === 'reference_images'
|
||||
? (prev.images.reference_images || [])[index]
|
||||
: prev.images[key];
|
||||
if (target?.id) fileStoreRef.current.delete(target.id);
|
||||
commit({
|
||||
...prev,
|
||||
images: writeImageSlot(prev.images, key, index, null),
|
||||
});
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
/** 整体替换图片槽(调整顺序 / 首尾帧切回图生等,槽对象原样保留)。 */
|
||||
const setImages = useCallback(
|
||||
(images) => {
|
||||
if (!images) return;
|
||||
commit({ ...formRef.current, images });
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
const retryImage = useCallback(
|
||||
(key, index, slot) => {
|
||||
const file = slot?.id ? fileStoreRef.current.get(slot.id) : null;
|
||||
if (!file) {
|
||||
// 刷新页面后原文件已不在内存中:移除该槽,让用户重新选择
|
||||
removeImage(key, index);
|
||||
return;
|
||||
}
|
||||
patchSlot(slot.id, { status: 'uploading', error: null });
|
||||
uploadSlotFile(slot.id, file);
|
||||
},
|
||||
[removeImage, patchSlot, uploadSlotFile],
|
||||
);
|
||||
|
||||
/**
|
||||
* 外部回填(复用参数 / 再生成)。filled = { modelName, mode, prompt, params, images }。
|
||||
* autoSubmit(再生成):参数原样有效(无模型回退、无吸附、无模式变化)时回填后立即提交,
|
||||
* 否则只回填并提示,由用户确认后再生成。notice:替换默认的"已回填参数"提示。
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const prefill = useCallback(
|
||||
(filled, { autoSubmit = false, notice = '' } = {}) => {
|
||||
const r = applyPrefill(kind, formRef.current, filled, models);
|
||||
if (r.error) {
|
||||
showError(
|
||||
t('原模型 {{model}} 已不可用,请先选择可用模型', {
|
||||
model: r.originalName || '-',
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (r.fallback) {
|
||||
showInfo(
|
||||
t('原模型 {{model}} 已不可用,已保留当前模型', {
|
||||
model: r.originalName,
|
||||
}),
|
||||
);
|
||||
}
|
||||
allImageSlots(formRef.current.images).forEach(
|
||||
(slot) => slot.id && fileStoreRef.current.delete(slot.id),
|
||||
);
|
||||
sessionValuesRef.current = r.sessionValues;
|
||||
schemaAppliedRef.current = true;
|
||||
commit(r.form);
|
||||
const target = models.find((m) => m.model === r.form.modelName);
|
||||
const changed = Boolean(
|
||||
r.fallback || r.adjustments.length || r.modeChange,
|
||||
);
|
||||
if (r.adjustments.length || r.modeChange) {
|
||||
notifyAdjustments(target, r.adjustments, r.modeChange);
|
||||
} else if (!autoSubmit) {
|
||||
showInfo(notice || t('已回填参数'));
|
||||
}
|
||||
if (autoSubmit && !changed) {
|
||||
autoSubmitRef.current = true;
|
||||
} else {
|
||||
if (autoSubmit) showInfo(t('参数已按当前模型调整,请确认后生成'));
|
||||
requestFocus();
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[kind, models, commit, notifyAdjustments, requestFocus, t],
|
||||
);
|
||||
|
||||
/** 清空提示词与图片,参数回到当前模型的记忆 / 默认值(保留模型)。 */
|
||||
const reset = useCallback(() => {
|
||||
const prev = formRef.current;
|
||||
allImageSlots(prev.images).forEach(
|
||||
(slot) => slot.id && fileStoreRef.current.delete(slot.id),
|
||||
);
|
||||
sessionValuesRef.current = {};
|
||||
const cleared = {
|
||||
...prev,
|
||||
prompt: '',
|
||||
preferredMode: '',
|
||||
mode: adapter.defaultMode,
|
||||
images: { first_frame: null, last_frame: null, reference_images: [] },
|
||||
};
|
||||
if (selectedModel) {
|
||||
const { values } = adapter.composeParams(selectedModel, {});
|
||||
cleared.params = values;
|
||||
cleared.mode = adapter.pickMode(selectedModel, adapter.defaultMode, {});
|
||||
}
|
||||
commit(cleared);
|
||||
setAdjustments([]);
|
||||
}, [adapter, selectedModel, commit]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 并发上限、估价、提交
|
||||
// ---------------------------------------------------------------------------
|
||||
const [serverRunning, setServerRunning] = useState(0);
|
||||
const [maxRunningOverride, setMaxRunningOverride] = useState(0);
|
||||
useEffect(() => {
|
||||
setServerRunning(Number(creationData.running_tasks) || 0);
|
||||
}, [creationData.running_tasks]);
|
||||
// 作品流中有任务结束时,以本地统计为准(服务端数字只在加载 / 429 时刷新)
|
||||
const prevLocalRef = useRef(localRunning);
|
||||
useEffect(() => {
|
||||
if (localRunning < prevLocalRef.current) setServerRunning(0);
|
||||
prevLocalRef.current = localRunning;
|
||||
}, [localRunning]);
|
||||
const maxRunning =
|
||||
maxRunningOverride || Number(creationData.max_running_tasks) || 0;
|
||||
const runningCount = Math.max(localRunning, serverRunning);
|
||||
const runningLimitReached = maxRunning > 0 && runningCount >= maxRunning;
|
||||
|
||||
const payload = useMemo(
|
||||
() => buildPayload(kind, selectedModel, form),
|
||||
[kind, selectedModel, form],
|
||||
);
|
||||
const quoteRequest = useMemo(
|
||||
() => buildQuoteRequest(kind, selectedModel, payload),
|
||||
[kind, selectedModel, payload],
|
||||
);
|
||||
const quoteState = useCreationQuote(quoteRequest);
|
||||
const budgetShortfall = useMemo(
|
||||
() => budgetShortfallOf(quoteState.quote),
|
||||
[quoteState.quote],
|
||||
);
|
||||
|
||||
// 埋点:每次拿到新的估价结果记一次 quote_shown
|
||||
useEffect(() => {
|
||||
const q = quoteState.quote;
|
||||
if (!q) return;
|
||||
trackCreationEvent('quote_shown', {
|
||||
kind,
|
||||
model: formRef.current.modelName,
|
||||
approximate: Boolean(q.approximate || q.items?.[0]?.approximate),
|
||||
});
|
||||
}, [kind, quoteState.quote]);
|
||||
|
||||
// 最近一次提交失败(统一错误映射,创作台内联展示 + 下一步动作)
|
||||
const [lastError, setLastError] = useState(null);
|
||||
const clearError = useCallback(() => setLastError(null), []);
|
||||
const clearAdjustments = useCallback(() => setAdjustments([]), []);
|
||||
|
||||
const submitBlock = useMemo(() => {
|
||||
if (modelsLoading) return t('模型列表加载中');
|
||||
if (modelsError && models.length === 0) return t('模型列表加载失败');
|
||||
if (allLocked) return t('当前等级暂无可用模型,升级后即可使用');
|
||||
const reason = formBlockReason(kind, selectedModel, form);
|
||||
if (reason) return t(reason.key);
|
||||
if (runningLimitReached) {
|
||||
return t('已有 {{n}} 个任务进行中,完成后可继续', { n: runningCount });
|
||||
}
|
||||
return '';
|
||||
}, [
|
||||
kind,
|
||||
modelsLoading,
|
||||
modelsError,
|
||||
models.length,
|
||||
allLocked,
|
||||
selectedModel,
|
||||
form,
|
||||
runningLimitReached,
|
||||
runningCount,
|
||||
t,
|
||||
]);
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const submittingRef = useRef(false);
|
||||
const submitFn = useMemo(
|
||||
() => submitter || defaultSubmitter(kind),
|
||||
[submitter, kind],
|
||||
);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (submittingRef.current) return false;
|
||||
if (submitBlock) {
|
||||
showError(submitBlock);
|
||||
return false;
|
||||
}
|
||||
if (!payload) return false;
|
||||
submittingRef.current = true;
|
||||
setSubmitting(true);
|
||||
setLastError(null);
|
||||
try {
|
||||
const result = await submitFn(payload);
|
||||
if (result?.ok) {
|
||||
if (kind === 'video') showInfo(t('视频生成任务已提交,请稍候...'));
|
||||
setAdjustments([]);
|
||||
trackCreationEvent('submit', {
|
||||
kind,
|
||||
model: payload.model,
|
||||
mode: payload.mode || formRef.current.mode,
|
||||
batch_size: Number(payload.n) || 1,
|
||||
});
|
||||
if (onSubmitted) onSubmitted(result, payload);
|
||||
return true;
|
||||
}
|
||||
const running = Number(result?.data?.running_tasks) || 0;
|
||||
if (result?.code === 'too_many_running_tasks') {
|
||||
const max = Number(result.data?.max_running_tasks) || 0;
|
||||
if (running > 0) setServerRunning(running);
|
||||
if (max > 0) setMaxRunningOverride(max);
|
||||
}
|
||||
const info = classifyCreationError(
|
||||
{
|
||||
code: result?.code,
|
||||
message: result?.message,
|
||||
status: result?.status,
|
||||
},
|
||||
{ running },
|
||||
);
|
||||
// 引用的原图已失效:标记可能失效的槽位,用户点槽位即可重新上传
|
||||
if (info.category === 'image_expired') {
|
||||
const marked = markExpiredSlots(formRef.current.images);
|
||||
if (marked.count) commit({ ...formRef.current, images: marked.images });
|
||||
}
|
||||
const text = describeCreationError(t, info);
|
||||
setLastError({ ...info, ...text });
|
||||
showError(text.detail ? `${text.title}:${text.detail}` : text.title);
|
||||
return false;
|
||||
} finally {
|
||||
submittingRef.current = false;
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [submitBlock, payload, submitFn, kind, onSubmitted, commit, t]);
|
||||
|
||||
/**
|
||||
* 套用灵感模板(WP B-7 模板墙 / 模板弹层):推荐模型可用时切换(静默吸附),
|
||||
* 再填入提示词与推荐参数(只套用新模型支持的合法值),最后展开并聚焦创作台。
|
||||
*/
|
||||
const applyTemplate = useCallback(
|
||||
(tpl) => {
|
||||
if (!tpl) return false;
|
||||
const target = templateModelFor(kind, tpl, models, selectedModel);
|
||||
if (target && target.model !== formRef.current.modelName) {
|
||||
applyModel(target, { silent: true });
|
||||
}
|
||||
const values = templateParamsFor(
|
||||
adapter.requestParamsOf(target || selectedModel),
|
||||
tpl.params,
|
||||
);
|
||||
sessionValuesRef.current = { ...sessionValuesRef.current, ...values };
|
||||
const prev = formRef.current;
|
||||
commit({
|
||||
...prev,
|
||||
prompt: tpl.prompt || prev.prompt,
|
||||
params: { ...prev.params, ...values },
|
||||
});
|
||||
setLastError(null);
|
||||
requestFocus();
|
||||
return true;
|
||||
},
|
||||
[kind, models, selectedModel, applyModel, adapter, commit, requestFocus],
|
||||
);
|
||||
|
||||
// 再生成 / 换种子再来:回填已提交到状态后执行一次提交;被阻断(如并发上限)时提示并聚焦创作台。
|
||||
// 多张(n>1)与手动提交同一金额阈值:等当前参数的估价返回,超阈值弹同一二次确认,
|
||||
// 拿不到估价时不自动提交(WP D-1)。
|
||||
const confirmThreshold = status?.experience_center_batch_confirm_threshold;
|
||||
useEffect(() => {
|
||||
if (!autoSubmitRef.current) return;
|
||||
if (submitBlock) {
|
||||
autoSubmitRef.current = false;
|
||||
showError(submitBlock);
|
||||
requestFocus();
|
||||
return;
|
||||
}
|
||||
const n = Number(payload?.n) || 1;
|
||||
const decision = autoSubmitDecision({
|
||||
n,
|
||||
threshold: confirmThreshold,
|
||||
quote: quoteState.quote,
|
||||
quoteFresh: quoteState.fresh && !quoteState.loading,
|
||||
quoteFailed: quoteState.failed,
|
||||
});
|
||||
if (decision === 'wait') return;
|
||||
autoSubmitRef.current = false;
|
||||
if (decision === 'confirm') {
|
||||
openBatchConfirm({
|
||||
t,
|
||||
n,
|
||||
quote: quoteState.quote,
|
||||
onOk: submit,
|
||||
onCancel: requestFocus,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (decision === 'manual') {
|
||||
// 多张但暂时拿不到估价:只回填,由用户看过价格后手动生成
|
||||
showInfo(t('已回填参数'));
|
||||
requestFocus();
|
||||
return;
|
||||
}
|
||||
submit();
|
||||
}, [
|
||||
form,
|
||||
payload,
|
||||
submitBlock,
|
||||
submit,
|
||||
requestFocus,
|
||||
confirmThreshold,
|
||||
quoteState.quote,
|
||||
quoteState.fresh,
|
||||
quoteState.loading,
|
||||
quoteState.failed,
|
||||
t,
|
||||
]);
|
||||
|
||||
const modeOptions = useMemo(
|
||||
() => adapter.modeOptionsOf(selectedModel),
|
||||
[adapter, selectedModel],
|
||||
);
|
||||
const imageSlots = useMemo(
|
||||
() =>
|
||||
selectedModel
|
||||
? adapter.slotsOf(selectedModel, form.mode, form.images)
|
||||
: [],
|
||||
[adapter, selectedModel, form.mode, form.images],
|
||||
);
|
||||
// 只显示适用于当前模式的参数(schema modes),与 buildPayload 的提交口径一致
|
||||
const visibleParams = useMemo(
|
||||
() => visibleParamsOf(kind, selectedModel, form.mode),
|
||||
[kind, selectedModel, form.mode],
|
||||
);
|
||||
|
||||
return {
|
||||
kind,
|
||||
form,
|
||||
// 模型 schema
|
||||
creationData,
|
||||
models,
|
||||
modelsLoading,
|
||||
modelsError,
|
||||
reloadModels,
|
||||
selectedModel,
|
||||
selectModel,
|
||||
// 模式 / 提示词 / 参数
|
||||
mode: form.mode,
|
||||
modeOptions,
|
||||
setMode,
|
||||
prompt: form.prompt,
|
||||
setPrompt,
|
||||
params: form.params,
|
||||
visibleParams,
|
||||
setParam,
|
||||
adjustments,
|
||||
clearAdjustments,
|
||||
applyTemplate,
|
||||
allLocked,
|
||||
// 图片
|
||||
imageSlots,
|
||||
pickImage,
|
||||
setImageRef,
|
||||
removeImage,
|
||||
retryImage,
|
||||
setImages,
|
||||
uploadByReference,
|
||||
cosEnabled,
|
||||
// 估价 / 提交
|
||||
payload,
|
||||
quote: quoteState.quote,
|
||||
quoteLoading: quoteState.loading,
|
||||
quoteFailed: quoteState.failed,
|
||||
// 估价对应当前参数且已返回(不是上一次参数的残留结果)
|
||||
quoteFresh: quoteState.fresh && !quoteState.loading,
|
||||
budgetShortfall,
|
||||
lastError,
|
||||
clearError,
|
||||
estSeconds: selectedModel?.est_seconds?.p50 || 0,
|
||||
submitBlock,
|
||||
submitting,
|
||||
runningCount,
|
||||
maxRunning,
|
||||
submit,
|
||||
// 回填
|
||||
prefill,
|
||||
reset,
|
||||
focusTick,
|
||||
requestFocus,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCreationForm;
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { API } from '../../helpers';
|
||||
|
||||
// 创作能力 schema(GET /api/creation/models?kind=video|image,WP A1-6)。
|
||||
// 按 kind 做模块级缓存:同一会话内多个组件共用一份数据,切换页面回来不重复加载。
|
||||
// 后端自身有 60s 缓存;这里的 TTL 只决定"回到页面时是否静默刷新"。
|
||||
|
||||
const CACHE_TTL_MS = 60 * 1000;
|
||||
const cache = new Map(); // kind → { data, at }
|
||||
const inflight = new Map(); // kind → Promise<data>
|
||||
|
||||
const EMPTY = {
|
||||
models: [],
|
||||
image_input_enabled: false,
|
||||
running_tasks: 0,
|
||||
max_running_tasks: 0,
|
||||
};
|
||||
|
||||
const normalize = (raw) => {
|
||||
const data = raw && typeof raw === 'object' ? raw : {};
|
||||
return {
|
||||
...EMPTY,
|
||||
...data,
|
||||
models: Array.isArray(data.models) ? data.models.filter(Boolean) : [],
|
||||
};
|
||||
};
|
||||
|
||||
const fetchModels = (kind) => {
|
||||
if (inflight.has(kind)) return inflight.get(kind);
|
||||
const promise = API.get('/api/creation/models', {
|
||||
params: { kind },
|
||||
skipErrorHandler: true,
|
||||
})
|
||||
.then((res) => {
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || 'load creation models failed');
|
||||
}
|
||||
const data = normalize(res.data.data);
|
||||
cache.set(kind, { data, at: Date.now() });
|
||||
return data;
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(kind);
|
||||
});
|
||||
inflight.set(kind, promise);
|
||||
return promise;
|
||||
};
|
||||
|
||||
/** 测试 / 管理端修改模型配置后可调用以丢弃缓存。 */
|
||||
export const invalidateCreationModels = (kind) => {
|
||||
if (kind) cache.delete(kind);
|
||||
else cache.clear();
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取创作能力 schema。
|
||||
*
|
||||
* @param {'video'|'image'} kind
|
||||
* @returns {{
|
||||
* data: { models: object[], image_input_enabled: boolean, running_tasks: number, max_running_tasks: number },
|
||||
* models: object[],
|
||||
* loading: boolean, // 首次加载(无缓存数据)中
|
||||
* error: Error|null, // 加载失败且无可用数据
|
||||
* reload: (opts?: { silent?: boolean }) => Promise<void>,
|
||||
* }}
|
||||
*/
|
||||
export const useCreationModels = (kind = 'video') => {
|
||||
const cached = cache.get(kind);
|
||||
const [data, setData] = useState(cached ? cached.data : EMPTY);
|
||||
const [loading, setLoading] = useState(!cached);
|
||||
const [error, setError] = useState(null);
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const reload = useCallback(
|
||||
async ({ silent = false } = {}) => {
|
||||
if (!silent) {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
}
|
||||
try {
|
||||
const next = await fetchModels(kind);
|
||||
if (!mountedRef.current) return;
|
||||
setData(next);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return;
|
||||
// 静默刷新失败时保留已有数据,不打断用户
|
||||
if (!silent) setError(err || new Error('load failed'));
|
||||
} finally {
|
||||
if (mountedRef.current && !silent) setLoading(false);
|
||||
}
|
||||
},
|
||||
[kind],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const hit = cache.get(kind);
|
||||
if (hit) {
|
||||
setData(hit.data);
|
||||
setLoading(false);
|
||||
if (Date.now() - hit.at > CACHE_TTL_MS) reload({ silent: true });
|
||||
return;
|
||||
}
|
||||
reload();
|
||||
}, [kind, reload]);
|
||||
|
||||
return { data, models: data.models, loading, error, reload };
|
||||
};
|
||||
|
||||
export default useCreationModels;
|
||||
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { API } from '../../helpers';
|
||||
|
||||
// 估价(POST /api/creation/quote,WP A1-7)。
|
||||
// - 300ms 防抖,参数变化时中止上一个请求(只采用最新一次结果);
|
||||
// - 估价只做展示,永远不阻止提交:失败 / 超时时 failed=true,由调用方显示"价格以实际扣费为准"。
|
||||
|
||||
const DEBOUNCE_MS = 300;
|
||||
const TIMEOUT_MS = 8000;
|
||||
|
||||
const CURRENCY_SYMBOLS = { CNY: '¥', USD: '$' };
|
||||
|
||||
/** 金额展示:"¥0.5";没有展示金额(自定义展示货币)时返回空串。 */
|
||||
export const formatQuoteAmount = (amount, currency) => {
|
||||
if (amount === undefined || amount === null || amount === '') return '';
|
||||
const symbol = CURRENCY_SYMBOLS[currency];
|
||||
return symbol ? `${symbol}${amount}` : `${amount} ${currency || ''}`.trim();
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {{ kind: 'video'|'image', items: Array<{model:string, mode?:string, params?:object, n?:number}> } | null} request
|
||||
* 为 null 或 items 为空时不估价。
|
||||
* @returns {{ quote: object|null, loading: boolean, failed: boolean, fresh: boolean }}
|
||||
* fresh:quote / failed 对应当前 request(不是上一次参数的残留结果;无估价请求时为 true)
|
||||
* quote = { items[], total, display_amount, currency, approximate, balance_enough, budget_source }
|
||||
*/
|
||||
export const useCreationQuote = (request) => {
|
||||
const key = useMemo(() => {
|
||||
if (!request || !Array.isArray(request.items) || !request.items.length) {
|
||||
return '';
|
||||
}
|
||||
if (request.items.some((item) => !item || !item.model)) return '';
|
||||
try {
|
||||
return JSON.stringify(request);
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}, [request]);
|
||||
|
||||
const [state, setState] = useState({
|
||||
quote: null,
|
||||
loading: false,
|
||||
failed: false,
|
||||
forKey: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) {
|
||||
setState({ quote: null, loading: false, failed: false, forKey: '' });
|
||||
return undefined;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
// superseded:参数已变化 / 组件卸载,本次结果作废(超时中止则按失败处理)
|
||||
let superseded = false;
|
||||
let timeoutId = null;
|
||||
setState((prev) => ({ ...prev, loading: true }));
|
||||
const debounceId = setTimeout(async () => {
|
||||
timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);
|
||||
try {
|
||||
const res = await API.post('/api/creation/quote', JSON.parse(key), {
|
||||
signal: controller.signal,
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (superseded) return;
|
||||
if (!res?.data?.success) throw new Error(res?.data?.message);
|
||||
setState({
|
||||
quote: res.data.data || null,
|
||||
loading: false,
|
||||
failed: false,
|
||||
forKey: key,
|
||||
});
|
||||
} catch (err) {
|
||||
if (superseded) return;
|
||||
setState({ quote: null, loading: false, failed: true, forKey: key });
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}, DEBOUNCE_MS);
|
||||
return () => {
|
||||
superseded = true;
|
||||
clearTimeout(debounceId);
|
||||
clearTimeout(timeoutId);
|
||||
controller.abort();
|
||||
};
|
||||
}, [key]);
|
||||
|
||||
return {
|
||||
quote: state.quote,
|
||||
loading: state.loading,
|
||||
failed: state.failed,
|
||||
fresh: state.forKey === key,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCreationQuote;
|
||||
@@ -0,0 +1,610 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
import {
|
||||
DEFAULT_FILTERS,
|
||||
FAVORITES_SYNCED_KEY,
|
||||
LEGACY_FAVORITES_KEY,
|
||||
LIST_ENDPOINTS,
|
||||
PAGE_SIZE,
|
||||
appendPage,
|
||||
applyUpdates,
|
||||
buildListParams,
|
||||
chunkIds,
|
||||
finishedTransitions,
|
||||
isActiveTask,
|
||||
mergeTask,
|
||||
nextPollDelay,
|
||||
nextPollStep,
|
||||
normalizeTask,
|
||||
optimisticTask,
|
||||
parseLegacyFavorites,
|
||||
pickPollBatch,
|
||||
removeTask,
|
||||
serverFilterKey,
|
||||
taskSignature,
|
||||
upsertTop,
|
||||
} from './creationTasks';
|
||||
import {
|
||||
forgetPending,
|
||||
reportStudioUpdates,
|
||||
watchPending,
|
||||
} from './useCreationWatch';
|
||||
|
||||
const DETAIL_ENDPOINTS = {
|
||||
image: (id) => `/api/images/generations/${encodeURIComponent(id)}`,
|
||||
video: (id) => `/api/video/tasks/${encodeURIComponent(id)}`,
|
||||
};
|
||||
const CANCEL_ENDPOINTS = {
|
||||
image: (id) => `/api/images/generations/${encodeURIComponent(id)}/cancel`,
|
||||
video: (id) => `/api/video/tasks/${encodeURIComponent(id)}/cancel`,
|
||||
};
|
||||
|
||||
const isDocumentHidden = () =>
|
||||
typeof document !== 'undefined' && document.visibilityState === 'hidden';
|
||||
|
||||
const activeIdsIn = (list) => list.filter(isActiveTask).map((task) => task.id);
|
||||
|
||||
const getStorage = () => {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const errorMessageOf = (error, fallback) =>
|
||||
error?.response?.data?.message ||
|
||||
error?.response?.data?.error?.message ||
|
||||
error?.message ||
|
||||
fallback;
|
||||
|
||||
/**
|
||||
* 旧 localStorage 收藏一次性导入服务端(WP B-5 接口)。全部 try/catch,失败下次进入再试。
|
||||
* @returns {Promise<number>} 导入条数
|
||||
*/
|
||||
const syncLegacyFavorites = async () => {
|
||||
const storage = getStorage();
|
||||
if (!storage) return 0;
|
||||
try {
|
||||
if (storage.getItem(FAVORITES_SYNCED_KEY)) return 0;
|
||||
const ids = parseLegacyFavorites(storage.getItem(LEGACY_FAVORITES_KEY));
|
||||
if (ids.length === 0) {
|
||||
storage.setItem(FAVORITES_SYNCED_KEY, '1');
|
||||
return 0;
|
||||
}
|
||||
const res = await API.post(
|
||||
'/api/creation/favorites/sync',
|
||||
{ task_ids: ids },
|
||||
{ skipErrorHandler: true },
|
||||
);
|
||||
if (!res?.data?.success) return 0;
|
||||
storage.setItem(FAVORITES_SYNCED_KEY, '1');
|
||||
return Number(res.data.data?.imported) || 0;
|
||||
} catch (e) {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 作品流任务(WP B-6,方案 §4.5):分页列表 + 筛选 + 乐观插入 + 批量轮询 + 收藏 / 删除 / 取消。
|
||||
*
|
||||
* 轮询:一个定时器用 ids=(≤ 20,超出轮转)查询全部进行中任务,3s → 5s → 10s 退避,
|
||||
* 页面隐藏时降频,回到页面立即刷新。新创作台不再挂载旧的 useImageTaskManagement / useVideoGeneration。
|
||||
*
|
||||
* @param {'image'|'video'} kind
|
||||
*/
|
||||
export const useCreationTasks = (kind) => {
|
||||
const { t } = useTranslation();
|
||||
const endpoint = LIST_ENDPOINTS[kind];
|
||||
|
||||
const [tasks, setTasks] = useState([]);
|
||||
const tasksRef = useRef(tasks);
|
||||
const commit = useCallback((next) => {
|
||||
tasksRef.current = next;
|
||||
setTasks(next);
|
||||
}, []);
|
||||
|
||||
const [filters, setFiltersState] = useState(DEFAULT_FILTERS);
|
||||
const filtersRef = useRef(filters);
|
||||
filtersRef.current = filters;
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [announcement, setAnnouncement] = useState('');
|
||||
|
||||
const pageRef = useRef(0);
|
||||
const listSeqRef = useRef(0);
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ids= 批量查询
|
||||
// ---------------------------------------------------------------------------
|
||||
const fetchByIds = useCallback(
|
||||
async (ids) => {
|
||||
if (!ids.length) return [];
|
||||
const res = await API.get(endpoint, {
|
||||
params: { ids: ids.join(',') },
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || 'query failed');
|
||||
}
|
||||
return (res.data.data?.items || []).map((raw) =>
|
||||
normalizeTask(kind, raw),
|
||||
);
|
||||
},
|
||||
[endpoint, kind],
|
||||
);
|
||||
|
||||
// 视频列表不含播放地址 / 时长:按 ids= 补全成功的作品(每批 ≤ 20)
|
||||
const hydrateVideos = useCallback(
|
||||
async (items) => {
|
||||
if (kind !== 'video') return;
|
||||
const ids = items
|
||||
.filter((task) => task.status === 'success' && !task.hydrated)
|
||||
.map((task) => task.id);
|
||||
for (const batch of chunkIds(ids)) {
|
||||
try {
|
||||
const updates = await fetchByIds(batch);
|
||||
if (!mountedRef.current) return;
|
||||
commit(applyUpdates(tasksRef.current, updates));
|
||||
} catch (e) {
|
||||
// 补全失败不影响列表,打开详情时会再取
|
||||
}
|
||||
}
|
||||
},
|
||||
[kind, fetchByIds, commit],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 分页列表(p= / page_size=)
|
||||
// ---------------------------------------------------------------------------
|
||||
const fetchPage = useCallback(
|
||||
async (page) => {
|
||||
const seq = ++listSeqRef.current;
|
||||
const reset = page === 1;
|
||||
if (reset) setLoading(true);
|
||||
else setLoadingMore(true);
|
||||
try {
|
||||
const res = await API.get(endpoint, {
|
||||
params: buildListParams(filtersRef.current, page),
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (seq !== listSeqRef.current || !mountedRef.current) return;
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || t('加载失败'));
|
||||
}
|
||||
const data = res.data.data || {};
|
||||
const items = (data.items || []).map((raw) => normalizeTask(kind, raw));
|
||||
const totalCount = Number(data.total) || 0;
|
||||
const next = reset
|
||||
? appendPage([], items)
|
||||
: appendPage(tasksRef.current, items);
|
||||
commit(next);
|
||||
pageRef.current = page;
|
||||
setTotal(totalCount);
|
||||
setHasMore(items.length > 0 && page * PAGE_SIZE < totalCount);
|
||||
setError('');
|
||||
hydrateVideos(items);
|
||||
} catch (err) {
|
||||
if (seq !== listSeqRef.current || !mountedRef.current) return;
|
||||
setError(errorMessageOf(err, t('加载失败')));
|
||||
} finally {
|
||||
if (seq === listSeqRef.current && mountedRef.current) {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[endpoint, kind, commit, hydrateVideos, t],
|
||||
);
|
||||
|
||||
const reload = useCallback(() => fetchPage(1), [fetchPage]);
|
||||
|
||||
const loadMore = useCallback(() => {
|
||||
if (loading || loadingMore || !hasMore) return;
|
||||
fetchPage(pageRef.current + 1);
|
||||
}, [loading, loadingMore, hasMore, fetchPage]);
|
||||
|
||||
// 服务端筛选条件变化时从第 1 页重新加载(本地筛选不重新请求)
|
||||
const serverKey = serverFilterKey(filters);
|
||||
useEffect(() => {
|
||||
fetchPage(1);
|
||||
}, [serverKey, fetchPage]);
|
||||
|
||||
const setFilters = useCallback((patch) => {
|
||||
setFiltersState((prev) => ({ ...prev, ...patch }));
|
||||
}, []);
|
||||
const resetFilters = useCallback(() => setFiltersState(DEFAULT_FILTERS), []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 批量轮询
|
||||
// ---------------------------------------------------------------------------
|
||||
const timerRef = useRef(null);
|
||||
const stepRef = useRef(0);
|
||||
const cursorRef = useRef(0);
|
||||
const pollingRef = useRef(false);
|
||||
const pollRef = useRef(null);
|
||||
const signaturesRef = useRef(new Map());
|
||||
|
||||
const schedule = useCallback((delay) => {
|
||||
clearTimeout(timerRef.current);
|
||||
timerRef.current = null;
|
||||
if (!mountedRef.current || activeIdsIn(tasksRef.current).length === 0)
|
||||
return;
|
||||
const wait =
|
||||
delay !== undefined
|
||||
? delay
|
||||
: nextPollDelay(stepRef.current, isDocumentHidden());
|
||||
timerRef.current = setTimeout(() => pollRef.current?.(), wait);
|
||||
}, []);
|
||||
|
||||
const announce = useCallback(
|
||||
(finished) => {
|
||||
if (!finished.length) return;
|
||||
const success = finished.filter((task) => task.status === 'success');
|
||||
const failed = finished.length - success.length;
|
||||
const parts = [];
|
||||
if (success.length) {
|
||||
parts.push(t('{{n}} 个作品已生成', { n: success.length }));
|
||||
}
|
||||
if (failed) parts.push(t('{{n}} 个作品生成失败', { n: failed }));
|
||||
setAnnouncement(parts.join(','));
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
/** 立即查询指定作品并合并(取消后 / 播放地址过期时);返回更新后的作品。 */
|
||||
const refreshByIds = useCallback(
|
||||
async (ids) => {
|
||||
const updates = await fetchByIds(ids);
|
||||
if (!mountedRef.current) return updates;
|
||||
const before = tasksRef.current;
|
||||
announce(finishedTransitions(before, updates));
|
||||
reportStudioUpdates(kind, updates);
|
||||
commit(applyUpdates(before, updates));
|
||||
return updates;
|
||||
},
|
||||
[kind, fetchByIds, announce, commit],
|
||||
);
|
||||
|
||||
const pollOnce = useCallback(async () => {
|
||||
if (pollingRef.current) return;
|
||||
const { batch, cursor } = pickPollBatch(
|
||||
activeIdsIn(tasksRef.current),
|
||||
cursorRef.current,
|
||||
);
|
||||
cursorRef.current = cursor;
|
||||
if (batch.length === 0) return;
|
||||
pollingRef.current = true;
|
||||
let changed = false;
|
||||
try {
|
||||
const updates = await fetchByIds(batch);
|
||||
if (!mountedRef.current) return;
|
||||
const returned = new Set(updates.map((task) => task.id));
|
||||
updates.forEach((task) => {
|
||||
const sig = taskSignature(task);
|
||||
if (signaturesRef.current.get(task.id) !== sig) changed = true;
|
||||
if (isActiveTask(task)) signaturesRef.current.set(task.id, sig);
|
||||
else signaturesRef.current.delete(task.id);
|
||||
});
|
||||
const before = tasksRef.current;
|
||||
let next = applyUpdates(before, updates);
|
||||
// 查询结果中没有的(已在别处删除):从作品流移除,停止轮询
|
||||
const missing = batch.filter((id) => !returned.has(id));
|
||||
missing.forEach((id) => {
|
||||
signaturesRef.current.delete(id);
|
||||
next = removeTask(next, id);
|
||||
});
|
||||
if (missing.length) forgetPending(kind, missing);
|
||||
// 完成提醒:结算登记(用户在本页 = 已读),页面隐藏时按开关发浏览器通知(WP C-4)
|
||||
reportStudioUpdates(kind, updates);
|
||||
announce(finishedTransitions(before, updates));
|
||||
if (next !== before) commit(next);
|
||||
} catch (e) {
|
||||
// 网络错误只记录,不把本地状态伪造为失败;稍后按退避重试
|
||||
} finally {
|
||||
pollingRef.current = false;
|
||||
}
|
||||
if (!mountedRef.current) return;
|
||||
stepRef.current = nextPollStep(stepRef.current, changed);
|
||||
schedule();
|
||||
}, [kind, fetchByIds, announce, commit, schedule]);
|
||||
pollRef.current = pollOnce;
|
||||
|
||||
// 进行中集合出现新任务时重置退避并尽快查询;没有进行中任务时停止
|
||||
const activeKey = useMemo(
|
||||
() =>
|
||||
tasks
|
||||
.filter(isActiveTask)
|
||||
.map((task) => task.id)
|
||||
.join(','),
|
||||
[tasks],
|
||||
);
|
||||
const knownActiveRef = useRef(new Set());
|
||||
useEffect(() => {
|
||||
const ids = activeKey ? activeKey.split(',') : [];
|
||||
if (ids.length === 0) {
|
||||
clearTimeout(timerRef.current);
|
||||
timerRef.current = null;
|
||||
knownActiveRef.current = new Set();
|
||||
return;
|
||||
}
|
||||
const hasNew = ids.some((id) => !knownActiveRef.current.has(id));
|
||||
knownActiveRef.current = new Set(ids);
|
||||
// 登记进行中任务:离开本页后由体验中心的轻量轮询继续跟踪,完成时显示未读角标(WP C-4)
|
||||
if (hasNew) watchPending(kind, ids);
|
||||
if (hasNew) {
|
||||
stepRef.current = 0;
|
||||
schedule();
|
||||
} else if (!timerRef.current && !pollingRef.current) {
|
||||
schedule();
|
||||
}
|
||||
}, [kind, activeKey, schedule]);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
const onVisibility = () => {
|
||||
if (activeIdsIn(tasksRef.current).length === 0) return;
|
||||
if (isDocumentHidden()) {
|
||||
schedule();
|
||||
} else {
|
||||
// 回到页面立即刷新
|
||||
stepRef.current = 0;
|
||||
schedule(0);
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
clearTimeout(timerRef.current);
|
||||
document.removeEventListener('visibilitychange', onVisibility);
|
||||
};
|
||||
}, [schedule]);
|
||||
|
||||
// 旧 localStorage 收藏一次性同步;有导入时刷新列表以带上 favorited
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
syncLegacyFavorites().then((imported) => {
|
||||
if (!cancelled && imported > 0) fetchPage(1);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// 只在挂载时执行一次
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 操作
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 提交成功后乐观插入顶部(useCreationForm onSubmitted(result, payload))。 */
|
||||
const addSubmitted = useCallback(
|
||||
(result, payload) => {
|
||||
const task = optimisticTask(kind, result?.data, payload);
|
||||
if (!task.id) {
|
||||
fetchPage(1);
|
||||
return;
|
||||
}
|
||||
commit(upsertTop(tasksRef.current, task));
|
||||
setTotal((n) => n + 1);
|
||||
},
|
||||
[kind, commit, fetchPage],
|
||||
);
|
||||
|
||||
const patchTask = useCallback(
|
||||
(id, patch) => {
|
||||
commit(
|
||||
tasksRef.current.map((task) =>
|
||||
task.id === id ? { ...task, ...patch } : task,
|
||||
),
|
||||
);
|
||||
},
|
||||
[commit],
|
||||
);
|
||||
|
||||
const toggleFavorite = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return;
|
||||
const next = !task.favorited;
|
||||
patchTask(task.id, { favorited: next });
|
||||
try {
|
||||
const res = next
|
||||
? await API.post(
|
||||
'/api/creation/favorites',
|
||||
{ task_id: task.id },
|
||||
{ skipErrorHandler: true },
|
||||
)
|
||||
: await API.delete(
|
||||
`/api/creation/favorites/${encodeURIComponent(task.id)}`,
|
||||
{ skipErrorHandler: true },
|
||||
);
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || t('操作失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
patchTask(task.id, { favorited: !next });
|
||||
showError(errorMessageOf(err, t('操作失败')));
|
||||
}
|
||||
},
|
||||
[patchTask, t],
|
||||
);
|
||||
|
||||
const deleteTask = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return false;
|
||||
try {
|
||||
const url = DETAIL_ENDPOINTS[kind](task.id);
|
||||
const res = await API.delete(url, { skipErrorHandler: true });
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || t('删除失败'));
|
||||
}
|
||||
commit(removeTask(tasksRef.current, task.id));
|
||||
setTotal((n) => Math.max(0, n - 1));
|
||||
showSuccess(t('任务已删除'));
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(
|
||||
t('删除失败: {{message}}', {
|
||||
message: errorMessageOf(err, t('未知错误')),
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[kind, commit, t],
|
||||
);
|
||||
|
||||
const cancelTask = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return false;
|
||||
try {
|
||||
const res = await API.post(CANCEL_ENDPOINTS[kind](task.id), null, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success) {
|
||||
throw new Error(res?.data?.message || t('取消失败'));
|
||||
}
|
||||
showSuccess(t('任务已取消'));
|
||||
try {
|
||||
await refreshByIds([task.id]);
|
||||
} catch (e) {
|
||||
// 下一次轮询会更新
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(
|
||||
t('取消失败: {{message}}', {
|
||||
message: errorMessageOf(err, t('未知错误')),
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[kind, refreshByIds, t],
|
||||
);
|
||||
|
||||
/** 任务详情(含参数快照 request),合并进作品流;失败返回 null。 */
|
||||
const fetchDetail = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return null;
|
||||
try {
|
||||
const res = await API.get(DETAIL_ENDPOINTS[kind](task.id), {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success || !res.data.data) return null;
|
||||
const detail = normalizeTask(kind, res.data.data);
|
||||
const current = tasksRef.current.find((item) => item.id === task.id);
|
||||
const merged = mergeTask(current || task, detail);
|
||||
if (current) {
|
||||
commit(applyUpdates(tasksRef.current, [merged]));
|
||||
}
|
||||
return merged;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[kind, commit],
|
||||
);
|
||||
|
||||
/**
|
||||
* 刷新图像结果的预签名地址(COS 私有桶过期);无 URL 只有 base64 的首张由后端转存。
|
||||
* @returns {Promise<string>} 新地址,失败为 ''
|
||||
*/
|
||||
const refreshImageUrl = useCallback(
|
||||
async (task, index = 0) => {
|
||||
const image = task?.images?.[index];
|
||||
if (!task?.id || !image) return '';
|
||||
const params = { task_id: task.id, type: 'generated' };
|
||||
if (image.url && !image.url.startsWith('data:')) params.url = image.url;
|
||||
else if (index > 0) return '';
|
||||
try {
|
||||
const res = await API.get('/api/images/refresh-url', {
|
||||
params,
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
const url = res?.data?.success ? res.data.data?.url : '';
|
||||
if (!url) return '';
|
||||
const current =
|
||||
tasksRef.current.find((item) => item.id === task.id) || task;
|
||||
const images = (current.images || []).map((img, i) =>
|
||||
i === index ? { ...img, url, hasB64: false } : img,
|
||||
);
|
||||
patchTask(task.id, { images });
|
||||
return url;
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
},
|
||||
[patchTask],
|
||||
);
|
||||
|
||||
/** 视频播放地址过期:经 ids= 取新的预签名地址。 */
|
||||
const refreshVideoUrl = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return '';
|
||||
try {
|
||||
const updates = await refreshByIds([task.id]);
|
||||
return updates.find((item) => item.id === task.id)?.videoUrl || '';
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
},
|
||||
[refreshByIds],
|
||||
);
|
||||
|
||||
const runningCount = useMemo(
|
||||
() => tasks.filter(isActiveTask).length,
|
||||
[tasks],
|
||||
);
|
||||
|
||||
return {
|
||||
kind,
|
||||
tasks,
|
||||
loading,
|
||||
loadingMore,
|
||||
error,
|
||||
hasMore,
|
||||
total,
|
||||
filters,
|
||||
setFilters,
|
||||
resetFilters,
|
||||
reload,
|
||||
loadMore,
|
||||
runningCount,
|
||||
announcement,
|
||||
addSubmitted,
|
||||
toggleFavorite,
|
||||
deleteTask,
|
||||
cancelTask,
|
||||
fetchDetail,
|
||||
refreshImageUrl,
|
||||
refreshVideoUrl,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCreationTasks;
|
||||
@@ -0,0 +1,345 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { API } from '../../helpers';
|
||||
import i18n from '../../i18n/i18n';
|
||||
import { LIST_ENDPOINTS, chunkIds, normalizeTask } from './creationTasks';
|
||||
import {
|
||||
WATCH_KINDS,
|
||||
WATCH_POLL_MS,
|
||||
WATCH_STORAGE_KEY,
|
||||
dropPending,
|
||||
emptyWatchState,
|
||||
kindsToPoll,
|
||||
markSeen,
|
||||
parseWatchState,
|
||||
pendingIdsOf,
|
||||
pruneWatchState,
|
||||
settleTasks,
|
||||
trackPending,
|
||||
unreadCount,
|
||||
} from './creationWatch';
|
||||
|
||||
// 完成提醒(WP C-4,方案 §4.5):一个模块级小 store(localStorage creation.watch.v1)。
|
||||
// - 创作页提交 / 看到进行中任务时登记 id;创作页自己的 ids= 轮询结果在这里结算(已读);
|
||||
// - 用户在体验中心其他页面时,useCreationWatchPoller 每 30 秒用 ids= 查询一次已登记的任务
|
||||
// (只有存在登记时才查询),完成的计入侧边栏未读角标,并按用户开关发浏览器通知;
|
||||
// - 回到对应创作页即清空未读。
|
||||
// 不引入 Service Worker,浏览器通知要求标签页保持打开。
|
||||
|
||||
const NOTIFY_KEY = 'creation.notify.v1';
|
||||
const NOTIFY_ASKED_KEY = 'creation.notify.asked.v1';
|
||||
|
||||
const listeners = new Set();
|
||||
const activeKinds = new Set();
|
||||
let state = null;
|
||||
let notifyEnabledCache = null;
|
||||
// 每次变化递增(通知开关 / 权限变化不改 state,用版本号驱动订阅者重渲染)
|
||||
let version = 0;
|
||||
|
||||
const getStorage = () => {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const emit = () => {
|
||||
version += 1;
|
||||
listeners.forEach((listener) => listener());
|
||||
};
|
||||
const getVersion = () => version;
|
||||
|
||||
const load = () => {
|
||||
if (state) return state;
|
||||
try {
|
||||
state = pruneWatchState(
|
||||
parseWatchState(getStorage()?.getItem(WATCH_STORAGE_KEY)),
|
||||
Date.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
state = emptyWatchState();
|
||||
}
|
||||
return state;
|
||||
};
|
||||
|
||||
const commit = (next) => {
|
||||
if (!next || next === state) return;
|
||||
state = next;
|
||||
try {
|
||||
getStorage()?.setItem(WATCH_STORAGE_KEY, JSON.stringify(next));
|
||||
} catch (e) {
|
||||
// 存储不可用时只在内存中生效
|
||||
}
|
||||
emit();
|
||||
};
|
||||
|
||||
const subscribe = (listener) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
};
|
||||
|
||||
// 其他标签页更新了状态(同一账号在多个标签页使用)
|
||||
if (typeof window !== 'undefined') {
|
||||
try {
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key === WATCH_STORAGE_KEY) {
|
||||
state = parseWatchState(e.newValue);
|
||||
emit();
|
||||
} else if (e.key === NOTIFY_KEY) {
|
||||
notifyEnabledCache = null;
|
||||
emit();
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 浏览器通知(用户在创作台菜单中开启;首次提交时才请求权限)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const notifySupported = () => {
|
||||
try {
|
||||
return typeof window !== 'undefined' && 'Notification' in window;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const notifyPermission = () =>
|
||||
notifySupported() ? window.Notification.permission : 'unsupported';
|
||||
|
||||
export const getNotifyEnabled = () => {
|
||||
if (notifyEnabledCache === null) {
|
||||
try {
|
||||
notifyEnabledCache = getStorage()?.getItem(NOTIFY_KEY) === '1';
|
||||
} catch (e) {
|
||||
notifyEnabledCache = false;
|
||||
}
|
||||
}
|
||||
return notifyEnabledCache;
|
||||
};
|
||||
|
||||
export const setNotifyEnabled = (enabled) => {
|
||||
notifyEnabledCache = Boolean(enabled);
|
||||
try {
|
||||
const storage = getStorage();
|
||||
if (enabled) {
|
||||
storage?.setItem(NOTIFY_KEY, '1');
|
||||
// 重新开启后,下次提交时可再询问一次(用户之前可能只是关掉了询问框)
|
||||
storage?.removeItem(NOTIFY_ASKED_KEY);
|
||||
} else {
|
||||
storage?.removeItem(NOTIFY_KEY);
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
emit();
|
||||
};
|
||||
|
||||
/** 开启通知后的首次提交:在用户手势内请求权限(只问一次)。 */
|
||||
export const maybeRequestNotifyPermission = () => {
|
||||
if (!getNotifyEnabled() || notifyPermission() !== 'default') return;
|
||||
try {
|
||||
const storage = getStorage();
|
||||
if (storage?.getItem(NOTIFY_ASKED_KEY)) return;
|
||||
storage?.setItem(NOTIFY_ASKED_KEY, '1');
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
const r = window.Notification.requestPermission(() => emit());
|
||||
if (r && typeof r.then === 'function') r.then(emit, () => {});
|
||||
} catch (e) {
|
||||
// 旧浏览器不支持
|
||||
}
|
||||
};
|
||||
|
||||
const isPageHidden = () => {
|
||||
try {
|
||||
return document.visibilityState === 'hidden';
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const notifyFinished = (kind, finished) => {
|
||||
if (!finished || !finished.length) return;
|
||||
if (!getNotifyEnabled() || notifyPermission() !== 'granted') return;
|
||||
// 用户正在看这个创作页时不打扰(作品流与 aria-live 已提示)
|
||||
if (activeKinds.has(kind) && !isPageHidden()) return;
|
||||
const t = (key, opts) => i18n.t(key, opts);
|
||||
const success = finished.filter((task) => task.status === 'success').length;
|
||||
const failed = finished.length - success;
|
||||
const parts = [];
|
||||
if (success) parts.push(t('{{n}} 个作品已生成', { n: success }));
|
||||
if (failed) parts.push(t('{{n}} 个作品生成失败', { n: failed }));
|
||||
try {
|
||||
const notice = new window.Notification(
|
||||
kind === 'video' ? t('视频生成完成') : t('图像生成完成'),
|
||||
{ body: parts.join(','), tag: `creation-${kind}` },
|
||||
);
|
||||
notice.onclick = () => {
|
||||
try {
|
||||
window.focus();
|
||||
notice.close();
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
} catch (e) {
|
||||
// 部分移动端浏览器只允许 Service Worker 通知:忽略
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 创作页接入
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 登记进行中任务(提交成功 / 作品流中出现的进行中任务)。 */
|
||||
export const watchPending = (kind, ids) => {
|
||||
let next = load();
|
||||
(ids || []).forEach((id) => {
|
||||
next = trackPending(next, kind, id, Date.now());
|
||||
});
|
||||
commit(next);
|
||||
};
|
||||
|
||||
/** 创作页自己的轮询结果:结算登记(用户在页面上 = 已读),页面隐藏时按开关发通知。 */
|
||||
export const reportStudioUpdates = (kind, updates) => {
|
||||
const r = settleTasks(load(), kind, updates, {
|
||||
now: Date.now(),
|
||||
seen: true,
|
||||
});
|
||||
commit(r.state);
|
||||
notifyFinished(kind, r.finished);
|
||||
};
|
||||
|
||||
/** 创作页查询不到的任务(已删除):取消登记。 */
|
||||
export const forgetPending = (kind, ids) =>
|
||||
commit(dropPending(load(), kind, ids));
|
||||
|
||||
/** 创作页挂载期间标记为活跃(后台轮询跳过该 kind),进入 / 离开时清空未读。 */
|
||||
export const useStudioWatch = (kind) => {
|
||||
useEffect(() => {
|
||||
activeKinds.add(kind);
|
||||
commit(markSeen(load(), kind, Date.now()));
|
||||
return () => {
|
||||
activeKinds.delete(kind);
|
||||
commit(markSeen(load(), kind, Date.now()));
|
||||
};
|
||||
}, [kind]);
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 体验中心其他页面:轻量轮询 + 角标
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let polling = false;
|
||||
|
||||
const pollOnce = async () => {
|
||||
if (polling) return;
|
||||
const kinds = kindsToPoll(load(), activeKinds, Date.now());
|
||||
if (!kinds.length) return;
|
||||
polling = true;
|
||||
try {
|
||||
for (const kind of kinds) {
|
||||
const ids = pendingIdsOf(load(), kind, Date.now());
|
||||
for (const batch of chunkIds(ids)) {
|
||||
// 期间用户进入了该创作页:交给创作页自己轮询
|
||||
if (activeKinds.has(kind)) break;
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const res = await API.get(LIST_ENDPOINTS[kind], {
|
||||
params: { ids: batch.join(',') },
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!res?.data?.success) continue;
|
||||
const items = (res.data.data?.items || []).map((raw) =>
|
||||
normalizeTask(kind, raw),
|
||||
);
|
||||
const returned = new Set(items.map((task) => task.id));
|
||||
const r = settleTasks(load(), kind, items, {
|
||||
now: Date.now(),
|
||||
seen: activeKinds.has(kind),
|
||||
});
|
||||
commit(
|
||||
dropPending(
|
||||
r.state,
|
||||
kind,
|
||||
batch.filter((id) => !returned.has(id)),
|
||||
),
|
||||
);
|
||||
notifyFinished(kind, r.finished);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 网络错误:下一轮再试
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 体验中心根组件挂载:存在已登记的进行中任务且用户不在对应创作页时,每 30 秒 ids= 查询一次。
|
||||
* @param {boolean} enabled 新创作台开关
|
||||
*/
|
||||
export const useCreationWatchPoller = (enabled) => {
|
||||
const snapshot = useSyncExternalStore(subscribe, load, load);
|
||||
const hasPending = WATCH_KINDS.some(
|
||||
(kind) => pendingIdsOf(snapshot, kind, Date.now()).length > 0,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!enabled || !hasPending) return undefined;
|
||||
const first = setTimeout(pollOnce, 3000);
|
||||
const timer = setInterval(pollOnce, WATCH_POLL_MS);
|
||||
return () => {
|
||||
clearTimeout(first);
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [enabled, hasPending]);
|
||||
};
|
||||
|
||||
/** 侧边栏 / 底部导航角标:{ image, video } 未读数。 */
|
||||
export const useCreationUnread = (enabled = true) => {
|
||||
const snapshot = useSyncExternalStore(subscribe, load, load);
|
||||
return useMemo(
|
||||
() =>
|
||||
enabled
|
||||
? {
|
||||
image: unreadCount(snapshot, 'image'),
|
||||
video: unreadCount(snapshot, 'video'),
|
||||
}
|
||||
: { image: 0, video: 0 },
|
||||
[snapshot, enabled],
|
||||
);
|
||||
};
|
||||
|
||||
/** 创作台菜单中的通知开关状态。 */
|
||||
export const useNotifySetting = () => {
|
||||
useSyncExternalStore(subscribe, getVersion, getVersion);
|
||||
return {
|
||||
supported: notifySupported(),
|
||||
enabled: getNotifyEnabled(),
|
||||
permission: notifyPermission(),
|
||||
};
|
||||
};
|
||||
@@ -64,7 +64,7 @@ export const useDashboardCharts = (
|
||||
title: {
|
||||
visible: true,
|
||||
text: t('模型调用排行'),
|
||||
subtext: `${t('总计')}:${renderNumber(0)}`,
|
||||
subtext: t('总计:{{value}}', { value: renderNumber(0) }),
|
||||
textStyle: {
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
@@ -203,7 +203,7 @@ export const useDashboardCharts = (
|
||||
title: {
|
||||
visible: true,
|
||||
text: t('消费时段走势'),
|
||||
subtext: `${t('总计')}:${renderQuota(0, 2)}`,
|
||||
subtext: t('总计:{{value}}', { value: renderQuota(0, 2) }),
|
||||
textStyle: {
|
||||
fontSize: 14,
|
||||
fontWeight: 600,
|
||||
@@ -809,7 +809,7 @@ export const useDashboardCharts = (
|
||||
updateChartSpec(
|
||||
setSpecPie,
|
||||
newPieData,
|
||||
`${t('总计')}:${renderNumber(totalTimes)}`,
|
||||
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
|
||||
newModelColors,
|
||||
'id0',
|
||||
);
|
||||
@@ -817,7 +817,7 @@ export const useDashboardCharts = (
|
||||
updateChartSpec(
|
||||
setSpecLine,
|
||||
newLineData,
|
||||
`${t('总计')}:${renderQuota(totalQuota, 2)}`,
|
||||
t('总计:{{value}}', { value: renderQuota(totalQuota, 2) }),
|
||||
newModelColors,
|
||||
'barData',
|
||||
);
|
||||
@@ -852,7 +852,7 @@ export const useDashboardCharts = (
|
||||
updateChartSpec(
|
||||
setSpecModelLine,
|
||||
modelLineData,
|
||||
`${t('总计')}:${renderNumber(totalTimes)}`,
|
||||
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
|
||||
newModelColors,
|
||||
'lineData',
|
||||
);
|
||||
@@ -860,7 +860,7 @@ export const useDashboardCharts = (
|
||||
updateChartSpec(
|
||||
setSpecRankBar,
|
||||
rankData,
|
||||
`${t('总计')}:${renderNumber(totalTimes)}`,
|
||||
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
|
||||
newModelColors,
|
||||
'rankData',
|
||||
);
|
||||
|
||||
@@ -187,7 +187,7 @@ export const useDashboardData = (userState, userDispatch, statusState) => {
|
||||
if (data.length === 0) {
|
||||
data.push({
|
||||
count: 0,
|
||||
model_name: '无数据',
|
||||
model_name: t('无数据'),
|
||||
quota: 0,
|
||||
created_at: now.getTime() / 1000,
|
||||
});
|
||||
@@ -201,7 +201,7 @@ export const useDashboardData = (userState, userDispatch, statusState) => {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [inputs, dataExportDefaultTime, isAdminUser, now]);
|
||||
}, [inputs, dataExportDefaultTime, isAdminUser, now, t]);
|
||||
|
||||
const loadTokenUsageData = useCallback(async () => {
|
||||
setTokenUsageLoading(true);
|
||||
|
||||
@@ -0,0 +1,723 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 体验中心图像页(WP A2-3)schema 驱动的纯函数:模式 / 参考图槽 / 参数合成 / 尺寸 / 请求体 / 草稿。
|
||||
// 无 React / i18n 依赖,可直接 node --test。schema 见 service/creation/image.go(GET /api/creation/models?kind=image)。
|
||||
|
||||
import {
|
||||
getDefaultValues,
|
||||
getParamDefault,
|
||||
optionValue,
|
||||
paramsForMode,
|
||||
snapValues,
|
||||
} from '../../components/creation/params/constraints.js';
|
||||
|
||||
export const DRAFT_STORAGE_KEY = 'expCenter.imageGen.draft.v3';
|
||||
const LEGACY_PARAMS_KEY = 'expCenter.imageGen.lastParams.v1';
|
||||
|
||||
/** 新创作台提交标识:后端按 schema 严格校验,并接受 cos:// / task:// 参考图引用。 */
|
||||
export const CREATION_STUDIO_SOURCE = 'creation_studio';
|
||||
|
||||
export const MODE_ORDER = ['text2image', 'edit'];
|
||||
|
||||
/** 模式显示名(i18n key)。 */
|
||||
export const MODE_LABEL_KEYS = {
|
||||
text2image: '文生图',
|
||||
edit: '图生图',
|
||||
};
|
||||
|
||||
/** 图像请求(dto.ImageRequest)认识的 schema 参数;其余参数不渲染也不提交。 */
|
||||
export const REQUEST_PARAM_KEYS = new Set([
|
||||
'size',
|
||||
'n',
|
||||
'quality',
|
||||
'negative_prompt',
|
||||
'seed',
|
||||
'style',
|
||||
'background',
|
||||
'output_format',
|
||||
'watermark',
|
||||
]);
|
||||
|
||||
// 参数控件库没有内置标签的 key(作为 i18n key)
|
||||
const EXTRA_PARAM_LABELS = {
|
||||
background: '背景',
|
||||
output_format: '输出格式',
|
||||
negative_prompt: '负向提示词',
|
||||
};
|
||||
|
||||
// 取值的显示名(i18n key);未列出的取值原样显示
|
||||
const OPTION_LABELS = {
|
||||
quality: {
|
||||
auto: '自动',
|
||||
high: '高',
|
||||
medium: '中',
|
||||
low: '低',
|
||||
hd: '高清',
|
||||
standard: '标准',
|
||||
},
|
||||
background: { auto: '自动', transparent: '透明', opaque: '不透明' },
|
||||
};
|
||||
|
||||
export const DEFAULT_IMAGE_FORM = Object.freeze({
|
||||
mode: 'text2image',
|
||||
// 用户最近一次主动选择的模式:切到不支持的模型再切回时恢复(方案 §4.3)
|
||||
preferredMode: '',
|
||||
prompt: '',
|
||||
modelName: '',
|
||||
params: {},
|
||||
references: [],
|
||||
// 按模型记忆的参数(切换模型时优先级第 2 位)
|
||||
paramMemory: {},
|
||||
});
|
||||
|
||||
export const modelNameOf = (model) => {
|
||||
if (!model) return '';
|
||||
if (typeof model === 'string') return model;
|
||||
return model.model || model.model_name || model.id || '';
|
||||
};
|
||||
|
||||
const decorateParam = (p) => {
|
||||
const labels = OPTION_LABELS[p.key];
|
||||
const out = { ...p };
|
||||
if (!out.label && EXTRA_PARAM_LABELS[p.key]) {
|
||||
out.label = EXTRA_PARAM_LABELS[p.key];
|
||||
}
|
||||
if (labels && Array.isArray(p.options)) {
|
||||
out.options = p.options.map((o) => {
|
||||
if (o && typeof o === 'object') return o;
|
||||
return labels[String(o).toLowerCase()]
|
||||
? { value: o, label: labels[String(o).toLowerCase()] }
|
||||
: o;
|
||||
});
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** schema 中可渲染 / 可提交的参数(补齐控件库缺少的标签与取值显示名)。 */
|
||||
export const requestParamsOf = (model) =>
|
||||
((model && model.params) || [])
|
||||
.filter((p) => p && p.key && REQUEST_PARAM_KEYS.has(p.key))
|
||||
.map(decorateParam);
|
||||
|
||||
/** 当前模式下可渲染 / 可提交的参数(schema 参数的 modes 不含当前模式时隐藏且不提交)。 */
|
||||
export const requestParamsForMode = (model, mode) =>
|
||||
paramsForMode(requestParamsOf(model), mode || 'text2image');
|
||||
|
||||
export const findParam = (model, key) =>
|
||||
requestParamsOf(model).find((p) => p.key === key) || null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 模式与参考图槽
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const isModeEnabled = (model, mode) =>
|
||||
Boolean(model && (model.modes || []).includes(mode));
|
||||
|
||||
/** 模式列表:可用模式 + 因系统配置禁用的模式(带原因),按固定顺序。 */
|
||||
export const modeOptionsOf = (model) => {
|
||||
if (!model) return [];
|
||||
const enabled = new Set(model.modes || []);
|
||||
const disabled = {};
|
||||
(model.disabled_modes || []).forEach((d) => {
|
||||
if (d && d.mode && !enabled.has(d.mode)) disabled[d.mode] = d.reason || '';
|
||||
});
|
||||
const all = new Set([...enabled, ...Object.keys(disabled)]);
|
||||
const order = (m) => {
|
||||
const i = MODE_ORDER.indexOf(m);
|
||||
return i < 0 ? MODE_ORDER.length : i;
|
||||
};
|
||||
return [...all]
|
||||
.sort((a, b) => order(a) - order(b))
|
||||
.map((mode) => ({
|
||||
mode,
|
||||
disabled: !enabled.has(mode),
|
||||
reason: disabled[mode] || '',
|
||||
}));
|
||||
};
|
||||
|
||||
/** 当前模型 × 模式可提交的参考图张数上限(0 = 不使用参考图)。 */
|
||||
export const referenceMaxOf = (model, mode) => {
|
||||
if (!isModeEnabled(model, mode)) return 0;
|
||||
const input = model && model.inputs && model.inputs.reference_images;
|
||||
if (!input || !Array.isArray(input.modes) || !input.modes.includes(mode)) {
|
||||
return 0;
|
||||
}
|
||||
const max = Number(input.max);
|
||||
return Number.isFinite(max) && max > 0 ? Math.floor(max) : 1;
|
||||
};
|
||||
|
||||
/** 模型是否支持图生图(任一模式使用参考图)。 */
|
||||
export const supportsReferences = (model) =>
|
||||
((model && model.modes) || []).some((m) => referenceMaxOf(model, m) > 0);
|
||||
|
||||
const isReady = (slot) =>
|
||||
Boolean(slot && slot.ref && (slot.status || 'ready') === 'ready');
|
||||
|
||||
/**
|
||||
* 面板要渲染的参考图槽。超出当前模型上限 / 当前模式不使用的图片保留并标为 unused
|
||||
* (方案 §4.3:新模型用不到的图片不删除,置灰标注,切回去自动恢复)。
|
||||
*
|
||||
* @returns {Array<{ index: number, label: string, labelIndex: number, slot: object|null, active: boolean }>}
|
||||
*/
|
||||
export const imageSlotsOf = (model, mode, references = []) => {
|
||||
const max = referenceMaxOf(model, mode);
|
||||
const list = (references || []).map((slot, index) => ({
|
||||
index,
|
||||
label: '参考图',
|
||||
labelIndex: index + 1,
|
||||
slot,
|
||||
active: max > 0 && index < max,
|
||||
}));
|
||||
if (max > 0 && list.length < max) {
|
||||
list.push({
|
||||
index: list.length,
|
||||
label: '参考图',
|
||||
labelIndex: list.length + 1,
|
||||
slot: null,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
return list;
|
||||
};
|
||||
|
||||
/** 当前会提交的参考图槽。 */
|
||||
export const activeReferenceSlots = (model, mode, references) =>
|
||||
imageSlotsOf(model, mode, references).filter((s) => s.active && s.slot);
|
||||
|
||||
/** 提交前与图片相关的阻断原因(i18n key),无阻断返回 null。 */
|
||||
export const imageBlockReason = (model, mode, references = []) => {
|
||||
if (!model) return null;
|
||||
if (!isModeEnabled(model, mode)) {
|
||||
return { key: '当前模型不支持该生成模式,请切换模式' };
|
||||
}
|
||||
const slots = activeReferenceSlots(model, mode, references);
|
||||
if (slots.some((s) => s.slot.status === 'uploading')) {
|
||||
return { key: '图片上传中,请稍候' };
|
||||
}
|
||||
if (slots.some((s) => s.slot.status === 'error')) {
|
||||
return { key: '图片上传失败,请重试或移除' };
|
||||
}
|
||||
if (slots.some((s) => s.slot.status === 'expired')) {
|
||||
return { key: '原图已失效,请重新上传' };
|
||||
}
|
||||
if (referenceMaxOf(model, mode) > 0 && !slots.some((s) => isReady(s.slot))) {
|
||||
return { key: '请上传参考图片后才能生成' };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换模型后的模式:想要的模式可用则沿用;否则有参考图且支持编辑 → 编辑;再退回文生图 / 第一个可用模式。
|
||||
*/
|
||||
export const pickModeForModel = (model, mode, references = []) => {
|
||||
if (!model) return mode || 'text2image';
|
||||
if (mode && isModeEnabled(model, mode)) return mode;
|
||||
const modes = model.modes || [];
|
||||
if ((references || []).length && modes.includes('edit')) return 'edit';
|
||||
if (modes.includes('text2image')) return 'text2image';
|
||||
return modes[0] || 'text2image';
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 尺寸(schema type = 'size':预设 + 可选 custom_size {min,max,step})
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** "1024x1024" / "1024×1024" / "1024*1024" → { width, height };无法解析返回 null。 */
|
||||
export const parseSize = (value) => {
|
||||
if (typeof value !== 'string') return null;
|
||||
const m = value.trim().match(/^(\d{1,5})\s*[x×*]\s*(\d{1,5})$/i);
|
||||
if (!m) return null;
|
||||
const width = Number(m[1]);
|
||||
const height = Number(m[2]);
|
||||
if (!width || !height) return null;
|
||||
return { width, height };
|
||||
};
|
||||
|
||||
/** 尺寸预设:[{ value, label, width, height }](兼容后端直接下发字符串)。 */
|
||||
export const sizePresetsOf = (param) =>
|
||||
((param && param.options) || [])
|
||||
.map((o) => {
|
||||
const value = String(optionValue(o) || '');
|
||||
const parsed =
|
||||
o && typeof o === 'object' && o.width && o.height
|
||||
? { width: Number(o.width), height: Number(o.height) }
|
||||
: parseSize(value);
|
||||
if (!value || !parsed) return null;
|
||||
return {
|
||||
value,
|
||||
label: (o && typeof o === 'object' && o.label) || '',
|
||||
width: parsed.width,
|
||||
height: parsed.height,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
/** 自定义尺寸范围;不允许自定义返回 null。 */
|
||||
export const customSizeRangeOf = (param) => {
|
||||
const r = param && param.custom_size;
|
||||
if (!r) return null;
|
||||
const min = Number(r.min);
|
||||
const max = Number(r.max);
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max) || min <= 0 || max < min) {
|
||||
return null;
|
||||
}
|
||||
const step = Number(r.step) > 0 ? Number(r.step) : 1;
|
||||
return { min, max, step };
|
||||
};
|
||||
|
||||
/** 单边吸附到步长并夹到 [min,max]。 */
|
||||
export const clampSizeSide = (n, range) => {
|
||||
const v = Number(n);
|
||||
if (!range) return Number.isFinite(v) ? Math.round(v) : 0;
|
||||
if (!Number.isFinite(v) || v <= 0) return range.min;
|
||||
let snapped = Math.round(v / range.step) * range.step;
|
||||
if (snapped < range.min)
|
||||
snapped = Math.ceil(range.min / range.step) * range.step;
|
||||
if (snapped > range.max)
|
||||
snapped = Math.floor(range.max / range.step) * range.step;
|
||||
// 步长与范围不对齐时退回边界值
|
||||
if (snapped < range.min || snapped > range.max) {
|
||||
snapped = Math.min(range.max, Math.max(range.min, Math.round(v)));
|
||||
}
|
||||
return snapped;
|
||||
};
|
||||
|
||||
const findPreset = (presets, value) => {
|
||||
const key = String(value || '').toLowerCase();
|
||||
return presets.find((p) => p.value.toLowerCase() === key) || null;
|
||||
};
|
||||
|
||||
/** 当前尺寸是否为预设之一。 */
|
||||
export const isPresetSize = (param, value) =>
|
||||
Boolean(findPreset(sizePresetsOf(param), value));
|
||||
|
||||
/**
|
||||
* 将尺寸吸附到合法值:预设命中保持;允许自定义时按范围 / 步长夹取;
|
||||
* 否则取宽高比最接近的预设(比例相同取面积最接近者)。
|
||||
*
|
||||
* @returns {{ value: string|undefined, changed: boolean }}
|
||||
*/
|
||||
export const normalizeSize = (param, value) => {
|
||||
if (!param) return { value: undefined, changed: false };
|
||||
const presets = sizePresetsOf(param);
|
||||
const fallback = () => {
|
||||
const d = getParamDefault(param);
|
||||
const hit = findPreset(presets, d);
|
||||
if (hit) return hit.value;
|
||||
if (typeof d === 'string' && d) return d;
|
||||
return presets[0] ? presets[0].value : undefined;
|
||||
};
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return { value: fallback(), changed: false };
|
||||
}
|
||||
const exact = findPreset(presets, value);
|
||||
if (exact) return { value: exact.value, changed: false };
|
||||
|
||||
const parsed = parseSize(String(value));
|
||||
const range = customSizeRangeOf(param);
|
||||
if (parsed && range) {
|
||||
const w = clampSizeSide(parsed.width, range);
|
||||
const h = clampSizeSide(parsed.height, range);
|
||||
const next = `${w}x${h}`;
|
||||
return {
|
||||
value: next,
|
||||
changed: w !== parsed.width || h !== parsed.height,
|
||||
};
|
||||
}
|
||||
if (parsed && presets.length) {
|
||||
const target = Math.log(parsed.width / parsed.height);
|
||||
const area = parsed.width * parsed.height;
|
||||
let best = presets[0];
|
||||
let bestRatio = Infinity;
|
||||
let bestArea = Infinity;
|
||||
presets.forEach((p) => {
|
||||
const dr = Math.abs(Math.log(p.width / p.height) - target);
|
||||
const da = Math.abs(p.width * p.height - area);
|
||||
if (
|
||||
dr < bestRatio - 1e-9 ||
|
||||
(Math.abs(dr - bestRatio) <= 1e-9 && da < bestArea)
|
||||
) {
|
||||
best = p;
|
||||
bestRatio = dr;
|
||||
bestArea = da;
|
||||
}
|
||||
});
|
||||
return { value: best.value, changed: true };
|
||||
}
|
||||
return { value: fallback(), changed: true };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 参数合成与请求体
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 合成某模型的参数取值(方案 §4.3 优先级):
|
||||
* 1. 本次会话用户手动设置的值(sessionValues);2. 该模型上次使用时记住的值(memory);
|
||||
* 3. schema 默认值。不合法的值吸附到最近的合法值。
|
||||
*
|
||||
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
|
||||
*/
|
||||
export const composeParams = (
|
||||
model,
|
||||
{ sessionValues = {}, memory = {} } = {},
|
||||
) => {
|
||||
const params = requestParamsOf(model);
|
||||
const sizeParam = params.find((p) => p.key === 'size') || null;
|
||||
const others = params.filter((p) => p.key !== 'size');
|
||||
const merged = getDefaultValues(others);
|
||||
params.forEach((p) => {
|
||||
if (memory && memory[p.key] !== undefined) merged[p.key] = memory[p.key];
|
||||
if (sessionValues && sessionValues[p.key] !== undefined) {
|
||||
merged[p.key] = sessionValues[p.key];
|
||||
}
|
||||
});
|
||||
const { values, adjustments } = snapValues(
|
||||
others,
|
||||
merged,
|
||||
(model && model.constraints) || [],
|
||||
);
|
||||
if (sizeParam) {
|
||||
const r = normalizeSize(sizeParam, merged.size);
|
||||
if (r.changed)
|
||||
adjustments.unshift({ key: 'size', from: merged.size, to: r.value });
|
||||
values.size = r.value;
|
||||
}
|
||||
// 只保留 schema 内的键:其它模型的参数不随请求提交
|
||||
const out = {};
|
||||
params.forEach((p) => {
|
||||
if (values[p.key] !== undefined) out[p.key] = values[p.key];
|
||||
});
|
||||
return { values: out, adjustments };
|
||||
};
|
||||
|
||||
/**
|
||||
* 复用参数 / 再生成 / 换种子再来:任务快照对请求参数是权威的。只按快照参数合成,
|
||||
* 快照缺省的可选参数(随机种子、空负向提示词等)取 schema 默认值,不合并此前的会话值
|
||||
* 与按模型记忆(否则上一次"换种子"的固定种子会泄漏到本次请求)。
|
||||
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
|
||||
*/
|
||||
export const composePrefillParams = (model, snapshotParams) =>
|
||||
composeParams(model, {
|
||||
sessionValues: { ...(snapshotParams || {}) },
|
||||
memory: {},
|
||||
});
|
||||
|
||||
const isRandomSeed = (v) =>
|
||||
v === undefined || v === null || v === '' || !Number.isFinite(Number(v));
|
||||
|
||||
/**
|
||||
* 构造 POST /api/images/generations 请求体(source=creation_studio)。
|
||||
* - 参数只取 schema 内、请求认识、且适用于当前模式(modes)的键;未设置的取 schema 默认值;
|
||||
* - 编辑模式按上限提交已就绪的参考图(1 张为字符串,多张为数组);其余模式不带图。
|
||||
*/
|
||||
export const buildImageRequest = (model, form) => {
|
||||
const mode = form.mode || 'text2image';
|
||||
const values = form.params || {};
|
||||
const payload = {
|
||||
model: modelNameOf(model),
|
||||
prompt: form.prompt || '',
|
||||
source: CREATION_STUDIO_SOURCE,
|
||||
};
|
||||
|
||||
requestParamsForMode(model, mode).forEach((p) => {
|
||||
const v = values[p.key] !== undefined ? values[p.key] : getParamDefault(p);
|
||||
switch (p.key) {
|
||||
case 'size': {
|
||||
const r = normalizeSize(p, v);
|
||||
if (r.value) payload.size = r.value;
|
||||
break;
|
||||
}
|
||||
case 'n': {
|
||||
const n = Math.trunc(Number(v));
|
||||
if (Number.isFinite(n) && n >= 1) payload.n = n;
|
||||
break;
|
||||
}
|
||||
case 'seed':
|
||||
if (!isRandomSeed(v)) payload.seed = Math.trunc(Number(v));
|
||||
break;
|
||||
case 'watermark':
|
||||
if (typeof v === 'boolean') payload.watermark = v;
|
||||
break;
|
||||
default:
|
||||
if (typeof v === 'string' && v.trim()) payload[p.key] = v.trim();
|
||||
}
|
||||
});
|
||||
|
||||
const max = referenceMaxOf(model, mode);
|
||||
if (max > 0) {
|
||||
const refs = (form.references || [])
|
||||
.slice(0, max)
|
||||
.filter(isReady)
|
||||
.map((s) => s.ref);
|
||||
if (refs.length === 1) payload.image = refs[0];
|
||||
else if (refs.length > 1) payload.image = refs;
|
||||
}
|
||||
return payload;
|
||||
};
|
||||
|
||||
/** 估价请求(kind=image:只带定价相关参数,张数单独传)。 */
|
||||
export const quoteRequestOf = (model, payload) => {
|
||||
if (!model || !payload) return null;
|
||||
const params = {};
|
||||
if (payload.size) params.size = payload.size;
|
||||
if (payload.quality) params.quality = payload.quality;
|
||||
return {
|
||||
kind: 'image',
|
||||
items: [
|
||||
{
|
||||
model: modelNameOf(model),
|
||||
mode: payload.image ? 'edit' : 'text2image',
|
||||
params,
|
||||
n: payload.n || 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 复用参数 / 再生成:任务详情 request(ExperienceImageRequestDTO)或旧任务数据 → 表单
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const nonEmptyString = (v) => typeof v === 'string' && v.trim() !== '';
|
||||
const isDisplayableURL = (v) => /^(https?:|data:|blob:)/i.test(String(v || ''));
|
||||
|
||||
const refSlot = (ref, display, id) => {
|
||||
const value = typeof ref === 'string' ? ref.trim() : '';
|
||||
if (!value) return null;
|
||||
const preview = isDisplayableURL(display)
|
||||
? display
|
||||
: isDisplayableURL(value)
|
||||
? value
|
||||
: null;
|
||||
return {
|
||||
id,
|
||||
status: 'ready',
|
||||
ref: value,
|
||||
previewUrl: preview,
|
||||
source: value.startsWith('data:') ? 'inline' : 'task',
|
||||
};
|
||||
};
|
||||
|
||||
const makeIdFactory = (newId) => {
|
||||
let seq = 0;
|
||||
return newId || (() => `ref-task-${Date.now().toString(36)}-${seq++}`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 任务详情 request → 表单回填值(未按 schema 吸附,调用方再走 composeParams)。
|
||||
* reference_image_refs[i] 为可再提交的引用(空串 = 原图已失效),reference_images[i] 为展示地址。
|
||||
*
|
||||
* @returns {{ modelName, mode, prompt, params, references, missingReferences }}
|
||||
*/
|
||||
export const formFromImageRequest = (request, { newId } = {}) => {
|
||||
const req = request || {};
|
||||
const makeId = makeIdFactory(newId);
|
||||
const params = {};
|
||||
if (nonEmptyString(req.size)) params.size = req.size.trim();
|
||||
if (nonEmptyString(req.quality)) params.quality = req.quality;
|
||||
if (Number(req.n) > 0) params.n = Number(req.n);
|
||||
if (typeof req.seed === 'number' && Number.isFinite(req.seed)) {
|
||||
params.seed = req.seed;
|
||||
}
|
||||
['negative_prompt', 'style', 'background', 'output_format'].forEach((k) => {
|
||||
if (nonEmptyString(req[k])) params[k] = req[k];
|
||||
});
|
||||
if (typeof req.watermark === 'boolean') params.watermark = req.watermark;
|
||||
|
||||
const refs = Array.isArray(req.reference_image_refs)
|
||||
? req.reference_image_refs
|
||||
: [];
|
||||
const displays = Array.isArray(req.reference_images)
|
||||
? req.reference_images
|
||||
: [];
|
||||
const references = [];
|
||||
let missingReferences = 0;
|
||||
refs.forEach((ref, i) => {
|
||||
const slot = refSlot(ref, displays[i], makeId());
|
||||
if (slot) references.push(slot);
|
||||
else missingReferences += 1;
|
||||
});
|
||||
const mode = MODE_ORDER.includes(req.mode)
|
||||
? req.mode
|
||||
: references.length || missingReferences
|
||||
? 'edit'
|
||||
: 'text2image';
|
||||
if (mode === 'edit' && refs.length === 0) missingReferences += 1;
|
||||
|
||||
return {
|
||||
modelName: typeof req.model === 'string' ? req.model : '',
|
||||
mode,
|
||||
prompt: typeof req.prompt === 'string' ? req.prompt : '',
|
||||
params,
|
||||
references,
|
||||
missingReferences,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 旧任务(无参数快照)→ 表单回填值。task 为 useImageTaskManagement 转换后的任务。
|
||||
* 旧任务的原图只有内联 base64 时可直接复用;COS / 上游地址无法按 creation_studio 提交,记为失效。
|
||||
*/
|
||||
export const formFromLegacyTask = (task, { newId } = {}) => {
|
||||
const tk = task || {};
|
||||
const data = tk.taskData || {};
|
||||
const makeId = makeIdFactory(newId);
|
||||
const params = {};
|
||||
const size =
|
||||
(nonEmptyString(data.size) && data.size.trim()) ||
|
||||
(tk.width && tk.height ? `${tk.width}x${tk.height}` : '');
|
||||
if (size) params.size = size;
|
||||
if (nonEmptyString(tk.quality)) params.quality = tk.quality;
|
||||
if (Number(tk.n) > 0) params.n = Number(tk.n);
|
||||
if (nonEmptyString(tk.negativePrompt)) {
|
||||
params.negative_prompt = tk.negativePrompt;
|
||||
}
|
||||
const isEdit = tk.mode === 'image-to-image' || tk.mode === 'edit';
|
||||
const references = [];
|
||||
let missingReferences = 0;
|
||||
if (isEdit) {
|
||||
const src = String(tk.sourceImageUrl || '');
|
||||
if (src.startsWith('data:')) references.push(refSlot(src, src, makeId()));
|
||||
else missingReferences = 1;
|
||||
}
|
||||
return {
|
||||
modelName: tk.model && tk.model !== 'unknown' ? tk.model : '',
|
||||
mode: isEdit ? 'edit' : 'text2image',
|
||||
prompt: tk.prompt || '',
|
||||
params,
|
||||
references,
|
||||
missingReferences,
|
||||
};
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 草稿(localStorage v3,读写全部 try/catch)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PERSISTABLE_SLOT_FIELDS = ['id', 'ref', 'previewUrl', 'name', 'source'];
|
||||
|
||||
const persistSlot = (slot, keepInline) => {
|
||||
if (!isReady(slot)) return null;
|
||||
if (!keepInline && String(slot.ref).startsWith('data:')) return null;
|
||||
const out = { status: 'ready' };
|
||||
PERSISTABLE_SLOT_FIELDS.forEach((k) => {
|
||||
if (slot[k] !== undefined && slot[k] !== null) out[k] = slot[k];
|
||||
});
|
||||
// 内联预览(内联图片的预览就是 ref 本身;上传图片的本地预览体积大)不重复存
|
||||
if (String(out.previewUrl || '').startsWith('data:')) delete out.previewUrl;
|
||||
return out;
|
||||
};
|
||||
|
||||
export const serializeDraft = (form, { keepInline = true } = {}) =>
|
||||
JSON.stringify({
|
||||
mode: form.mode,
|
||||
preferredMode: form.preferredMode || '',
|
||||
prompt: form.prompt || '',
|
||||
modelName: form.modelName || '',
|
||||
params: form.params || {},
|
||||
paramMemory: form.paramMemory || {},
|
||||
references: (form.references || [])
|
||||
.map((s) => persistSlot(s, keepInline))
|
||||
.filter(Boolean),
|
||||
});
|
||||
|
||||
const restoreSlot = (slot) => {
|
||||
if (!slot || typeof slot !== 'object' || typeof slot.ref !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const out = { ...slot, status: 'ready' };
|
||||
if (!out.previewUrl && out.ref.startsWith('data:')) out.previewUrl = out.ref;
|
||||
if (!out.id) out.id = `ref-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return out;
|
||||
};
|
||||
|
||||
const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
export const parseDraft = (raw) => {
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw);
|
||||
if (!isPlainObject(data)) return null;
|
||||
return {
|
||||
...DEFAULT_IMAGE_FORM,
|
||||
mode: MODE_ORDER.includes(data.mode) ? data.mode : 'text2image',
|
||||
preferredMode: MODE_ORDER.includes(data.preferredMode)
|
||||
? data.preferredMode
|
||||
: '',
|
||||
prompt: typeof data.prompt === 'string' ? data.prompt : '',
|
||||
modelName: typeof data.modelName === 'string' ? data.modelName : '',
|
||||
params: isPlainObject(data.params) ? data.params : {},
|
||||
paramMemory: isPlainObject(data.paramMemory) ? data.paramMemory : {},
|
||||
references: Array.isArray(data.references)
|
||||
? data.references.map(restoreSlot).filter(Boolean)
|
||||
: [],
|
||||
};
|
||||
};
|
||||
|
||||
/** 读取草稿;v3 不存在时从 v1(上次提交的参数)迁移模型与参数,按 schema 吸附后生效。 */
|
||||
export const loadDraft = (storage) => {
|
||||
if (!storage) return { ...DEFAULT_IMAGE_FORM };
|
||||
try {
|
||||
const v3 = parseDraft(storage.getItem(DRAFT_STORAGE_KEY));
|
||||
if (v3) return v3;
|
||||
} catch (e) {
|
||||
// 草稿损坏时忽略
|
||||
}
|
||||
try {
|
||||
const raw = storage.getItem(LEGACY_PARAMS_KEY);
|
||||
const v1 = raw ? JSON.parse(raw) : null;
|
||||
if (isPlainObject(v1)) {
|
||||
const params = {};
|
||||
if (nonEmptyString(v1.size)) params.size = v1.size;
|
||||
if (nonEmptyString(v1.quality)) params.quality = v1.quality;
|
||||
if (Number(v1.n) > 0) params.n = Number(v1.n);
|
||||
if (nonEmptyString(v1.negativePrompt)) {
|
||||
params.negative_prompt = v1.negativePrompt;
|
||||
}
|
||||
return {
|
||||
...DEFAULT_IMAGE_FORM,
|
||||
modelName: typeof v1.modelName === 'string' ? v1.modelName : '',
|
||||
params,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
return { ...DEFAULT_IMAGE_FORM };
|
||||
};
|
||||
|
||||
/** 保存草稿;配额不足时退而不存内联 base64 图片,仍失败则放弃。 */
|
||||
export const saveDraft = (storage, form) => {
|
||||
if (!storage) return false;
|
||||
try {
|
||||
storage.setItem(DRAFT_STORAGE_KEY, serializeDraft(form));
|
||||
return true;
|
||||
} catch (e) {
|
||||
try {
|
||||
storage.setItem(
|
||||
DRAFT_STORAGE_KEY,
|
||||
serializeDraft(form, { keepInline: false }),
|
||||
);
|
||||
return true;
|
||||
} catch (e2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,403 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
DRAFT_STORAGE_KEY,
|
||||
buildImageRequest,
|
||||
clampSizeSide,
|
||||
composeParams,
|
||||
formFromImageRequest,
|
||||
formFromLegacyTask,
|
||||
imageBlockReason,
|
||||
imageSlotsOf,
|
||||
loadDraft,
|
||||
modeOptionsOf,
|
||||
normalizeSize,
|
||||
pickModeForModel,
|
||||
quoteRequestOf,
|
||||
referenceMaxOf,
|
||||
requestParamsOf,
|
||||
saveDraft,
|
||||
} from './imageCreation.js';
|
||||
|
||||
const sizeOpt = (w, h, label) => ({
|
||||
value: `${w}x${h}`,
|
||||
label,
|
||||
width: w,
|
||||
height: h,
|
||||
});
|
||||
|
||||
// 允许自定义尺寸、可编辑(最多 3 张参考图)的模型
|
||||
const gemini = {
|
||||
model: 'gemini-image',
|
||||
modes: ['text2image', 'edit'],
|
||||
params: [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: [sizeOpt(1024, 1024, '1:1'), sizeOpt(1280, 720, '16:9')],
|
||||
default: '1024x1024',
|
||||
custom_size: { min: 256, max: 2048, step: 64 },
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'n',
|
||||
type: 'segmented',
|
||||
options: [1, 2, 3, 4],
|
||||
default: 1,
|
||||
placement: 'dock',
|
||||
},
|
||||
{ key: 'seed', type: 'seed', placement: 'advanced' },
|
||||
{ key: 'response_format', type: 'select', options: ['url'] },
|
||||
],
|
||||
inputs: { reference_images: { label: '参考图', modes: ['edit'], max: 3 } },
|
||||
};
|
||||
|
||||
// 只接受固定尺寸、只能文生图的模型
|
||||
const gptImage = {
|
||||
model: 'gpt-image-1',
|
||||
modes: ['text2image'],
|
||||
params: [
|
||||
{
|
||||
key: 'size',
|
||||
type: 'size',
|
||||
options: [
|
||||
sizeOpt(1024, 1024, '1:1'),
|
||||
sizeOpt(1536, 1024, '3:2'),
|
||||
sizeOpt(1024, 1536, '2:3'),
|
||||
],
|
||||
default: '1024x1024',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'quality',
|
||||
type: 'chips',
|
||||
options: ['auto', 'high', 'low'],
|
||||
default: 'auto',
|
||||
placement: 'dock',
|
||||
},
|
||||
{ key: 'watermark', type: 'switch', default: false, placement: 'advanced' },
|
||||
],
|
||||
inputs: {},
|
||||
};
|
||||
|
||||
const ready = (ref, extra = {}) => ({
|
||||
id: ref,
|
||||
status: 'ready',
|
||||
ref,
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('requestParamsOf 过滤请求不认识的参数并补齐取值显示名', () => {
|
||||
const keys = requestParamsOf(gemini).map((p) => p.key);
|
||||
assert.deepEqual(keys, ['size', 'n', 'seed']);
|
||||
const quality = requestParamsOf(gptImage).find((p) => p.key === 'quality');
|
||||
assert.deepEqual(quality.options[0], { value: 'auto', label: '自动' });
|
||||
});
|
||||
|
||||
test('modeOptionsOf / referenceMaxOf', () => {
|
||||
assert.deepEqual(
|
||||
modeOptionsOf(gemini).map((o) => o.mode),
|
||||
['text2image', 'edit'],
|
||||
);
|
||||
assert.equal(referenceMaxOf(gemini, 'edit'), 3);
|
||||
assert.equal(referenceMaxOf(gemini, 'text2image'), 0);
|
||||
assert.equal(referenceMaxOf(gptImage, 'edit'), 0);
|
||||
});
|
||||
|
||||
test('clampSizeSide 按步长吸附并夹到范围', () => {
|
||||
const r = { min: 256, max: 2048, step: 64 };
|
||||
assert.equal(clampSizeSide(1000, r), 1024);
|
||||
assert.equal(clampSizeSide(10, r), 256);
|
||||
assert.equal(clampSizeSide(5000, r), 2048);
|
||||
assert.equal(clampSizeSide('abc', r), 256);
|
||||
});
|
||||
|
||||
test('normalizeSize:预设 / 自定义 / 最近比例', () => {
|
||||
const g = gemini.params[0];
|
||||
assert.deepEqual(normalizeSize(g, '1280X720'), {
|
||||
value: '1280x720',
|
||||
changed: false,
|
||||
});
|
||||
assert.deepEqual(normalizeSize(g, '1000x3000'), {
|
||||
value: '1024x2048',
|
||||
changed: true,
|
||||
});
|
||||
assert.deepEqual(normalizeSize(g, undefined), {
|
||||
value: '1024x1024',
|
||||
changed: false,
|
||||
});
|
||||
const p = gptImage.params[0];
|
||||
// 不允许自定义:16:9 吸附到最接近的横版 3:2
|
||||
assert.deepEqual(normalizeSize(p, '1280x720'), {
|
||||
value: '1536x1024',
|
||||
changed: true,
|
||||
});
|
||||
assert.deepEqual(normalizeSize(p, 'bogus'), {
|
||||
value: '1024x1024',
|
||||
changed: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('composeParams:会话值 > 记忆 > 默认,非法值吸附并给出调整项', () => {
|
||||
const { values, adjustments } = composeParams(gptImage, {
|
||||
sessionValues: { size: '1280x720', n: 4, quality: 'medium' },
|
||||
memory: { watermark: true },
|
||||
});
|
||||
assert.deepEqual(values, {
|
||||
size: '1536x1024',
|
||||
quality: 'auto',
|
||||
watermark: true,
|
||||
});
|
||||
assert.deepEqual(
|
||||
adjustments.map((a) => a.key),
|
||||
['size', 'quality'],
|
||||
);
|
||||
const g = composeParams(gemini, { sessionValues: { n: 9 } });
|
||||
assert.equal(g.values.n, 4);
|
||||
assert.equal(g.values.size, '1024x1024');
|
||||
});
|
||||
|
||||
test('imageSlotsOf:超出上限 / 当前模式不使用的参考图置灰保留', () => {
|
||||
const refs = [ready('a'), ready('b'), ready('c'), ready('d')];
|
||||
const slots = imageSlotsOf(gemini, 'edit', refs);
|
||||
assert.deepEqual(
|
||||
slots.map((s) => s.active),
|
||||
[true, true, true, false],
|
||||
);
|
||||
const one = imageSlotsOf(gemini, 'edit', [ready('a')]);
|
||||
assert.equal(one.length, 2);
|
||||
assert.equal(one[1].slot, null);
|
||||
const t2i = imageSlotsOf(gptImage, 'text2image', [ready('a')]);
|
||||
assert.deepEqual(
|
||||
t2i.map((s) => s.active),
|
||||
[false],
|
||||
);
|
||||
});
|
||||
|
||||
test('imageBlockReason', () => {
|
||||
assert.equal(
|
||||
imageBlockReason(gemini, 'edit', []).key,
|
||||
'请上传参考图片后才能生成',
|
||||
);
|
||||
assert.equal(
|
||||
imageBlockReason(gemini, 'edit', [{ id: 'x', status: 'uploading' }]).key,
|
||||
'图片上传中,请稍候',
|
||||
);
|
||||
assert.equal(imageBlockReason(gemini, 'edit', [ready('a')]), null);
|
||||
assert.equal(
|
||||
imageBlockReason(gptImage, 'edit', []).key,
|
||||
'当前模型不支持该生成模式,请切换模式',
|
||||
);
|
||||
assert.equal(imageBlockReason(gptImage, 'text2image', [ready('a')]), null);
|
||||
});
|
||||
|
||||
test('pickModeForModel', () => {
|
||||
assert.equal(pickModeForModel(gptImage, 'edit', [ready('a')]), 'text2image');
|
||||
assert.equal(pickModeForModel(gemini, 'edit', []), 'edit');
|
||||
assert.equal(pickModeForModel(gemini, '', [ready('a')]), 'edit');
|
||||
});
|
||||
|
||||
test('buildImageRequest:文生图只带 schema 参数 + source', () => {
|
||||
const payload = buildImageRequest(gptImage, {
|
||||
mode: 'text2image',
|
||||
prompt: 'cat',
|
||||
params: { size: '1024x1536', quality: 'high', n: 3, negative_prompt: 'x' },
|
||||
references: [ready('task://1')],
|
||||
});
|
||||
assert.deepEqual(payload, {
|
||||
model: 'gpt-image-1',
|
||||
prompt: 'cat',
|
||||
source: 'creation_studio',
|
||||
size: '1024x1536',
|
||||
quality: 'high',
|
||||
watermark: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('buildImageRequest:编辑模式按上限提交参考图,单张为字符串', () => {
|
||||
const base = {
|
||||
mode: 'edit',
|
||||
prompt: 'p',
|
||||
params: { size: '700x700', n: 2, seed: '42' },
|
||||
};
|
||||
const single = buildImageRequest(gemini, {
|
||||
...base,
|
||||
references: [ready('cos://playground/1/a.png')],
|
||||
});
|
||||
assert.equal(single.image, 'cos://playground/1/a.png');
|
||||
assert.equal(single.size, '704x704');
|
||||
assert.equal(single.n, 2);
|
||||
assert.equal(single.seed, 42);
|
||||
|
||||
const multi = buildImageRequest(gemini, {
|
||||
...base,
|
||||
params: {},
|
||||
references: [
|
||||
ready('task://t1'),
|
||||
{ id: 'u', status: 'uploading' },
|
||||
ready('data:image/png;base64,AAA'),
|
||||
ready('task://t4'),
|
||||
],
|
||||
});
|
||||
assert.deepEqual(multi.image, ['task://t1', 'data:image/png;base64,AAA']);
|
||||
assert.equal(multi.n, 1);
|
||||
assert.equal(multi.seed, undefined);
|
||||
});
|
||||
|
||||
test('quoteRequestOf', () => {
|
||||
const payload = buildImageRequest(gemini, {
|
||||
mode: 'edit',
|
||||
prompt: 'p',
|
||||
params: { n: 3 },
|
||||
references: [ready('task://t1')],
|
||||
});
|
||||
assert.deepEqual(quoteRequestOf(gemini, payload), {
|
||||
kind: 'image',
|
||||
items: [
|
||||
{
|
||||
model: 'gemini-image',
|
||||
mode: 'edit',
|
||||
params: { size: '1024x1024' },
|
||||
n: 3,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('formFromImageRequest:快照回填,失效参考图计数', () => {
|
||||
const filled = formFromImageRequest(
|
||||
{
|
||||
model: 'gemini-image',
|
||||
mode: 'edit',
|
||||
prompt: 'hello',
|
||||
size: '1280x720',
|
||||
n: 2,
|
||||
seed: 7,
|
||||
negative_prompt: 'blur',
|
||||
watermark: false,
|
||||
reference_images: ['https://cos/a.png', ''],
|
||||
reference_image_refs: ['task://abc#ref0', ''],
|
||||
},
|
||||
{ newId: () => 'id' },
|
||||
);
|
||||
assert.equal(filled.mode, 'edit');
|
||||
assert.deepEqual(filled.params, {
|
||||
size: '1280x720',
|
||||
n: 2,
|
||||
seed: 7,
|
||||
negative_prompt: 'blur',
|
||||
watermark: false,
|
||||
});
|
||||
assert.equal(filled.references.length, 1);
|
||||
assert.equal(filled.references[0].ref, 'task://abc#ref0');
|
||||
assert.equal(filled.references[0].previewUrl, 'https://cos/a.png');
|
||||
assert.equal(filled.missingReferences, 1);
|
||||
});
|
||||
|
||||
test('formFromLegacyTask:旧任务只复用内联原图', () => {
|
||||
const legacy = formFromLegacyTask({
|
||||
model: 'wanx-v1',
|
||||
mode: 'image-to-image',
|
||||
prompt: 'p',
|
||||
width: 1280,
|
||||
height: 720,
|
||||
n: 2,
|
||||
negativePrompt: 'neg',
|
||||
sourceImageUrl: 'https://cos/src.png',
|
||||
taskData: { size: '1280x720' },
|
||||
});
|
||||
assert.equal(legacy.mode, 'edit');
|
||||
assert.deepEqual(legacy.params, {
|
||||
size: '1280x720',
|
||||
n: 2,
|
||||
negative_prompt: 'neg',
|
||||
});
|
||||
assert.equal(legacy.references.length, 0);
|
||||
assert.equal(legacy.missingReferences, 1);
|
||||
});
|
||||
|
||||
const memoryStorage = (initial = {}) => {
|
||||
const data = { ...initial };
|
||||
return {
|
||||
data,
|
||||
getItem: (k) => (k in data ? data[k] : null),
|
||||
setItem: (k, v) => {
|
||||
data[k] = String(v);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
test('草稿:v3 读写往返,v1 迁移模型与参数', () => {
|
||||
const storage = memoryStorage();
|
||||
const form = {
|
||||
mode: 'edit',
|
||||
preferredMode: 'edit',
|
||||
prompt: 'p',
|
||||
modelName: 'gemini-image',
|
||||
params: { size: '1024x1024' },
|
||||
paramMemory: {},
|
||||
references: [
|
||||
ready('task://t1', { previewUrl: 'https://x/a.png', source: 'task' }),
|
||||
{ id: 'u', status: 'uploading' },
|
||||
],
|
||||
};
|
||||
assert.equal(saveDraft(storage, form), true);
|
||||
const back = loadDraft(storage);
|
||||
assert.equal(back.modelName, 'gemini-image');
|
||||
assert.equal(back.references.length, 1);
|
||||
assert.equal(back.references[0].previewUrl, 'https://x/a.png');
|
||||
|
||||
const legacy = memoryStorage({
|
||||
'expCenter.imageGen.lastParams.v1': JSON.stringify({
|
||||
mode: 'text-to-image',
|
||||
modelName: 'gpt-image-1',
|
||||
size: '1024x1536',
|
||||
quality: 'high',
|
||||
n: 1,
|
||||
}),
|
||||
});
|
||||
const migrated = loadDraft(legacy);
|
||||
assert.equal(migrated.modelName, 'gpt-image-1');
|
||||
assert.deepEqual(migrated.params, {
|
||||
size: '1024x1536',
|
||||
quality: 'high',
|
||||
n: 1,
|
||||
});
|
||||
assert.equal(DRAFT_STORAGE_KEY in legacy.data, false);
|
||||
});
|
||||
|
||||
test('草稿:配额不足时不存内联图片', () => {
|
||||
let calls = 0;
|
||||
const storage = {
|
||||
getItem: () => null,
|
||||
setItem: (k, v) => {
|
||||
calls += 1;
|
||||
if (String(v).includes('data:')) throw new Error('quota');
|
||||
},
|
||||
};
|
||||
const ok = saveDraft(storage, {
|
||||
mode: 'edit',
|
||||
references: [ready('data:image/png;base64,AAA')],
|
||||
});
|
||||
assert.equal(ok, true);
|
||||
assert.equal(calls, 2);
|
||||
});
|
||||
@@ -0,0 +1,802 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showInfo } from '../../helpers';
|
||||
import {
|
||||
getExperienceCenterBool,
|
||||
getExperienceCenterPositiveInt,
|
||||
} from '../../helpers/experienceCenter';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { useCreationModels } from '../creation/useCreationModels';
|
||||
import { useCreationQuote } from '../creation/useCreationQuote';
|
||||
import {
|
||||
optionLabel,
|
||||
paramLabel,
|
||||
} from '../../components/creation/params/labels';
|
||||
import {
|
||||
MODE_LABEL_KEYS,
|
||||
buildImageRequest,
|
||||
composeParams,
|
||||
composePrefillParams,
|
||||
formFromImageRequest,
|
||||
formFromLegacyTask,
|
||||
imageBlockReason,
|
||||
imageSlotsOf,
|
||||
isModeEnabled,
|
||||
loadDraft,
|
||||
modeOptionsOf,
|
||||
modelNameOf,
|
||||
pickModeForModel,
|
||||
quoteRequestOf,
|
||||
referenceMaxOf,
|
||||
requestParamsForMode,
|
||||
requestParamsOf,
|
||||
saveDraft,
|
||||
supportsReferences,
|
||||
} from './imageCreation';
|
||||
|
||||
// 内联提交(不经上传接口)时的单张参考图上限,与旧表单一致
|
||||
const INLINE_MAX_MB = 20;
|
||||
|
||||
const getStorage = () => {
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const newSlotId = () =>
|
||||
`ref-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
const readAsDataURL = (file) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.onerror = () => reject(reader.error || new Error('read failed'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
// 从 URL 获取图片并构造 File 对象(结果不可按 task:// 引用时的兜底)
|
||||
const urlToFile = async (url, filename = 'reference.png') => {
|
||||
const resp = await fetch(url);
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const blob = await resp.blob();
|
||||
const ext = (blob.type.split('/')[1] || 'png').replace('jpeg', 'jpg');
|
||||
return new File([blob], `${filename.replace(/\.[^.]+$/, '')}.${ext}`, {
|
||||
type: blob.type || 'image/png',
|
||||
});
|
||||
};
|
||||
|
||||
/** 写入(slot 为 null 时移除)一张参考图。index 超出时追加。 */
|
||||
const writeReference = (list, index, slot) => {
|
||||
const next = [...(list || [])];
|
||||
if (slot) {
|
||||
if (index === undefined || index === null || index >= next.length) {
|
||||
next.push(slot);
|
||||
} else {
|
||||
next[index] = slot;
|
||||
}
|
||||
} else if (index !== undefined && index !== null) {
|
||||
next.splice(index, 1);
|
||||
}
|
||||
return next.filter(Boolean);
|
||||
};
|
||||
|
||||
const patchReferenceById = (list, id, patch) =>
|
||||
(list || []).map((slot) =>
|
||||
slot && slot.id === id ? { ...slot, ...patch } : slot,
|
||||
);
|
||||
|
||||
/**
|
||||
* 体验中心图像页的创作表单(WP A2-3):schema 驱动的模型 / 参数 / 参考图、估价、提交。
|
||||
*
|
||||
* @param {{
|
||||
* tasks: object[],
|
||||
* addTask: (payload: object) => Promise<{ok: boolean, code?: string, message?: string, data?: object}>,
|
||||
* fetchTaskDetail: (taskId: string) => Promise<object|null>,
|
||||
* }} deps 来自 useImageTaskManagement
|
||||
*/
|
||||
export const useImageCreation = ({ tasks = [], addTask, fetchTaskDetail }) => {
|
||||
const { t } = useTranslation();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const status = statusState?.status;
|
||||
|
||||
const {
|
||||
data: creationData,
|
||||
models,
|
||||
loading: modelsLoading,
|
||||
error: modelsError,
|
||||
reload: reloadModels,
|
||||
} = useCreationModels('image');
|
||||
|
||||
const [formData, setFormData] = useState(() => loadDraft(getStorage()));
|
||||
const formRef = useRef(formData);
|
||||
formRef.current = formData;
|
||||
|
||||
// 本次会话用户手动设置过的参数(切换模型时优先级最高)
|
||||
const sessionValuesRef = useRef({});
|
||||
const schemaAppliedRef = useRef(false);
|
||||
const fileStoreRef = useRef(new Map()); // slotId → File(重试用,不进草稿)
|
||||
// 外部回填(复用参数 / 用作参考图 / 示例提示词)计数:移动端据此展开表单
|
||||
const [prefillSeq, setPrefillSeq] = useState(0);
|
||||
|
||||
const selectedModel = useMemo(
|
||||
() => models.find((m) => m.model === formData.modelName) || null,
|
||||
[models, formData.modelName],
|
||||
);
|
||||
|
||||
// 自动保存草稿
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => saveDraft(getStorage(), formData), 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [formData]);
|
||||
|
||||
// 参数 / 模式被吸附时的提示(切换模型与复用参数共用)
|
||||
const notifyAdjustments = useCallback(
|
||||
(model, adjustments, fromMode, toMode) => {
|
||||
const params = requestParamsOf(model);
|
||||
const items = adjustments.map((a) => {
|
||||
const param = params.find((p) => p.key === a.key) || { key: a.key };
|
||||
return `${paramLabel(t, param)} ${optionLabel(t, param, a.from)} → ${optionLabel(t, param, a.to)}`;
|
||||
});
|
||||
if (fromMode && toMode && fromMode !== toMode) {
|
||||
items.unshift(
|
||||
`${t('生成模式')} ${t(MODE_LABEL_KEYS[fromMode] || fromMode)} → ${t(MODE_LABEL_KEYS[toMode] || toMode)}`,
|
||||
);
|
||||
}
|
||||
if (items.length) {
|
||||
showInfo(
|
||||
t('已按新模型调整:{{list}}(该模型不支持原取值)', {
|
||||
list: items.join(';'),
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const applyModel = useCallback(
|
||||
(next, { silent = false } = {}) => {
|
||||
if (!next) return;
|
||||
const prev = formRef.current;
|
||||
const name = modelNameOf(next);
|
||||
const paramMemory = { ...(prev.paramMemory || {}) };
|
||||
if (prev.modelName && prev.modelName !== name && prev.params) {
|
||||
paramMemory[prev.modelName] = prev.params;
|
||||
}
|
||||
const memory =
|
||||
name === prev.modelName ? prev.params : paramMemory[name] || {};
|
||||
const { values, adjustments } = composeParams(next, {
|
||||
sessionValues: sessionValuesRef.current,
|
||||
memory,
|
||||
});
|
||||
const mode = pickModeForModel(
|
||||
next,
|
||||
prev.preferredMode || prev.mode,
|
||||
prev.references,
|
||||
);
|
||||
const nextForm = {
|
||||
...prev,
|
||||
modelName: name,
|
||||
params: values,
|
||||
mode,
|
||||
paramMemory,
|
||||
};
|
||||
formRef.current = nextForm;
|
||||
setFormData(nextForm);
|
||||
if (!silent) notifyAdjustments(next, adjustments, prev.mode, mode);
|
||||
},
|
||||
[notifyAdjustments],
|
||||
);
|
||||
|
||||
// 模型加载后:沿用草稿中的模型(仍可用时),否则选第一个可调用的模型
|
||||
useEffect(() => {
|
||||
if (modelsLoading || models.length === 0) return;
|
||||
const current = models.find((m) => m.model === formRef.current.modelName);
|
||||
if (current && !current.level_locked) {
|
||||
if (!schemaAppliedRef.current) {
|
||||
schemaAppliedRef.current = true;
|
||||
applyModel(current, { silent: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const first = models.find((m) => !m.level_locked);
|
||||
if (first) {
|
||||
schemaAppliedRef.current = true;
|
||||
applyModel(first, { silent: true });
|
||||
}
|
||||
}, [models, modelsLoading, applyModel]);
|
||||
|
||||
const setSelectedModel = useCallback(
|
||||
(modelOrName) => {
|
||||
const name = modelNameOf(modelOrName);
|
||||
const next = models.find((m) => m.model === name);
|
||||
if (!next) return;
|
||||
if (next.level_locked) {
|
||||
showError(t('当前等级无权调用此模型,请选择其他模型'));
|
||||
return;
|
||||
}
|
||||
applyModel(next);
|
||||
},
|
||||
[models, applyModel, t],
|
||||
);
|
||||
|
||||
const setMode = useCallback(
|
||||
(mode) => {
|
||||
if (selectedModel && !isModeEnabled(selectedModel, mode)) return;
|
||||
setFormData((prev) => ({ ...prev, mode, preferredMode: mode }));
|
||||
},
|
||||
[selectedModel],
|
||||
);
|
||||
|
||||
const setPrompt = useCallback((prompt) => {
|
||||
setFormData((prev) => ({ ...prev, prompt: prompt || '' }));
|
||||
}, []);
|
||||
|
||||
const updateParam = useCallback((key, value) => {
|
||||
sessionValuesRef.current = { ...sessionValuesRef.current, [key]: value };
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
params: { ...prev.params, [key]: value },
|
||||
}));
|
||||
}, []);
|
||||
|
||||
/** 重置:清空提示词、负向提示词、参考图,参数回到当前模型默认值(保留模型)。 */
|
||||
const resetForm = useCallback(() => {
|
||||
const prev = formRef.current;
|
||||
(prev.references || []).forEach(
|
||||
(slot) => slot?.id && fileStoreRef.current.delete(slot.id),
|
||||
);
|
||||
sessionValuesRef.current = {};
|
||||
const { values } = composeParams(selectedModel, {});
|
||||
setFormData({
|
||||
...prev,
|
||||
prompt: '',
|
||||
references: [],
|
||||
params: values,
|
||||
mode: pickModeForModel(selectedModel, 'text2image', []),
|
||||
preferredMode: '',
|
||||
});
|
||||
}, [selectedModel]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 参考图:COS + 上传开关都开启时先上传再按 cos:// 引用提交,否则内联 base64
|
||||
// ---------------------------------------------------------------------------
|
||||
const cosEnabled = status?.experience_center_cos_enabled === true;
|
||||
let fileUploadEnabled = false;
|
||||
let uploadMaxMB = 10;
|
||||
try {
|
||||
fileUploadEnabled = getExperienceCenterBool(
|
||||
status,
|
||||
'experience_center_enable_file_upload',
|
||||
'experience_center_enable_file_upload',
|
||||
false,
|
||||
);
|
||||
uploadMaxMB = getExperienceCenterPositiveInt(
|
||||
status,
|
||||
'experience_center_upload_max_size',
|
||||
'experience_center_upload_max_size',
|
||||
10,
|
||||
);
|
||||
} catch (e) {
|
||||
// localStorage 不可用时按默认值
|
||||
}
|
||||
const uploadByReference = cosEnabled && fileUploadEnabled;
|
||||
const maxFileMB = uploadByReference ? uploadMaxMB : INLINE_MAX_MB;
|
||||
|
||||
const uploadSlotFile = useCallback(
|
||||
async (id, file) => {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
try {
|
||||
const res = await API.post('/api/user/upload/file', fd, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
const data = res?.data?.data;
|
||||
if (!res?.data?.success || !data?.cos_path) {
|
||||
throw new Error(res?.data?.message || t('上传失败'));
|
||||
}
|
||||
fileStoreRef.current.delete(id);
|
||||
setFormData((prev) => {
|
||||
const current = (prev.references || []).find((s) => s && s.id === id);
|
||||
return {
|
||||
...prev,
|
||||
references: patchReferenceById(prev.references, id, {
|
||||
status: 'ready',
|
||||
ref: `cos://${data.cos_path}`,
|
||||
previewUrl: data.url || current?.previewUrl,
|
||||
error: null,
|
||||
}),
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
const message =
|
||||
err?.response?.data?.message || err?.message || t('上传失败');
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
references: patchReferenceById(prev.references, id, {
|
||||
status: 'error',
|
||||
error: message,
|
||||
}),
|
||||
}));
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
/** 选择 / 拖入 / 粘贴一张参考图放入第 index 个槽(index 缺省为追加)。 */
|
||||
const pickImage = useCallback(
|
||||
async (index, file, { name } = {}) => {
|
||||
if (!file) return false;
|
||||
if (file.type && !file.type.startsWith('image/')) {
|
||||
showError(t('请上传图片'));
|
||||
return false;
|
||||
}
|
||||
if (maxFileMB > 0 && file.size > maxFileMB * 1024 * 1024) {
|
||||
showError(t('图片不能超过 {{size}}MB', { size: maxFileMB }));
|
||||
return false;
|
||||
}
|
||||
let dataUrl;
|
||||
try {
|
||||
dataUrl = await readAsDataURL(file);
|
||||
} catch (e) {
|
||||
showError(t('读取图片失败,请重新选择'));
|
||||
return false;
|
||||
}
|
||||
const id = newSlotId();
|
||||
const base = { id, name: name || file.name, previewUrl: dataUrl };
|
||||
const slot = uploadByReference
|
||||
? { ...base, status: 'uploading', source: 'upload' }
|
||||
: { ...base, status: 'ready', ref: dataUrl, source: 'inline' };
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
references: writeReference(prev.references, index, slot),
|
||||
}));
|
||||
if (uploadByReference) {
|
||||
fileStoreRef.current.set(id, file);
|
||||
uploadSlotFile(id, file);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[t, maxFileMB, uploadByReference, uploadSlotFile],
|
||||
);
|
||||
|
||||
const removeImage = useCallback((index) => {
|
||||
setFormData((prev) => {
|
||||
const target = (prev.references || [])[index];
|
||||
if (target?.id) fileStoreRef.current.delete(target.id);
|
||||
return {
|
||||
...prev,
|
||||
references: writeReference(prev.references, index, null),
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
const retryImage = useCallback(
|
||||
(index, slot) => {
|
||||
const file = slot?.id ? fileStoreRef.current.get(slot.id) : null;
|
||||
if (!file) {
|
||||
// 刷新页面后原文件已不在内存中:移除该槽,让用户重新选择
|
||||
removeImage(index);
|
||||
return;
|
||||
}
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
references: patchReferenceById(prev.references, slot.id, {
|
||||
status: 'uploading',
|
||||
error: null,
|
||||
}),
|
||||
}));
|
||||
uploadSlotFile(slot.id, file);
|
||||
},
|
||||
[removeImage, uploadSlotFile],
|
||||
);
|
||||
|
||||
/**
|
||||
* 用作参考图:结果可复用(reusable_as_input)时按 task:// 引用放入参考图槽,否则下载后按本地图片处理。
|
||||
* 当前模型支持编辑时切到编辑模式;不支持时图片保留并置灰,切到支持的模型后自动使用。
|
||||
*/
|
||||
const applyAsReference = useCallback(
|
||||
async (task) => {
|
||||
if (!task?.id) return false;
|
||||
const prev = formRef.current;
|
||||
const model = selectedModel;
|
||||
const max = referenceMaxOf(model, 'edit');
|
||||
const refs = prev.references || [];
|
||||
// 槽满时替换最后一张(旧表单只有一张参考图,行为一致)
|
||||
const index = max > 0 && refs.length >= max ? max - 1 : refs.length;
|
||||
let added = false;
|
||||
if (task.reusableAsInput) {
|
||||
setFormData((p) => ({
|
||||
...p,
|
||||
references: writeReference(p.references, index, {
|
||||
id: newSlotId(),
|
||||
status: 'ready',
|
||||
ref: `task://${task.id}`,
|
||||
previewUrl: task.imageUrl || null,
|
||||
source: 'task',
|
||||
}),
|
||||
}));
|
||||
added = true;
|
||||
} else if (task.imageUrl) {
|
||||
try {
|
||||
const file = await urlToFile(task.imageUrl, `reference-${task.id}`);
|
||||
added = await pickImage(index, file);
|
||||
} catch (e) {
|
||||
console.warn('Load reference image url failed:', e);
|
||||
showError(t('参考图加载失败'));
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
showError(t('该图片暂不可用作参考图'));
|
||||
return false;
|
||||
}
|
||||
if (!added) return false;
|
||||
if (model && isModeEnabled(model, 'edit')) {
|
||||
setFormData((p) => ({ ...p, mode: 'edit', preferredMode: 'edit' }));
|
||||
showInfo(t('已切换到图生图并回填参考图'));
|
||||
} else {
|
||||
setFormData((p) => ({ ...p, preferredMode: 'edit' }));
|
||||
showInfo(
|
||||
t('当前模型不支持图生图,参考图已保留,切换到支持图生图的模型后使用'),
|
||||
);
|
||||
}
|
||||
setPrefillSeq((n) => n + 1);
|
||||
return true;
|
||||
},
|
||||
[selectedModel, pickImage, t],
|
||||
);
|
||||
|
||||
/** 示例提示词(空状态卡片)。 */
|
||||
const applySamplePrompt = useCallback(
|
||||
(prompt) => {
|
||||
if (!prompt) return;
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
prompt,
|
||||
mode: pickModeForModel(selectedModel, 'text2image', prev.references),
|
||||
preferredMode: 'text2image',
|
||||
}));
|
||||
setPrefillSeq((n) => n + 1);
|
||||
},
|
||||
[selectedModel],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 复用参数 / 再生成:优先使用任务详情中的参数快照(request),旧任务退回任务数据
|
||||
// ---------------------------------------------------------------------------
|
||||
const resolveTaskForm = useCallback(
|
||||
async (task) => {
|
||||
let request = task?.request || null;
|
||||
if (!request && fetchTaskDetail && task?.id) {
|
||||
const detail = await fetchTaskDetail(task.id);
|
||||
request = detail?.request || null;
|
||||
}
|
||||
const filled = request
|
||||
? formFromImageRequest(request, { newId: newSlotId })
|
||||
: formFromLegacyTask(task, { newId: newSlotId });
|
||||
const originalName = filled.modelName || task?.model || '';
|
||||
const original = models.find((m) => m.model === originalName);
|
||||
return { filled, originalName, original };
|
||||
},
|
||||
[fetchTaskDetail, models],
|
||||
);
|
||||
|
||||
/** 复用参数:回填表单,等用户确认后再生成。 */
|
||||
const prefillFromTask = useCallback(
|
||||
async (task) => {
|
||||
if (!task) return false;
|
||||
const { filled, originalName, original } = await resolveTaskForm(task);
|
||||
const prev = formRef.current;
|
||||
let target = original && !original.level_locked ? original : null;
|
||||
if (!target) {
|
||||
target =
|
||||
models.find((m) => m.model === prev.modelName && !m.level_locked) ||
|
||||
null;
|
||||
if (!target) {
|
||||
showError(
|
||||
t('原模型 {{model}} 已不可用,请先选择可用模型', {
|
||||
model: originalName,
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (originalName) {
|
||||
showInfo(
|
||||
t('原模型 {{model}} 已不可用,已保留当前模型', {
|
||||
model: originalName,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
const name = modelNameOf(target);
|
||||
const paramMemory = { ...(prev.paramMemory || {}) };
|
||||
if (prev.modelName && prev.modelName !== name && prev.params) {
|
||||
paramMemory[prev.modelName] = prev.params;
|
||||
}
|
||||
// 任务快照对请求参数是权威的:只按快照合成(不合并此前会话值 / 模型记忆,避免固定种子等泄漏);
|
||||
// 之后视同用户本次手动设置,切换模型时仍优先保留
|
||||
sessionValuesRef.current = { ...(filled.params || {}) };
|
||||
const { values, adjustments } = composePrefillParams(
|
||||
target,
|
||||
filled.params,
|
||||
);
|
||||
const mode = pickModeForModel(target, filled.mode, filled.references);
|
||||
(prev.references || []).forEach(
|
||||
(slot) => slot?.id && fileStoreRef.current.delete(slot.id),
|
||||
);
|
||||
const nextForm = {
|
||||
...prev,
|
||||
modelName: name,
|
||||
mode,
|
||||
preferredMode: filled.mode,
|
||||
prompt: filled.prompt,
|
||||
params: values,
|
||||
references: filled.references,
|
||||
paramMemory,
|
||||
};
|
||||
schemaAppliedRef.current = true;
|
||||
formRef.current = nextForm;
|
||||
setFormData(nextForm);
|
||||
setPrefillSeq((n) => n + 1);
|
||||
if (filled.missingReferences > 0) {
|
||||
showInfo(t('部分参考图已失效,请重新上传'));
|
||||
}
|
||||
if (adjustments.length || mode !== filled.mode) {
|
||||
notifyAdjustments(target, adjustments, filled.mode, mode);
|
||||
} else {
|
||||
showInfo(t('已回填参数'));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[models, notifyAdjustments, resolveTaskForm, t],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 并发上限、估价、提交
|
||||
// ---------------------------------------------------------------------------
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const submittingRef = useRef(false);
|
||||
const [serverRunning, setServerRunning] = useState(0);
|
||||
const [maxRunningOverride, setMaxRunningOverride] = useState(0);
|
||||
useEffect(() => {
|
||||
setServerRunning(Number(creationData.running_tasks) || 0);
|
||||
}, [creationData.running_tasks]);
|
||||
|
||||
const localRunning = useMemo(
|
||||
() => tasks.filter((task) => task.status === 'processing').length,
|
||||
[tasks],
|
||||
);
|
||||
// 本地任务有结束时,以本地统计为准(服务端数字只在加载 / 429 时刷新)
|
||||
const prevLocalRunningRef = useRef(localRunning);
|
||||
useEffect(() => {
|
||||
if (localRunning < prevLocalRunningRef.current) setServerRunning(0);
|
||||
prevLocalRunningRef.current = localRunning;
|
||||
}, [localRunning]);
|
||||
|
||||
const maxRunning =
|
||||
maxRunningOverride || Number(creationData.max_running_tasks) || 0;
|
||||
const runningCount = Math.max(localRunning, serverRunning);
|
||||
const runningLimitReached = maxRunning > 0 && runningCount >= maxRunning;
|
||||
|
||||
const requestPayload = useMemo(
|
||||
() => (selectedModel ? buildImageRequest(selectedModel, formData) : null),
|
||||
[selectedModel, formData],
|
||||
);
|
||||
|
||||
const quoteRequest = useMemo(() => {
|
||||
if (!selectedModel || selectedModel.level_locked || !requestPayload) {
|
||||
return null;
|
||||
}
|
||||
return quoteRequestOf(selectedModel, requestPayload);
|
||||
}, [selectedModel, requestPayload]);
|
||||
const quoteState = useCreationQuote(quoteRequest);
|
||||
|
||||
const submitBlock = useMemo(() => {
|
||||
if (modelsLoading) return t('模型列表加载中');
|
||||
if (modelsError && models.length === 0) return t('模型列表加载失败');
|
||||
if (!selectedModel) return t('请选择模型');
|
||||
if (selectedModel.level_locked) return t('当前等级无权调用此模型');
|
||||
if (!formData.prompt || !formData.prompt.trim()) return t('请输入提示词');
|
||||
const imageReason = imageBlockReason(
|
||||
selectedModel,
|
||||
formData.mode,
|
||||
formData.references,
|
||||
);
|
||||
if (imageReason) return t(imageReason.key);
|
||||
if (runningLimitReached) {
|
||||
return t('已有 {{n}} 个任务进行中,完成后可继续', { n: runningCount });
|
||||
}
|
||||
return '';
|
||||
}, [
|
||||
modelsLoading,
|
||||
modelsError,
|
||||
models.length,
|
||||
selectedModel,
|
||||
formData.prompt,
|
||||
formData.mode,
|
||||
formData.references,
|
||||
runningLimitReached,
|
||||
runningCount,
|
||||
t,
|
||||
]);
|
||||
|
||||
/** 提交请求体;失败时按错误码给出中文提示。 */
|
||||
const submitPayload = useCallback(
|
||||
async (payload) => {
|
||||
if (!addTask || !payload || submittingRef.current) return false;
|
||||
submittingRef.current = true;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const result = await addTask(payload);
|
||||
if (result?.ok) return true;
|
||||
if (result?.code === 'too_many_running_tasks') {
|
||||
const running = Number(result.data?.running_tasks) || 0;
|
||||
const max = Number(result.data?.max_running_tasks) || 0;
|
||||
if (running > 0) setServerRunning(running);
|
||||
if (max > 0) setMaxRunningOverride(max);
|
||||
showError(
|
||||
running > 0
|
||||
? t('已有 {{n}} 个任务进行中,完成后可继续', { n: running })
|
||||
: result.message || t('进行中的任务过多,请稍后再试'),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
showError(
|
||||
t('图片生成失败:{{message}}', {
|
||||
message: result?.message || t('未知错误'),
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
submittingRef.current = false;
|
||||
setSubmitting(false);
|
||||
}
|
||||
},
|
||||
[addTask, t],
|
||||
);
|
||||
|
||||
const handleGenerate = useCallback(async () => {
|
||||
if (submittingRef.current) return false;
|
||||
if (submitBlock) {
|
||||
showError(submitBlock);
|
||||
return false;
|
||||
}
|
||||
if (!requestPayload) return false;
|
||||
return submitPayload(requestPayload);
|
||||
}, [submitBlock, requestPayload, submitPayload]);
|
||||
|
||||
/** 重新生成 / 重试:按原任务参数(快照优先)直接再提交一次,不改动当前表单。 */
|
||||
const regenerateTask = useCallback(
|
||||
async (task) => {
|
||||
if (!task) {
|
||||
showError(t('任务不存在'));
|
||||
return false;
|
||||
}
|
||||
const { filled, originalName, original } = await resolveTaskForm(task);
|
||||
if (!filled.prompt) {
|
||||
showError(t('无法重新生成:缺少提示词'));
|
||||
return false;
|
||||
}
|
||||
if (!original || original.level_locked) {
|
||||
showError(
|
||||
t('原模型 {{model}} 已不可用,请使用「复用参数」选择其他模型', {
|
||||
model: originalName || '-',
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (filled.mode === 'edit' && filled.missingReferences > 0) {
|
||||
showError(t('原参考图已失效,请使用「复用参数」后重新上传参考图'));
|
||||
return false;
|
||||
}
|
||||
const mode = pickModeForModel(original, filled.mode, filled.references);
|
||||
if (mode !== filled.mode) {
|
||||
showError(t('当前模型不支持该生成模式,请切换模式'));
|
||||
return false;
|
||||
}
|
||||
const { values, adjustments } = composeParams(original, {
|
||||
sessionValues: filled.params,
|
||||
});
|
||||
if (adjustments.length) {
|
||||
notifyAdjustments(original, adjustments);
|
||||
}
|
||||
return submitPayload(
|
||||
buildImageRequest(original, {
|
||||
mode,
|
||||
prompt: filled.prompt,
|
||||
params: values,
|
||||
references: filled.references,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[resolveTaskForm, notifyAdjustments, submitPayload, t],
|
||||
);
|
||||
|
||||
const modeOptions = useMemo(
|
||||
() => modeOptionsOf(selectedModel),
|
||||
[selectedModel],
|
||||
);
|
||||
const imageSlots = useMemo(
|
||||
() =>
|
||||
selectedModel
|
||||
? imageSlotsOf(selectedModel, formData.mode, formData.references)
|
||||
: [],
|
||||
[selectedModel, formData.mode, formData.references],
|
||||
);
|
||||
// 只显示适用于当前模式的参数(schema modes),与 buildImageRequest 的提交口径一致
|
||||
const visibleParams = useMemo(
|
||||
() =>
|
||||
selectedModel ? requestParamsForMode(selectedModel, formData.mode) : [],
|
||||
[selectedModel, formData.mode],
|
||||
);
|
||||
|
||||
return {
|
||||
// 表单
|
||||
formData,
|
||||
setPrompt,
|
||||
setMode,
|
||||
updateParam,
|
||||
resetForm,
|
||||
prefillSeq,
|
||||
// 模型 schema
|
||||
models,
|
||||
modelsLoading,
|
||||
modelsError,
|
||||
reloadModels,
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
modeOptions,
|
||||
visibleParams,
|
||||
supportsReferences: supportsReferences(selectedModel),
|
||||
// 参考图
|
||||
imageSlots,
|
||||
pickImage,
|
||||
removeImage,
|
||||
retryImage,
|
||||
applyAsReference,
|
||||
uploadByReference,
|
||||
// 估价 / 提交
|
||||
quote: quoteState.quote,
|
||||
quoteLoading: quoteState.loading,
|
||||
quoteFailed: quoteState.failed,
|
||||
estSeconds: selectedModel?.est_seconds?.p50 || 0,
|
||||
submitBlock,
|
||||
submitting,
|
||||
runningCount,
|
||||
maxRunning,
|
||||
handleGenerate,
|
||||
// 任务操作
|
||||
prefillFromTask,
|
||||
regenerateTask,
|
||||
applySamplePrompt,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageCreation;
|
||||
@@ -1,334 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/**
|
||||
* 图像生成管理钩子
|
||||
* @param {Function} onImageGenerated 图片生成成功后的回调函数
|
||||
* @returns {Object} 图像生成相关状态和方法
|
||||
*/
|
||||
const useImageGeneration = (onImageGenerated) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 状态管理
|
||||
const [generatedImages, setGeneratedImages] = useState([]);
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [generationParams, setGenerationParams] = useState({});
|
||||
|
||||
// 加载状态管理
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loadingProgress, setLoadingProgress] = useState(0);
|
||||
|
||||
// 用于存储上一次成功生成的参数
|
||||
const lastSuccessfulParamsRef = useRef({});
|
||||
|
||||
// 清除错误信息
|
||||
const clearError = useCallback(() => {
|
||||
setError('');
|
||||
}, []);
|
||||
|
||||
// 清除生成的图片
|
||||
const clearGeneratedImages = useCallback(() => {
|
||||
setGeneratedImages([]);
|
||||
clearError();
|
||||
}, [clearError]);
|
||||
|
||||
/**
|
||||
* 生成图片
|
||||
* @param {Object} params 生成参数
|
||||
* @param {string} params.prompt 提示词
|
||||
* @param {string} params.model 模型名称
|
||||
* @param {string} params.size 图片尺寸
|
||||
* @param {string} params.quality 图片质量
|
||||
* @param {string} params.negativePrompt 反向提示词
|
||||
* @param {number} params.n 生成图片数量
|
||||
*/
|
||||
const generateImage = useCallback(
|
||||
async (params) => {
|
||||
const {
|
||||
prompt,
|
||||
model,
|
||||
size,
|
||||
quality,
|
||||
negativePrompt = '',
|
||||
n = 1,
|
||||
} = params;
|
||||
|
||||
// 参数验证
|
||||
if (!prompt || !prompt.trim()) {
|
||||
setError(t('请输入提示词'));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!model) {
|
||||
setError(t('请选择生成模型'));
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!size) {
|
||||
setError(t('请选择图片尺寸'));
|
||||
return false;
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
setIsGenerating(true);
|
||||
setError('');
|
||||
setIsLoading(true);
|
||||
setLoadingProgress(0);
|
||||
|
||||
// 保存当前参数
|
||||
setGenerationParams(params);
|
||||
|
||||
try {
|
||||
// 模拟进度更新
|
||||
const progressInterval = setInterval(() => {
|
||||
setLoadingProgress((prev) => {
|
||||
if (prev >= 90) {
|
||||
clearInterval(progressInterval);
|
||||
return prev;
|
||||
}
|
||||
return prev + Math.random() * 10;
|
||||
});
|
||||
}, 200);
|
||||
|
||||
// 这里是模拟API调用,实际实现需要替换为真实的API请求
|
||||
// 模拟网络延迟
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
|
||||
clearInterval(progressInterval);
|
||||
|
||||
// 模拟生成的图片数据
|
||||
const mockImages = Array.from({ length: n }, (_, index) => ({
|
||||
id: Date.now() + index,
|
||||
url: `https://picsum.photos/seed/${Date.now() + index}/${size.split('x')[0]}/${size.split('x')[1]}`,
|
||||
revised_prompt: prompt,
|
||||
created_at: new Date().toISOString(),
|
||||
metadata: {
|
||||
model,
|
||||
size,
|
||||
quality,
|
||||
negative_prompt: negativePrompt,
|
||||
},
|
||||
}));
|
||||
|
||||
setGeneratedImages(mockImages);
|
||||
|
||||
// 更新上一次成功生成的参数
|
||||
lastSuccessfulParamsRef.current = params;
|
||||
|
||||
// 调用回调函数
|
||||
if (onImageGenerated) {
|
||||
onImageGenerated(mockImages, params);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('Image generation failed:', err);
|
||||
setError(t('图片生成失败,请重试') + ': ' + (err.message || ''));
|
||||
return false;
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
setIsLoading(false);
|
||||
setLoadingProgress(100);
|
||||
}
|
||||
},
|
||||
[t, onImageGenerated],
|
||||
);
|
||||
|
||||
/**
|
||||
* 重新生成图片
|
||||
* 使用上一次成功生成的参数或当前保存的参数
|
||||
*/
|
||||
const regenerateImage = useCallback(async () => {
|
||||
// 获取有效的参数
|
||||
const params =
|
||||
Object.keys(lastSuccessfulParamsRef.current).length > 0
|
||||
? lastSuccessfulParamsRef.current
|
||||
: Object.keys(generationParams).length > 0
|
||||
? generationParams
|
||||
: null;
|
||||
|
||||
if (!params) {
|
||||
setError(t('没有可用的生成参数'));
|
||||
return false;
|
||||
}
|
||||
|
||||
// 确保参数完整
|
||||
if (!params.prompt || !params.model || !params.size) {
|
||||
setError(t('参数不完整,无法重新生成'));
|
||||
return false;
|
||||
}
|
||||
|
||||
return generateImage(params);
|
||||
}, [generateImage, generationParams, t]);
|
||||
|
||||
/**
|
||||
* 下载单个图片
|
||||
* @param {string} imageUrl 图片URL
|
||||
* @param {number} index 图片索引
|
||||
* @param {string} prompt 提示词(用于生成文件名)
|
||||
*/
|
||||
const downloadImage = useCallback((imageUrl, index = 0, prompt = '') => {
|
||||
const link = document.createElement('a');
|
||||
|
||||
// 生成文件名
|
||||
let filename = 'generated-image';
|
||||
|
||||
// 如果有提示词,使用前20个字符作为文件名的一部分
|
||||
if (prompt && prompt.trim()) {
|
||||
const safePrompt = prompt
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]/gi, '_')
|
||||
.substring(0, 20);
|
||||
filename = `${filename}-${safePrompt}`;
|
||||
}
|
||||
|
||||
// 添加索引和时间戳
|
||||
filename = `${filename}-${index}-${Date.now()}.png`;
|
||||
|
||||
link.href = imageUrl;
|
||||
link.download = filename;
|
||||
|
||||
// 模拟点击下载
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// 清理
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(link);
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 批量下载所有生成的图片
|
||||
* @param {string} prompt 提示词(用于生成文件名前缀)
|
||||
*/
|
||||
const downloadAllImages = useCallback(
|
||||
(prompt = '') => {
|
||||
if (generatedImages.length === 0) {
|
||||
setError(t('没有可下载的图片'));
|
||||
return;
|
||||
}
|
||||
|
||||
// 为每个图片创建下载
|
||||
generatedImages.forEach((image, index) => {
|
||||
downloadImage(image.url, index, prompt);
|
||||
});
|
||||
},
|
||||
[generatedImages, downloadImage, t],
|
||||
);
|
||||
|
||||
/**
|
||||
* 将图片转换为Blob对象
|
||||
* @param {string} imageUrl 图片URL
|
||||
* @returns {Promise<Blob>} Blob对象
|
||||
*/
|
||||
const imageUrlToBlob = useCallback(async (imageUrl) => {
|
||||
try {
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
return blob;
|
||||
} catch (error) {
|
||||
console.error('Failed to convert image to blob:', error);
|
||||
throw error;
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 将图片复制到剪贴板
|
||||
* @param {string} imageUrl 图片URL
|
||||
*/
|
||||
const copyImageToClipboard = useCallback(
|
||||
async (imageUrl) => {
|
||||
try {
|
||||
const blob = await imageUrlToBlob(imageUrl);
|
||||
|
||||
// 检查浏览器是否支持剪贴板API
|
||||
if (navigator.clipboard && window.ClipboardItem) {
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': blob,
|
||||
}),
|
||||
]);
|
||||
return true;
|
||||
} else {
|
||||
setError(t('您的浏览器不支持复制图片到剪贴板'));
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to copy image to clipboard:', error);
|
||||
setError(t('复制图片失败: {{error}}', { error: error.message }));
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[imageUrlToBlob, t],
|
||||
);
|
||||
|
||||
/**
|
||||
* 查看图片详情
|
||||
* @param {Object} image 图片对象
|
||||
*/
|
||||
const viewImageDetails = useCallback((image) => {
|
||||
// 可以在这里实现图片详情查看逻辑,比如打开模态框显示大图
|
||||
console.log('Viewing image details:', image);
|
||||
|
||||
// 如果是浏览器环境,可以在新标签页打开图片
|
||||
if (typeof window !== 'undefined' && window.open) {
|
||||
window.open(image.url, '_blank');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 获取图片信息
|
||||
* @param {string} imageId 图片ID
|
||||
* @returns {Object|null} 图片对象
|
||||
*/
|
||||
const getImageById = useCallback(
|
||||
(imageId) => {
|
||||
return generatedImages.find((image) => image.id === imageId) || null;
|
||||
},
|
||||
[generatedImages],
|
||||
);
|
||||
|
||||
return {
|
||||
// 状态
|
||||
generatedImages,
|
||||
isGenerating,
|
||||
error,
|
||||
loadingProgress,
|
||||
isLoading,
|
||||
generationParams,
|
||||
|
||||
// 操作方法
|
||||
generateImage,
|
||||
regenerateImage,
|
||||
downloadImage,
|
||||
downloadAllImages,
|
||||
copyImageToClipboard,
|
||||
viewImageDetails,
|
||||
clearGeneratedImages,
|
||||
clearError,
|
||||
getImageById,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageGeneration;
|
||||
@@ -1,401 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 本地存储键名
|
||||
const STORAGE_KEY = 'imageGenerationHistory';
|
||||
// 最大历史记录条数
|
||||
const MAX_HISTORY_ITEMS = 50;
|
||||
|
||||
/**
|
||||
* 图像生成历史记录管理钩子
|
||||
* @param {number} maxItems 最大历史记录条数
|
||||
* @returns {Object} 历史记录相关状态和方法
|
||||
*/
|
||||
const useImageHistory = (maxItems = MAX_HISTORY_ITEMS) => {
|
||||
const { t: _t } = useTranslation();
|
||||
|
||||
// 状态管理
|
||||
const [history, setHistory] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// 从本地存储加载历史记录
|
||||
const loadHistory = useCallback(() => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const savedHistory = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedHistory) {
|
||||
const parsedHistory = JSON.parse(savedHistory);
|
||||
// 确保是数组格式
|
||||
if (Array.isArray(parsedHistory)) {
|
||||
setHistory(parsedHistory);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load history from localStorage:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 保存历史记录到本地存储
|
||||
const saveHistory = useCallback((historyData) => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(historyData));
|
||||
} catch (error) {
|
||||
console.error('Failed to save history to localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 初始化时加载历史记录
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, [loadHistory]);
|
||||
|
||||
/**
|
||||
* 添加新的生成记录
|
||||
* @param {Object} record 生成记录
|
||||
* @param {string} record.model 使用的模型
|
||||
* @param {string} record.prompt 使用的提示词
|
||||
* @param {string} record.negativePrompt 使用的反向提示词
|
||||
* @param {string} record.size 图片尺寸
|
||||
* @param {string} record.quality 图片质量
|
||||
* @param {Array} record.images 生成的图片数组
|
||||
*/
|
||||
const addHistoryRecord = useCallback(
|
||||
(record) => {
|
||||
if (
|
||||
!record ||
|
||||
!record.prompt ||
|
||||
!record.images ||
|
||||
!Array.isArray(record.images)
|
||||
) {
|
||||
console.error('Invalid history record:', record);
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建完整的记录对象
|
||||
const newRecord = {
|
||||
id: Date.now().toString(), // 使用时间戳作为唯一ID
|
||||
timestamp: new Date().toISOString(),
|
||||
model: record.model || '',
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt || '',
|
||||
size: record.size || '',
|
||||
quality: record.quality || 'standard',
|
||||
style: record.style || 'natural',
|
||||
images: record.images,
|
||||
};
|
||||
|
||||
setHistory((prev) => {
|
||||
// 添加新记录到开头,并限制最大数量
|
||||
const updatedHistory = [newRecord, ...prev].slice(0, maxItems);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 删除单条历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
*/
|
||||
const deleteHistoryRecord = useCallback(
|
||||
(recordId) => {
|
||||
setHistory((prev) => {
|
||||
const updatedHistory = prev.filter((item) => item.id !== recordId);
|
||||
// 保存到本地存储
|
||||
saveHistory(updatedHistory);
|
||||
return updatedHistory;
|
||||
});
|
||||
},
|
||||
[saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 清空所有历史记录
|
||||
*/
|
||||
const clearAllHistory = useCallback(() => {
|
||||
setHistory([]);
|
||||
// 从本地存储中删除
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Failed to clear history from localStorage:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 根据ID获取历史记录
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 历史记录对象
|
||||
*/
|
||||
const getHistoryRecordById = useCallback(
|
||||
(recordId) => {
|
||||
return history.find((item) => item.id === recordId) || null;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 从历史记录中加载参数
|
||||
* @param {string} recordId 记录ID
|
||||
* @returns {Object|null} 生成参数对象
|
||||
*/
|
||||
const loadParamsFromHistory = useCallback(
|
||||
(recordId) => {
|
||||
const record = getHistoryRecordById(recordId);
|
||||
if (!record) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
model: record.model,
|
||||
prompt: record.prompt,
|
||||
negativePrompt: record.negativePrompt,
|
||||
size: record.size,
|
||||
quality: record.quality,
|
||||
style: record.style,
|
||||
images: record.images,
|
||||
};
|
||||
},
|
||||
[getHistoryRecordById],
|
||||
);
|
||||
|
||||
/**
|
||||
* 搜索历史记录
|
||||
* @param {string} keyword 搜索关键词
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const searchHistory = useCallback(
|
||||
(keyword) => {
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
const searchTerm = keyword.toLowerCase().trim();
|
||||
return history.filter(
|
||||
(item) =>
|
||||
item.prompt.toLowerCase().includes(searchTerm) ||
|
||||
(item.negativePrompt &&
|
||||
item.negativePrompt.toLowerCase().includes(searchTerm)) ||
|
||||
item.model.toLowerCase().includes(searchTerm),
|
||||
);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按时间范围过滤历史记录
|
||||
* @param {Date} startDate 开始时间
|
||||
* @param {Date} endDate 结束时间
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByDate = useCallback(
|
||||
(startDate, endDate) => {
|
||||
if (!startDate && !endDate) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => {
|
||||
const itemDate = new Date(item.timestamp);
|
||||
|
||||
if (startDate && itemDate < startDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (endDate && itemDate > endDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 按模型过滤历史记录
|
||||
* @param {string} modelName 模型名称
|
||||
* @returns {Array} 符合条件的历史记录数组
|
||||
*/
|
||||
const filterHistoryByModel = useCallback(
|
||||
(modelName) => {
|
||||
if (!modelName || !modelName.trim()) {
|
||||
return history;
|
||||
}
|
||||
|
||||
return history.filter((item) => item.model === modelName);
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 导出历史记录为JSON
|
||||
* @returns {string} JSON格式的历史记录
|
||||
*/
|
||||
const exportHistory = useCallback(() => {
|
||||
return JSON.stringify(history, null, 2);
|
||||
}, [history]);
|
||||
|
||||
/**
|
||||
* 导入历史记录
|
||||
* @param {string} jsonData JSON格式的历史记录数据
|
||||
* @returns {boolean} 是否导入成功
|
||||
*/
|
||||
const importHistory = useCallback(
|
||||
(jsonData) => {
|
||||
try {
|
||||
const importedData = JSON.parse(jsonData);
|
||||
|
||||
// 验证导入的数据格式
|
||||
if (!Array.isArray(importedData)) {
|
||||
throw new Error('Invalid history data format');
|
||||
}
|
||||
|
||||
// 验证每条记录的格式
|
||||
const validRecords = importedData.filter(
|
||||
(record) =>
|
||||
record.id &&
|
||||
record.timestamp &&
|
||||
record.prompt &&
|
||||
Array.isArray(record.images),
|
||||
);
|
||||
|
||||
if (validRecords.length === 0) {
|
||||
throw new Error('No valid history records found');
|
||||
}
|
||||
|
||||
// 合并现有历史记录,避免重复,并限制最大数量
|
||||
const combinedRecords = [...validRecords, ...history];
|
||||
|
||||
// 去重(基于ID)
|
||||
const uniqueRecords = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const record of combinedRecords) {
|
||||
if (!seenIds.has(record.id)) {
|
||||
seenIds.add(record.id);
|
||||
uniqueRecords.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
// 按时间戳排序(最新的在前)
|
||||
uniqueRecords.sort(
|
||||
(a, b) => new Date(b.timestamp) - new Date(a.timestamp),
|
||||
);
|
||||
|
||||
// 限制最大数量
|
||||
const finalRecords = uniqueRecords.slice(0, maxItems);
|
||||
|
||||
// 更新状态并保存
|
||||
setHistory(finalRecords);
|
||||
saveHistory(finalRecords);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Failed to import history:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[history, maxItems, saveHistory],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取最近使用的提示词列表
|
||||
* @param {number} limit 最大返回数量
|
||||
* @returns {Array} 提示词数组
|
||||
*/
|
||||
const getRecentPrompts = useCallback(
|
||||
(limit = 10) => {
|
||||
const prompts = [];
|
||||
const seenPrompts = new Set();
|
||||
|
||||
for (const item of history) {
|
||||
if (item.prompt && !seenPrompts.has(item.prompt)) {
|
||||
seenPrompts.add(item.prompt);
|
||||
prompts.push(item.prompt);
|
||||
|
||||
if (prompts.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prompts;
|
||||
},
|
||||
[history],
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取历史记录统计信息
|
||||
* @returns {Object} 统计信息
|
||||
*/
|
||||
const getHistoryStats = useCallback(() => {
|
||||
const stats = {
|
||||
totalRecords: history.length,
|
||||
models: {},
|
||||
sizes: {},
|
||||
recentActivity:
|
||||
history.length > 0 ? new Date(history[0].timestamp) : null,
|
||||
};
|
||||
|
||||
// 统计各模型和尺寸的使用次数
|
||||
history.forEach((item) => {
|
||||
// 模型统计
|
||||
if (item.model) {
|
||||
stats.models[item.model] = (stats.models[item.model] || 0) + 1;
|
||||
}
|
||||
|
||||
// 尺寸统计
|
||||
if (item.size) {
|
||||
stats.sizes[item.size] = (stats.sizes[item.size] || 0) + 1;
|
||||
}
|
||||
});
|
||||
|
||||
return stats;
|
||||
}, [history]);
|
||||
|
||||
return {
|
||||
// 状态
|
||||
history,
|
||||
isLoading,
|
||||
|
||||
// 操作方法
|
||||
addHistoryRecord,
|
||||
deleteHistoryRecord,
|
||||
clearAllHistory,
|
||||
getHistoryRecordById,
|
||||
loadParamsFromHistory,
|
||||
searchHistory,
|
||||
filterHistoryByDate,
|
||||
filterHistoryByModel,
|
||||
exportHistory,
|
||||
importHistory,
|
||||
getRecentPrompts,
|
||||
getHistoryStats,
|
||||
loadHistory,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageHistory;
|
||||
@@ -1,276 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 导入模型判断函数
|
||||
import { IsImageGenerationModel } from '../../../common/model';
|
||||
|
||||
// 定义支持的图片生成模型列表
|
||||
const IMAGE_GENERATION_MODELS = [
|
||||
{
|
||||
value: 'dall-e-3',
|
||||
label: 'DALL-E 3',
|
||||
vendor: 'OpenAI',
|
||||
description: '最新一代DALL-E模型,生成高质量、详细的图像',
|
||||
recommended: true,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1024x1792', '1792x1024'],
|
||||
supportsQuality: true,
|
||||
maxImages: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'dall-e-2',
|
||||
label: 'DALL-E 2',
|
||||
vendor: 'OpenAI',
|
||||
description: '较早的DALL-E模型,平衡效果和速度',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['256x256', '512x512', '1024x1024'],
|
||||
supportsQuality: false,
|
||||
maxImages: 10,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'gpt-image-1',
|
||||
label: 'GPT-4V Image',
|
||||
vendor: 'OpenAI',
|
||||
description: '基于GPT-4V的图像生成能力',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024'],
|
||||
supportsQuality: true,
|
||||
maxImages: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'imagen-3',
|
||||
label: 'Imagen 3',
|
||||
vendor: 'Google',
|
||||
description: 'Google最新的图像生成模型,擅长文本理解',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1792x1024', '1024x1792'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'flux.1-schnell',
|
||||
label: 'FLUX.1 Schnell',
|
||||
vendor: 'Black Forest Labs',
|
||||
description: '快速版FLUX.1模型,生成速度快',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1344x1024', '1024x1344'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: 'flux.1-dev',
|
||||
label: 'FLUX.1 Dev',
|
||||
vendor: 'Black Forest Labs',
|
||||
description: '开发版FLUX.1模型,质量更高',
|
||||
recommended: false,
|
||||
capabilities: {
|
||||
sizes: ['1024x1024', '1344x1024', '1024x1344'],
|
||||
supportsQuality: true,
|
||||
maxImages: 4,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// 定义图片尺寸选项
|
||||
const IMAGE_SIZES = [
|
||||
{ value: '256x256', label: '256×256', description: '最小尺寸,生成速度最快' },
|
||||
{
|
||||
value: '512x512',
|
||||
label: '512×512',
|
||||
description: '中等尺寸,平衡质量和速度',
|
||||
},
|
||||
{ value: '1024x1024', label: '1024×1024', description: '标准高清尺寸' },
|
||||
{
|
||||
value: '1024x1792',
|
||||
label: '1024×1792 (9:16)',
|
||||
description: '纵向比例,适合手机壁纸',
|
||||
},
|
||||
{
|
||||
value: '1792x1024',
|
||||
label: '1792×1024 (16:9)',
|
||||
description: '横向比例,适合桌面壁纸',
|
||||
},
|
||||
{ value: '1344x1024', label: '1344×1024', description: '宽屏比例' },
|
||||
{ value: '1024x1344', label: '1024×1344', description: '竖屏比例' },
|
||||
];
|
||||
|
||||
// 定义图片质量选项
|
||||
const IMAGE_QUALITY = [
|
||||
{ value: 'standard', label: '标准', description: '标准质量,速度较快' },
|
||||
{ value: 'hd', label: '高清', description: '更高质量,细节更丰富' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 图像生成模型管理钩子
|
||||
* @returns {Object} 模型选择相关状态和方法
|
||||
*/
|
||||
const useImageModel = () => {
|
||||
const { t: _t } = useTranslation();
|
||||
|
||||
// 获取推荐模型(默认选择第一个推荐的模型)
|
||||
const getRecommendedModel = () => {
|
||||
const recommended = IMAGE_GENERATION_MODELS.find(
|
||||
(model) => model.recommended,
|
||||
);
|
||||
return recommended ? recommended.value : IMAGE_GENERATION_MODELS[0].value;
|
||||
};
|
||||
|
||||
// 状态管理
|
||||
const [selectedModel, setSelectedModel] = useState(() => {
|
||||
// 尝试从localStorage获取上次选择的模型
|
||||
const savedModel = localStorage.getItem('selectedImageModel');
|
||||
return savedModel && IsImageGenerationModel(savedModel)
|
||||
? savedModel
|
||||
: getRecommendedModel();
|
||||
});
|
||||
|
||||
const [selectedSize, setSelectedSize] = useState('1024x1024');
|
||||
const [selectedQuality, setSelectedQuality] = useState('standard');
|
||||
|
||||
// 当模型改变时,更新可用的尺寸和质量设置
|
||||
useEffect(() => {
|
||||
// 保存选择的模型到localStorage
|
||||
localStorage.setItem('selectedImageModel', selectedModel);
|
||||
|
||||
// 获取当前模型的能力
|
||||
const currentModel = IMAGE_GENERATION_MODELS.find(
|
||||
(m) => m.value === selectedModel,
|
||||
);
|
||||
|
||||
if (currentModel) {
|
||||
// 检查当前选择的尺寸是否可用,如果不可用则选择第一个可用尺寸
|
||||
if (!currentModel.capabilities.sizes.includes(selectedSize)) {
|
||||
setSelectedSize(currentModel.capabilities.sizes[0]);
|
||||
}
|
||||
|
||||
// 如果模型不支持质量选择,确保质量设置为standard
|
||||
if (
|
||||
!currentModel.capabilities.supportsQuality &&
|
||||
selectedQuality !== 'standard'
|
||||
) {
|
||||
setSelectedQuality('standard');
|
||||
}
|
||||
}
|
||||
}, [selectedModel]);
|
||||
|
||||
// 获取当前选中模型的详细信息
|
||||
const getCurrentModelInfo = useCallback(() => {
|
||||
return (
|
||||
IMAGE_GENERATION_MODELS.find((model) => model.value === selectedModel) ||
|
||||
IMAGE_GENERATION_MODELS[0]
|
||||
);
|
||||
}, [selectedModel]);
|
||||
|
||||
// 获取当前模型可用的尺寸选项
|
||||
const getAvailableSizes = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return IMAGE_SIZES.filter((size) =>
|
||||
modelInfo.capabilities.sizes.includes(size.value),
|
||||
);
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 检查当前模型是否支持质量选择
|
||||
const supportsQualityOption = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return modelInfo.capabilities.supportsQuality;
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 获取当前模型支持的最大图片数量
|
||||
const getMaxImages = useCallback(() => {
|
||||
const modelInfo = getCurrentModelInfo();
|
||||
return modelInfo.capabilities.maxImages;
|
||||
}, [getCurrentModelInfo]);
|
||||
|
||||
// 按厂商分组模型
|
||||
const getModelsByVendor = useCallback(() => {
|
||||
const grouped = {};
|
||||
IMAGE_GENERATION_MODELS.forEach((model) => {
|
||||
if (!grouped[model.vendor]) {
|
||||
grouped[model.vendor] = [];
|
||||
}
|
||||
grouped[model.vendor].push(model);
|
||||
});
|
||||
return grouped;
|
||||
}, []);
|
||||
|
||||
// 获取模型描述信息
|
||||
const getModelDescription = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.description : '';
|
||||
}, []);
|
||||
|
||||
// 获取模型厂商信息
|
||||
const getVendorInfo = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.vendor : '';
|
||||
}, []);
|
||||
|
||||
// 检查模型是否为推荐模型
|
||||
const isRecommendedModel = useCallback((modelValue) => {
|
||||
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
|
||||
return model ? model.recommended : false;
|
||||
}, []);
|
||||
|
||||
return {
|
||||
// 模型列表和信息
|
||||
models: IMAGE_GENERATION_MODELS,
|
||||
modelOptions: IMAGE_GENERATION_MODELS.map((model) => ({
|
||||
value: model.value,
|
||||
label: model.label,
|
||||
vendor: model.vendor,
|
||||
recommended: model.recommended,
|
||||
})),
|
||||
|
||||
// 状态和setter
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
selectedSize,
|
||||
setSelectedSize,
|
||||
selectedQuality,
|
||||
setSelectedQuality,
|
||||
|
||||
// 尺寸和质量选项
|
||||
sizeOptions: IMAGE_SIZES,
|
||||
qualityOptions: IMAGE_QUALITY,
|
||||
|
||||
// 功能方法
|
||||
getCurrentModelInfo,
|
||||
getAvailableSizes,
|
||||
supportsQualityOption,
|
||||
getMaxImages,
|
||||
getModelsByVendor,
|
||||
getModelDescription,
|
||||
getVendorInfo,
|
||||
isRecommendedModel,
|
||||
};
|
||||
};
|
||||
|
||||
export default useImageModel;
|
||||
@@ -1,314 +0,0 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
|
||||
/**
|
||||
* 错误类型枚举
|
||||
*/
|
||||
export const ERROR_TYPES = {
|
||||
NETWORK: 'network',
|
||||
VALIDATION: 'validation',
|
||||
API: 'api',
|
||||
RATE_LIMIT: 'rate_limit',
|
||||
CREDIT: 'credit',
|
||||
UNKNOWN: 'unknown',
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载阶段枚举
|
||||
*/
|
||||
export const LOADING_STAGES = {
|
||||
IDLE: 'idle',
|
||||
PROCESSING: 'processing',
|
||||
GENERATING: 'generating',
|
||||
COMPLETING: 'completing',
|
||||
};
|
||||
|
||||
/**
|
||||
* 图片状态管理钩子
|
||||
* 用于管理图片生成过程中的加载状态、错误处理、进度显示等
|
||||
*/
|
||||
const useImageStatus = () => {
|
||||
// 状态管理
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loadingStage, setLoadingStage] = useState(LOADING_STAGES.IDLE);
|
||||
const [error, setError] = useState(null);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [successMessage, setSuccessMessage] = useState('');
|
||||
const [notification, setNotification] = useState(null);
|
||||
|
||||
// 重置状态
|
||||
const resetStatus = useCallback(() => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError(null);
|
||||
setProgress(0);
|
||||
setSuccessMessage('');
|
||||
}, []);
|
||||
|
||||
// 设置加载状态
|
||||
const setLoading = useCallback((stage, customProgress) => {
|
||||
setIsLoading(true);
|
||||
setLoadingStage(stage || LOADING_STAGES.PROCESSING);
|
||||
setError(null);
|
||||
setSuccessMessage('');
|
||||
if (typeof customProgress !== 'undefined') {
|
||||
setProgress(customProgress);
|
||||
} else {
|
||||
// 根据阶段设置默认进度
|
||||
const stageProgress = {
|
||||
[LOADING_STAGES.IDLE]: 0,
|
||||
[LOADING_STAGES.PROCESSING]: 25,
|
||||
[LOADING_STAGES.GENERATING]: 50,
|
||||
[LOADING_STAGES.COMPLETING]: 75,
|
||||
};
|
||||
setProgress(stageProgress[stage] || 0);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 设置错误
|
||||
const setErrorState = useCallback(
|
||||
(message, type = ERROR_TYPES.UNKNOWN, details = {}) => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError({
|
||||
message,
|
||||
type,
|
||||
details,
|
||||
});
|
||||
setProgress(0);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 设置成功
|
||||
const setSuccess = useCallback((message = '') => {
|
||||
setIsLoading(false);
|
||||
setLoadingStage(LOADING_STAGES.IDLE);
|
||||
setError(null);
|
||||
setProgress(100);
|
||||
setSuccessMessage(message);
|
||||
|
||||
// 如果有成功消息,短暂显示通知
|
||||
if (message) {
|
||||
showNotification(message, 'success');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 更新进度
|
||||
const updateProgress = useCallback((newProgress) => {
|
||||
setProgress(Math.min(Math.max(0, newProgress), 100));
|
||||
}, []);
|
||||
|
||||
// 显示通知
|
||||
const showNotification = useCallback(
|
||||
(message, type = 'info', duration = 3000) => {
|
||||
setNotification({
|
||||
message,
|
||||
type,
|
||||
duration,
|
||||
id: Date.now(),
|
||||
});
|
||||
|
||||
// 自动清除通知
|
||||
setTimeout(() => {
|
||||
setNotification(null);
|
||||
}, duration);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 清除通知
|
||||
const clearNotification = useCallback(() => {
|
||||
setNotification(null);
|
||||
}, []);
|
||||
|
||||
// 根据错误类型获取建议操作
|
||||
const getErrorAction = useCallback((errorType) => {
|
||||
const actionMap = {
|
||||
[ERROR_TYPES.NETWORK]: {
|
||||
label: '重试连接',
|
||||
type: 'retry',
|
||||
},
|
||||
[ERROR_TYPES.VALIDATION]: {
|
||||
label: '修改参数',
|
||||
type: 'edit',
|
||||
},
|
||||
[ERROR_TYPES.API]: {
|
||||
label: '查看详情',
|
||||
type: 'details',
|
||||
},
|
||||
[ERROR_TYPES.RATE_LIMIT]: {
|
||||
label: '稍后重试',
|
||||
type: 'wait',
|
||||
},
|
||||
[ERROR_TYPES.CREDIT]: {
|
||||
label: '充值',
|
||||
type: 'recharge',
|
||||
},
|
||||
[ERROR_TYPES.UNKNOWN]: {
|
||||
label: '联系支持',
|
||||
type: 'support',
|
||||
},
|
||||
};
|
||||
|
||||
return actionMap[errorType] || actionMap[ERROR_TYPES.UNKNOWN];
|
||||
}, []);
|
||||
|
||||
// 根据加载阶段获取描述文本
|
||||
const getStageText = useCallback((stage) => {
|
||||
const stageTextMap = {
|
||||
[LOADING_STAGES.IDLE]: '准备中...',
|
||||
[LOADING_STAGES.PROCESSING]: '处理提示词...',
|
||||
[LOADING_STAGES.GENERATING]: '正在生成图像...',
|
||||
[LOADING_STAGES.COMPLETING]: '优化图片质量...',
|
||||
};
|
||||
|
||||
return stageTextMap[stage] || stageTextMap[LOADING_STAGES.IDLE];
|
||||
}, []);
|
||||
|
||||
// 格式化错误消息
|
||||
const formatErrorMessage = useCallback((errorObj) => {
|
||||
if (!errorObj) return '';
|
||||
|
||||
const { message, type, details } = errorObj;
|
||||
|
||||
// 特定错误类型的格式化
|
||||
if (type === ERROR_TYPES.VALIDATION && details.field) {
|
||||
return `${details.field}: ${message}`;
|
||||
}
|
||||
|
||||
if (type === ERROR_TYPES.API && details.code) {
|
||||
return `${message} (错误码: ${details.code})`;
|
||||
}
|
||||
|
||||
return message;
|
||||
}, []);
|
||||
|
||||
// 处理API错误响应
|
||||
const handleApiError = useCallback(
|
||||
(apiResponse) => {
|
||||
if (!apiResponse) {
|
||||
return setErrorState('未知错误,请重试', ERROR_TYPES.UNKNOWN);
|
||||
}
|
||||
|
||||
const { error, status } = apiResponse;
|
||||
|
||||
if (!error) {
|
||||
return setErrorState('API返回异常,请重试', ERROR_TYPES.API);
|
||||
}
|
||||
|
||||
// 根据状态码和错误信息判断错误类型
|
||||
if (status === 429) {
|
||||
return setErrorState(
|
||||
error.message || '请求过于频繁,请稍后重试',
|
||||
ERROR_TYPES.RATE_LIMIT,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 400 && error.validationErrors) {
|
||||
return setErrorState(
|
||||
error.message || '参数验证失败',
|
||||
ERROR_TYPES.VALIDATION,
|
||||
{ status, validationErrors: error.validationErrors },
|
||||
);
|
||||
}
|
||||
|
||||
if (status === 402) {
|
||||
return setErrorState(
|
||||
error.message || '余额不足,请充值',
|
||||
ERROR_TYPES.CREDIT,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
// 网络相关错误
|
||||
if (status >= 500 || status === 0) {
|
||||
return setErrorState(
|
||||
error.message || '网络错误,请检查连接后重试',
|
||||
ERROR_TYPES.NETWORK,
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
// 其他API错误
|
||||
return setErrorState(error.message || 'API请求失败', ERROR_TYPES.API, {
|
||||
status,
|
||||
});
|
||||
},
|
||||
[setErrorState],
|
||||
);
|
||||
|
||||
// 导出的状态和方法
|
||||
const statusProps = useMemo(
|
||||
() => ({
|
||||
// 状态
|
||||
isLoading,
|
||||
loadingStage,
|
||||
error,
|
||||
progress,
|
||||
successMessage,
|
||||
notification,
|
||||
|
||||
// 操作方法
|
||||
resetStatus,
|
||||
setLoading,
|
||||
setErrorState,
|
||||
setSuccess,
|
||||
updateProgress,
|
||||
showNotification,
|
||||
clearNotification,
|
||||
|
||||
// 辅助方法
|
||||
getErrorAction,
|
||||
getStageText,
|
||||
formatErrorMessage,
|
||||
handleApiError,
|
||||
|
||||
// 常量
|
||||
ERROR_TYPES,
|
||||
LOADING_STAGES,
|
||||
}),
|
||||
[
|
||||
isLoading,
|
||||
loadingStage,
|
||||
error,
|
||||
progress,
|
||||
successMessage,
|
||||
notification,
|
||||
resetStatus,
|
||||
setLoading,
|
||||
setErrorState,
|
||||
setSuccess,
|
||||
updateProgress,
|
||||
showNotification,
|
||||
clearNotification,
|
||||
getErrorAction,
|
||||
getStageText,
|
||||
formatErrorMessage,
|
||||
handleApiError,
|
||||
],
|
||||
);
|
||||
|
||||
return statusProps;
|
||||
};
|
||||
|
||||
export default useImageStatus;
|
||||
@@ -19,7 +19,27 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
import { buildImageRequestBody } from '../../constants/imageModelCapabilities';
|
||||
import i18next from 'i18next';
|
||||
import { pollDelay } from '../video/videoCreation';
|
||||
|
||||
// ids= 批量查询上限(GET /api/images/tasks?ids=,后端限制 20)
|
||||
const IDS_QUERY_LIMIT = 20;
|
||||
|
||||
const isDocumentHidden = () =>
|
||||
typeof document !== 'undefined' && document.visibilityState === 'hidden';
|
||||
|
||||
/** 提交 / 查询失败的统一结构:{ code, message, data, status }(message 为可读文案)。 */
|
||||
const toRequestError = (error) => {
|
||||
const body = error?.response?.data || error?.data || {};
|
||||
const status = error?.response?.status || 0;
|
||||
let message = body.message || body.error?.message || '';
|
||||
if (!message) {
|
||||
message = error?.response
|
||||
? error?.message || ''
|
||||
: i18next.t('网络异常,请稍后重试');
|
||||
}
|
||||
return { code: body.code || '', message, data: body.data, status };
|
||||
};
|
||||
|
||||
/**
|
||||
* 图片生成任务管理 Hook
|
||||
@@ -31,14 +51,17 @@ export const useImageTaskManagement = () => {
|
||||
// 加载状态
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// 轮询定时器
|
||||
// 轮询:一个定时器用 ids= 批量查询全部进行中任务(3s → 5s → 10s 退避,页面隐藏时降频)
|
||||
const pollingTimerRef = useRef(null);
|
||||
const pollRef = useRef(null);
|
||||
const pollStepRef = useRef(0);
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
// 正在轮询的任务ID集合
|
||||
const pollingTasksRef = useRef(new Set());
|
||||
|
||||
// 轮询失败计数器
|
||||
const pollingErrorCountRef = useRef(new Map());
|
||||
// 上次轮询到的状态签名(status|progress),无变化时逐步退避
|
||||
const lastSeenRef = useRef(new Map());
|
||||
|
||||
/**
|
||||
* 将后端任务数据转换为前端格式
|
||||
@@ -50,6 +73,8 @@ export const useImageTaskManagement = () => {
|
||||
let imageBase64 = null; // 标记是否有base64数据(用于刷新链接功能)
|
||||
let sourceImageUrl = null; // 图生图的原图URL
|
||||
let sourceImageBase64 = null; // 标记是否有原图base64数据
|
||||
// 首张结果现在能否以 task:// 引用用作参考图(服务端判定,前端不自行推断)
|
||||
let reusableAsInput = false;
|
||||
let prompt = '';
|
||||
let width = 1024;
|
||||
let height = 1024;
|
||||
@@ -78,6 +103,7 @@ export const useImageTaskManagement = () => {
|
||||
if (firstImage.b64_json) {
|
||||
imageBase64 = true; // 只保存标记,表示后端有base64数据可用
|
||||
}
|
||||
reusableAsInput = firstImage.reusable_as_input === true;
|
||||
}
|
||||
// 注意:任务处理中时data只包含请求参数,没有图片URL是正常的
|
||||
|
||||
@@ -160,6 +186,13 @@ export const useImageTaskManagement = () => {
|
||||
n: taskData.n,
|
||||
negativePrompt: taskData.negative_prompt || taskData.negativePrompt,
|
||||
taskData: taskData,
|
||||
reusableAsInput,
|
||||
// 任务返回的退款 / 估价 / 可取消标记(WP A2-2)
|
||||
refundedQuota: Number(backendTask.refunded_quota) || 0,
|
||||
quotedQuota: Number(backendTask.quoted_quota) || 0,
|
||||
cancelable: backendTask.cancelable,
|
||||
// 参数快照(仅任务详情返回;复用参数 / 再生成优先使用)
|
||||
request: backendTask.request || null,
|
||||
};
|
||||
|
||||
// 如果是成功状态但没有图片URL也没有base64,打印警告
|
||||
@@ -174,86 +207,106 @@ export const useImageTaskManagement = () => {
|
||||
return convertedTask;
|
||||
}, []);
|
||||
|
||||
// 添加新任务
|
||||
const addTask = useCallback(
|
||||
async (taskData) => {
|
||||
setLoading(true);
|
||||
// 轮询调度:只保留一个定时器
|
||||
const schedulePoll = useCallback((delay) => {
|
||||
clearTimeout(pollingTimerRef.current);
|
||||
pollingTimerRef.current = null;
|
||||
if (!mountedRef.current || pollingTasksRef.current.size === 0) return;
|
||||
const wait =
|
||||
delay !== undefined
|
||||
? delay
|
||||
: pollDelay(pollStepRef.current, isDocumentHidden());
|
||||
pollingTimerRef.current = setTimeout(() => pollRef.current?.(), wait);
|
||||
}, []);
|
||||
|
||||
// 开始跟踪进行中的任务(新任务重置退避,尽快拿到第一次状态)
|
||||
const trackTasks = useCallback(
|
||||
(ids) => {
|
||||
let added = false;
|
||||
ids.forEach((id) => {
|
||||
if (id && !pollingTasksRef.current.has(id)) {
|
||||
pollingTasksRef.current.add(id);
|
||||
added = true;
|
||||
}
|
||||
});
|
||||
if (!added) return;
|
||||
pollStepRef.current = 0;
|
||||
schedulePoll();
|
||||
},
|
||||
[schedulePoll],
|
||||
);
|
||||
|
||||
/**
|
||||
* 提交图像生成(payload 由调用方按 schema 构造,见 hooks/image/imageCreation.buildImageRequest)。
|
||||
*
|
||||
* @returns {Promise<{ ok: true, taskId: string } | { ok: false, code: string, message: string, data?: object, status: number }>}
|
||||
* 失败不弹提示,由调用方按 code(如 too_many_running_tasks)处理。
|
||||
*/
|
||||
const addTask = useCallback(
|
||||
async (payload) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const modelName = taskData.model || 'sora_image';
|
||||
let requestData = buildImageRequestBody(modelName, {
|
||||
prompt: taskData.prompt,
|
||||
width: taskData.width,
|
||||
height: taskData.height,
|
||||
quality: taskData.quality,
|
||||
n: taskData.n,
|
||||
negativePrompt: taskData.negativePrompt,
|
||||
mode: taskData.mode || 'text-to-image',
|
||||
const response = await API.post('/api/images/generations', payload, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
|
||||
// 图生图模式:将图片转换为 base64
|
||||
if (taskData.mode === 'image-to-image' && taskData.referenceImage) {
|
||||
// 获取原始文件对象
|
||||
const file =
|
||||
taskData.referenceImage.fileInstance || taskData.referenceImage;
|
||||
|
||||
// 将文件转换为 base64
|
||||
const base64Image = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = (error) => reject(error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
requestData.image = base64Image;
|
||||
}
|
||||
|
||||
const response = await API.post('/api/images/generations', requestData);
|
||||
|
||||
console.log('创建任务响应:', response.data);
|
||||
|
||||
// 后端返回任务信息,不是图片URL
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
|
||||
// 转换为前端格式并添加到任务列表
|
||||
const newTask = convertBackendTask({
|
||||
id: backendTask.id,
|
||||
task_id: backendTask.task_id,
|
||||
status: backendTask.status,
|
||||
progress: backendTask.progress,
|
||||
created_at: backendTask.created_at,
|
||||
properties: {
|
||||
input: taskData.prompt,
|
||||
model: taskData.model,
|
||||
mode: taskData.mode || 'text-to-image',
|
||||
},
|
||||
});
|
||||
|
||||
setTasks((prev) => [newTask, ...prev]);
|
||||
|
||||
// 将任务添加到轮询列表;终态以服务端为准,前端不再合成本地超时失败
|
||||
pollingTasksRef.current.add(newTask.id);
|
||||
|
||||
showSuccess('图片生成任务已创建,正在生成中...');
|
||||
return newTask.id;
|
||||
} else {
|
||||
throw new Error('Invalid response format');
|
||||
if (!response.data?.success || !response.data?.data) {
|
||||
throw { data: response.data };
|
||||
}
|
||||
const backendTask = response.data.data;
|
||||
|
||||
// 转换为前端格式并添加到任务列表
|
||||
const newTask = convertBackendTask({
|
||||
id: backendTask.id,
|
||||
task_id: backendTask.task_id,
|
||||
status: backendTask.status,
|
||||
progress: backendTask.progress,
|
||||
created_at: backendTask.created_at,
|
||||
properties: { input: payload.prompt },
|
||||
data: {
|
||||
model: payload.model,
|
||||
prompt: payload.prompt,
|
||||
size: payload.size,
|
||||
n: payload.n,
|
||||
quality: payload.quality,
|
||||
negative_prompt: payload.negative_prompt,
|
||||
mode: payload.image ? 'image-to-image' : 'text-to-image',
|
||||
},
|
||||
});
|
||||
|
||||
setTasks((prev) => [newTask, ...prev]);
|
||||
|
||||
// 将任务添加到轮询列表;终态以服务端为准,前端不再合成本地超时失败
|
||||
trackTasks([newTask.id]);
|
||||
|
||||
showSuccess(i18next.t('图片生成任务已创建,正在生成中...'));
|
||||
return { ok: true, taskId: newTask.id };
|
||||
} catch (error) {
|
||||
console.error('创建图片生成任务失败:', error);
|
||||
showError(
|
||||
'图片生成失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
return null;
|
||||
return { ok: false, ...toRequestError(error) };
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[convertBackendTask],
|
||||
[convertBackendTask, trackTasks],
|
||||
);
|
||||
|
||||
/** 任务详情(GET /api/images/generations/:id,含参数快照 request);失败返回 null。 */
|
||||
const fetchTaskDetail = useCallback(async (taskId) => {
|
||||
if (!taskId) return null;
|
||||
try {
|
||||
const response = await API.get(
|
||||
`/api/images/generations/${encodeURIComponent(taskId)}`,
|
||||
{ skipErrorHandler: true },
|
||||
);
|
||||
return response.data?.success ? response.data.data || null : null;
|
||||
} catch (error) {
|
||||
console.warn('获取任务详情失败:', error);
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 更新任务状态
|
||||
const updateTaskStatus = useCallback(
|
||||
(taskId, status, additionalData = {}) => {
|
||||
@@ -297,7 +350,7 @@ export const useImageTaskManagement = () => {
|
||||
async (taskId, type = 'generated', silent = false) => {
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) {
|
||||
if (!silent) showError('任务不存在');
|
||||
if (!silent) showError(i18next.t('任务不存在'));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -338,18 +391,19 @@ export const useImageTaskManagement = () => {
|
||||
updateTask(taskId, { imageUrl: newUrl, imageBase64: null });
|
||||
}
|
||||
|
||||
if (!silent) showSuccess('链接已刷新');
|
||||
if (!silent) showSuccess(i18next.t('链接已刷新'));
|
||||
return true;
|
||||
} else {
|
||||
if (!silent) showError('刷新链接失败');
|
||||
if (!silent) showError(i18next.t('刷新链接失败'));
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('刷新URL失败:', error);
|
||||
if (!silent)
|
||||
showError(
|
||||
'刷新链接失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
i18next.t('刷新链接失败:{{message}}', {
|
||||
message: error.response?.data?.error?.message || error.message,
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@@ -422,7 +476,7 @@ export const useImageTaskManagement = () => {
|
||||
|
||||
// 立即从轮询列表中移除,停止轮询
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
lastSeenRef.current.delete(taskId);
|
||||
|
||||
// 如果任务正在处理中,调用后端取消API
|
||||
if (task && task.status === 'processing') {
|
||||
@@ -431,14 +485,14 @@ export const useImageTaskManagement = () => {
|
||||
`/api/images/generations/${taskId}/cancel`,
|
||||
);
|
||||
if (response.data?.success) {
|
||||
showSuccess('任务已取消');
|
||||
showSuccess(i18next.t('任务已取消'));
|
||||
} else {
|
||||
console.warn('后端取消任务失败:', response.data?.message);
|
||||
showSuccess('任务已从列表中移除');
|
||||
showSuccess(i18next.t('任务已从列表中移除'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('取消任务失败:', error);
|
||||
showSuccess('任务已从列表中移除');
|
||||
showSuccess(i18next.t('任务已从列表中移除'));
|
||||
}
|
||||
} else {
|
||||
// 已完成的任务,调用删除API(软删除)
|
||||
@@ -447,14 +501,14 @@ export const useImageTaskManagement = () => {
|
||||
`/api/images/generations/${taskId}`,
|
||||
);
|
||||
if (response.data?.success) {
|
||||
showSuccess('任务已删除');
|
||||
showSuccess(i18next.t('任务已删除'));
|
||||
} else {
|
||||
console.warn('后端删除任务失败:', response.data?.message);
|
||||
showSuccess('任务已从列表中移除');
|
||||
showSuccess(i18next.t('任务已从列表中移除'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除任务失败:', error);
|
||||
showSuccess('任务已从列表中移除');
|
||||
showSuccess(i18next.t('任务已从列表中移除'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -464,98 +518,6 @@ export const useImageTaskManagement = () => {
|
||||
[tasks],
|
||||
);
|
||||
|
||||
// 重试任务 - 使用原任务的参数创建新任务
|
||||
const retryTask = useCallback(
|
||||
async (taskId) => {
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) {
|
||||
showError('任务不存在');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 检查是否是图生图模式
|
||||
const isImageToImage = task.mode === 'image-to-image';
|
||||
|
||||
// 对于图生图任务,需要有原图数据
|
||||
if (isImageToImage) {
|
||||
// 检查是否有原图数据
|
||||
if (!task.sourceImageUrl) {
|
||||
showError('图生图任务缺少原图数据,无法重试。请重新上传图片');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 如果原图是COS URL(不是base64),无法直接重试
|
||||
if (!task.sourceImageUrl.startsWith('data:')) {
|
||||
showError(
|
||||
'图生图任务的原图已上传到云存储,无法直接重试。请重新上传图片',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// 构建请求数据 — 复用 capability registry 清洗
|
||||
const modelName = task.model || 'sora_image';
|
||||
let requestData = buildImageRequestBody(modelName, {
|
||||
prompt: task.prompt,
|
||||
width: task.width,
|
||||
height: task.height,
|
||||
quality: task.quality,
|
||||
n: task.n,
|
||||
negativePrompt: task.negativePrompt,
|
||||
mode: task.mode || 'text-to-image',
|
||||
});
|
||||
|
||||
// 图生图模式:添加原图数据
|
||||
if (isImageToImage && task.sourceImageUrl) {
|
||||
requestData.image = task.sourceImageUrl;
|
||||
}
|
||||
|
||||
const response = await API.post('/api/images/generations', requestData);
|
||||
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
|
||||
// 转换为前端格式并添加到任务列表
|
||||
const newTask = convertBackendTask({
|
||||
id: backendTask.id,
|
||||
task_id: backendTask.task_id,
|
||||
status: backendTask.status,
|
||||
progress: backendTask.progress,
|
||||
created_at: backendTask.created_at,
|
||||
properties: {
|
||||
input: task.prompt,
|
||||
model: task.model,
|
||||
mode: task.mode || 'text-to-image',
|
||||
},
|
||||
});
|
||||
|
||||
setTasks((prev) => [newTask, ...prev]);
|
||||
|
||||
// 将任务添加到轮询列表,并记录开始时间
|
||||
pollingTasksRef.current.add(newTask.id);
|
||||
|
||||
showSuccess('重试任务已创建,正在生成中...');
|
||||
return newTask.id;
|
||||
} else {
|
||||
throw new Error('Invalid response format');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('重试任务失败:', error);
|
||||
showError(
|
||||
'重试失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[tasks, convertBackendTask],
|
||||
);
|
||||
|
||||
// 刷新任务列表
|
||||
// autoRefreshUrls: 是否自动刷新成功任务的图片链接(默认 true,首次加载时使用)
|
||||
const refreshTasks = useCallback(
|
||||
@@ -564,8 +526,6 @@ export const useImageTaskManagement = () => {
|
||||
try {
|
||||
const response = await API.get('/api/images/tasks?page=1&page_size=50');
|
||||
|
||||
console.log('获取任务列表响应:', response.data);
|
||||
|
||||
if (response.data?.success && response.data?.data?.items) {
|
||||
const backendTasks = response.data.data.items;
|
||||
|
||||
@@ -576,15 +536,12 @@ export const useImageTaskManagement = () => {
|
||||
|
||||
setTasks(convertedTasks);
|
||||
|
||||
// 找出所有正在进行中的任务,添加到轮询列表
|
||||
convertedTasks.forEach((task) => {
|
||||
if (task.status === 'processing') {
|
||||
// 如果任务还没在轮询列表中,添加并记录开始时间
|
||||
if (!pollingTasksRef.current.has(task.id)) {
|
||||
pollingTasksRef.current.add(task.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
// 找出所有正在进行中的任务,加入批量轮询
|
||||
trackTasks(
|
||||
convertedTasks
|
||||
.filter((task) => task.status === 'processing')
|
||||
.map((task) => task.id),
|
||||
);
|
||||
|
||||
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
|
||||
if (autoRefreshUrls) {
|
||||
@@ -595,156 +552,126 @@ export const useImageTaskManagement = () => {
|
||||
}
|
||||
|
||||
if (showNotification) {
|
||||
showSuccess('刷新成功');
|
||||
showSuccess(i18next.t('刷新成功'));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('刷新任务列表失败:', error);
|
||||
if (showNotification) {
|
||||
showError(
|
||||
'刷新失败:' +
|
||||
(error.response?.data?.error?.message || error.message),
|
||||
i18next.t('刷新失败:{{message}}', {
|
||||
message: error.response?.data?.error?.message || error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[convertBackendTask, refreshAllSuccessUrls],
|
||||
[convertBackendTask, refreshAllSuccessUrls, trackTasks],
|
||||
);
|
||||
|
||||
// 轮询单个任务状态
|
||||
const pollTaskStatus = useCallback(
|
||||
async (taskId) => {
|
||||
try {
|
||||
const response = await API.get(`/api/images/generations/${taskId}`);
|
||||
|
||||
if (response.data?.success && response.data?.data) {
|
||||
const backendTask = response.data.data;
|
||||
const updatedTask = convertBackendTask(backendTask);
|
||||
|
||||
// 轮询成功,清除错误计数
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
|
||||
// 更新任务状态
|
||||
// 批量轮询进行中任务:GET /api/images/tasks?ids=(≤20 个 / 次,超出的轮转到下一次)
|
||||
const pollOnce = useCallback(async () => {
|
||||
const all = [...pollingTasksRef.current];
|
||||
const ids = all.slice(0, IDS_QUERY_LIMIT);
|
||||
if (ids.length === 0) return;
|
||||
// 轮转:本次查询的任务排到队尾,超过 20 个时其余任务下一次查询
|
||||
ids.forEach((id) => {
|
||||
pollingTasksRef.current.delete(id);
|
||||
pollingTasksRef.current.add(id);
|
||||
});
|
||||
let changed = false;
|
||||
try {
|
||||
const response = await API.get('/api/images/tasks', {
|
||||
params: { ids: ids.join(',') },
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (response.data?.success) {
|
||||
const items = response.data.data?.items || [];
|
||||
const updated = new Map();
|
||||
items.forEach((backendTask) => {
|
||||
const task = convertBackendTask(backendTask);
|
||||
updated.set(task.id, task);
|
||||
const sig = `${backendTask.status}|${backendTask.progress}`;
|
||||
if (lastSeenRef.current.get(task.id) !== sig) changed = true;
|
||||
lastSeenRef.current.set(task.id, sig);
|
||||
// 任务已完成(成功或失败):停止轮询
|
||||
if (task.status === 'success' || task.status === 'failed') {
|
||||
pollingTasksRef.current.delete(task.id);
|
||||
lastSeenRef.current.delete(task.id);
|
||||
}
|
||||
});
|
||||
// 查询结果里没有的任务(已删除 / 不存在):停止轮询并标记
|
||||
const missing = new Set(ids.filter((id) => !updated.has(id)));
|
||||
missing.forEach((id) => {
|
||||
pollingTasksRef.current.delete(id);
|
||||
lastSeenRef.current.delete(id);
|
||||
});
|
||||
if (mountedRef.current && (updated.size || missing.size)) {
|
||||
setTasks((prev) =>
|
||||
prev.map((task) => (task.id === taskId ? updatedTask : task)),
|
||||
prev.map((task) => {
|
||||
if (updated.has(task.id)) {
|
||||
// 列表接口不含详情字段:保留已加载的快照
|
||||
const next = updated.get(task.id);
|
||||
return next.request ? next : { ...next, request: task.request };
|
||||
}
|
||||
if (missing.has(task.id) && task.status === 'processing') {
|
||||
return {
|
||||
...task,
|
||||
status: 'failed',
|
||||
errorMessage: i18next.t('任务不存在'),
|
||||
};
|
||||
}
|
||||
return task;
|
||||
}),
|
||||
);
|
||||
|
||||
// 如果任务已完成(成功或失败),从轮询列表中移除
|
||||
if (
|
||||
updatedTask.status === 'success' ||
|
||||
updatedTask.status === 'failed'
|
||||
) {
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
}
|
||||
|
||||
return updatedTask;
|
||||
} else {
|
||||
// 非终态 API 错误只记录,不把本地状态伪造为失败;后端任务可能仍会成功并扣费。
|
||||
const errorCount =
|
||||
(pollingErrorCountRef.current.get(taskId) || 0) + 1;
|
||||
const errorMessage =
|
||||
response.data?.message || response.data?.error?.message || '';
|
||||
if (errorMessage.toLowerCase().includes('task not found')) {
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? {
|
||||
...task,
|
||||
status: 'failed',
|
||||
errorMessage: '任务不存在',
|
||||
}
|
||||
: task,
|
||||
),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
|
||||
if (errorCount === 3) {
|
||||
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`轮询任务 ${taskId} 状态失败:`, error);
|
||||
|
||||
// 增加错误计数
|
||||
const errorCount = (pollingErrorCountRef.current.get(taskId) || 0) + 1;
|
||||
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
|
||||
|
||||
// 如果是404错误,直接停止轮询
|
||||
if (error.response?.status === 404) {
|
||||
console.warn(`任务 ${taskId} 不存在,停止轮询`);
|
||||
pollingTasksRef.current.delete(taskId);
|
||||
pollingErrorCountRef.current.delete(taskId);
|
||||
|
||||
// 更新任务状态为失败
|
||||
setTasks((prev) =>
|
||||
prev.map((task) =>
|
||||
task.id === taskId
|
||||
? { ...task, status: 'failed', errorMessage: '任务不存在' }
|
||||
: task,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorCount === 3) {
|
||||
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
|
||||
}
|
||||
}
|
||||
},
|
||||
[convertBackendTask],
|
||||
);
|
||||
|
||||
// 轮询所有进行中的任务
|
||||
const pollAllTasks = useCallback(async () => {
|
||||
const tasksToPool = Array.from(pollingTasksRef.current);
|
||||
|
||||
if (tasksToPool.length === 0) {
|
||||
return;
|
||||
} catch (error) {
|
||||
// 非终态 API 错误只记录,不把本地状态伪造为失败;后端任务可能仍会成功并扣费。
|
||||
console.warn('轮询任务状态失败,将稍后重试:', error);
|
||||
}
|
||||
if (!mountedRef.current) return;
|
||||
pollStepRef.current = changed ? 0 : pollStepRef.current + 1;
|
||||
schedulePoll();
|
||||
}, [convertBackendTask, schedulePoll]);
|
||||
pollRef.current = pollOnce;
|
||||
|
||||
console.log('轮询任务:', tasksToPool);
|
||||
|
||||
// 并发轮询所有任务
|
||||
await Promise.all(tasksToPool.map((taskId) => pollTaskStatus(taskId)));
|
||||
}, [pollTaskStatus]);
|
||||
|
||||
// 启动轮询定时器
|
||||
// 挂载时加载任务列表;页面隐藏时降频,回到页面立即刷新
|
||||
useEffect(() => {
|
||||
// 组件挂载时加载任务列表
|
||||
mountedRef.current = true;
|
||||
refreshTasks();
|
||||
|
||||
// 设置定时器,每5秒轮询一次
|
||||
pollingTimerRef.current = setInterval(() => {
|
||||
pollAllTasks();
|
||||
}, 5000);
|
||||
|
||||
// 清理函数
|
||||
return () => {
|
||||
if (pollingTimerRef.current) {
|
||||
clearInterval(pollingTimerRef.current);
|
||||
const onVisibility = () => {
|
||||
if (pollingTasksRef.current.size === 0) return;
|
||||
if (isDocumentHidden()) {
|
||||
schedulePoll();
|
||||
} else {
|
||||
pollStepRef.current = 0;
|
||||
schedulePoll(0);
|
||||
}
|
||||
};
|
||||
}, [refreshTasks, pollAllTasks]);
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
clearTimeout(pollingTimerRef.current);
|
||||
document.removeEventListener('visibilitychange', onVisibility);
|
||||
};
|
||||
}, [refreshTasks, schedulePoll]);
|
||||
|
||||
// 清空所有任务
|
||||
const clearAllTasks = useCallback(() => {
|
||||
setTasks([]);
|
||||
showSuccess('已清空所有任务');
|
||||
showSuccess(i18next.t('已清空所有任务'));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
tasks,
|
||||
loading,
|
||||
addTask,
|
||||
fetchTaskDetail,
|
||||
updateTaskStatus,
|
||||
deleteTask,
|
||||
retryTask,
|
||||
refreshTasks,
|
||||
refreshTaskUrl,
|
||||
clearAllTasks,
|
||||
|
||||
@@ -19,7 +19,8 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { API, showError } from '../../helpers';
|
||||
import { MODEL_CATEGORY_NAMES } from '../../constants';
|
||||
import i18next from 'i18next';
|
||||
import { MODEL_CATEGORY_NAME_KEYS } from '../../constants';
|
||||
|
||||
/**
|
||||
* 加载模型分类数据的 Hook
|
||||
@@ -27,8 +28,9 @@ import { MODEL_CATEGORY_NAMES } from '../../constants';
|
||||
*/
|
||||
export const useModelCategories = () => {
|
||||
const [categories, setCategories] = useState([]);
|
||||
// 存中文键而非译文,由渲染处 t() 翻译,切换语言时才能跟着变
|
||||
const [categoryNames, setCategoryNames] = useState({
|
||||
...MODEL_CATEGORY_NAMES,
|
||||
...MODEL_CATEGORY_NAME_KEYS,
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
@@ -44,7 +46,7 @@ export const useModelCategories = () => {
|
||||
setCategories(categoriesData);
|
||||
|
||||
// 构建 category_key -> category_name 的映射
|
||||
const nameMap = { ...MODEL_CATEGORY_NAMES };
|
||||
const nameMap = { ...MODEL_CATEGORY_NAME_KEYS };
|
||||
categoriesData.forEach((cat) => {
|
||||
if (cat.category_key && cat.category_name) {
|
||||
nameMap[cat.category_key] = cat.category_name;
|
||||
@@ -52,7 +54,7 @@ export const useModelCategories = () => {
|
||||
});
|
||||
setCategoryNames(nameMap);
|
||||
} else {
|
||||
showError(message || '加载分类失败');
|
||||
showError(message || i18next.t('加载分类失败'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load categories:', error);
|
||||
|
||||
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { API, showError } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
import {
|
||||
MODEL_CATEGORY,
|
||||
inferModelCategory,
|
||||
@@ -77,8 +78,8 @@ export const useModelSelector = (category = null) => {
|
||||
// 使用 /api/user/models 接口,普通用户可访问
|
||||
const [modelsRes, pricingRes] = await Promise.all([
|
||||
API.get(`/api/user/models/?page_size=1000${categoryQuery}`),
|
||||
// discount_scope=personal:体验中心/模型选择器的调用恒按个人等级计费,
|
||||
// 企业 web 会话下若跟随会话作用域会把企业折扣价标给个人计费的调用
|
||||
// discount_scope=personal:体验中心/模型选择器的调用恒走个人计费(属于企业的用户按所属企业等级),
|
||||
// 企业 web 会话下若跟随会话作用域会标成当前所选企业的价格
|
||||
API.get('/api/pricing?discount_scope=personal').catch(() => ({
|
||||
data: { success: true, data: [] },
|
||||
})), // 如果pricing接口失败,使用空数组
|
||||
@@ -188,11 +189,13 @@ export const useModelSelector = (category = null) => {
|
||||
setFilteredModels(modelsWithCategory);
|
||||
}
|
||||
} else {
|
||||
showError(message || '获取模型列表失败');
|
||||
showError(message || i18next.t('获取模型列表失败'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载模型失败:', error);
|
||||
showError('加载模型失败: ' + error.message);
|
||||
showError(
|
||||
i18next.t('加载模型失败: {{message}}', { message: error.message }),
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -399,7 +399,11 @@ export const useModelsData = () => {
|
||||
if (res.data.success) {
|
||||
successCount++;
|
||||
} else {
|
||||
showError(`删除模型 ${selectedKeys[index].model_name} 失败: ${res.data.message}`,
|
||||
showError(
|
||||
t('删除模型 {{name}} 失败: {{message}}', {
|
||||
name: selectedKeys[index].model_name,
|
||||
message: res.data.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
|
||||
// 获取企业X-Org-Id header
|
||||
const getOrgHeaders = (orgId) => ({
|
||||
@@ -213,7 +214,7 @@ export function useOrgPromptRecords(orgId) {
|
||||
} else {
|
||||
setRecords([]);
|
||||
setTotal(0);
|
||||
setError(res.data.message || '查询失败');
|
||||
setError(res.data.message || i18next.t('查询失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
if (seq !== seqRef.current) return;
|
||||
@@ -267,7 +268,7 @@ export function useOrgMemberLogs(orgId) {
|
||||
} else {
|
||||
setLogs([]);
|
||||
setTotal(0);
|
||||
showError(res.data.message || '加载消耗明细失败');
|
||||
showError(res.data.message || i18next.t('加载消耗明细失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
@@ -326,7 +327,7 @@ export function useOrgLogsStat(orgId) {
|
||||
tpm: 0,
|
||||
has_time_range: false,
|
||||
});
|
||||
showError(res.data.message || '加载消耗统计失败');
|
||||
showError(res.data.message || i18next.t('加载消耗统计失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
@@ -369,7 +370,7 @@ export function useOrgMemberRanking(orgId) {
|
||||
setRanking(res.data.data || []);
|
||||
} else {
|
||||
setRanking([]);
|
||||
showError(res.data.message || '加载成员排行失败');
|
||||
showError(res.data.message || i18next.t('加载成员排行失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
|
||||
@@ -394,7 +394,7 @@ export const useApiRequest = (
|
||||
try {
|
||||
errorBody = await response.text();
|
||||
} catch (e) {
|
||||
errorBody = '无法读取错误响应体';
|
||||
errorBody = t('无法读取错误响应体');
|
||||
}
|
||||
|
||||
const errorInfo = handleApiError(
|
||||
@@ -505,7 +505,7 @@ export const useApiRequest = (
|
||||
error?.name === 'AbortError' && abortCtl.signal.aborted;
|
||||
const friendlyMessage = isWatchdogAbort
|
||||
? t('服务器长时间未响应,请求已自动中止,请重试')
|
||||
: t('请求发生错误: ') + (error?.message || '');
|
||||
: t('请求发生错误: {{message}}', { message: error?.message || '' });
|
||||
|
||||
const errorInfo = handleApiError(error);
|
||||
setDebugData((prev) => ({
|
||||
@@ -685,7 +685,9 @@ export const useApiRequest = (
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse SSE message:', error);
|
||||
const errorInfo = `解析错误: ${error.message}`;
|
||||
const errorInfo = t('解析错误: {{message}}', {
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
setDebugData((prev) => ({
|
||||
...prev,
|
||||
@@ -952,7 +954,8 @@ export const useApiRequest = (
|
||||
|
||||
setDebugData((prev) => ({
|
||||
...prev,
|
||||
response: 'Stream启动失败:\n' + JSON.stringify(errorInfo, null, 2),
|
||||
response:
|
||||
t('Stream启动失败:') + '\n' + JSON.stringify(errorInfo, null, 2),
|
||||
}));
|
||||
setActiveDebugTab(DEBUG_TABS.RESPONSE);
|
||||
|
||||
|
||||
@@ -231,7 +231,7 @@ export const useRedemptionsData = () => {
|
||||
showSuccess(t('已复制到剪贴板!'));
|
||||
} else {
|
||||
Modal.error({
|
||||
title: '无法复制到剪贴板,请手动复制',
|
||||
title: t('无法复制到剪贴板,请手动复制'),
|
||||
content: text,
|
||||
size: 'large',
|
||||
});
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
API,
|
||||
copy,
|
||||
isAdmin,
|
||||
isRoot,
|
||||
showError,
|
||||
showSuccess,
|
||||
timestamp2string,
|
||||
@@ -32,7 +33,25 @@ import { EVENTS, emit } from '../../helpers/eventBus';
|
||||
import { ITEMS_PER_PAGE } from '../../constants';
|
||||
import { useTableCompactMode } from '../common/useTableCompactMode';
|
||||
|
||||
export const useTaskLogsData = () => {
|
||||
const DEFAULT_TASK_RANGE_DAYS = 7;
|
||||
|
||||
const toUnixTimestamp = (value) => {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return Math.floor(value.getTime() / 1000);
|
||||
}
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : NaN;
|
||||
};
|
||||
|
||||
export const useTaskLogsData = ({
|
||||
organizationMode = false,
|
||||
sharedStartTimestamp,
|
||||
sharedEndTimestamp,
|
||||
sharedFilterRevision = 0,
|
||||
} = {}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Define column keys for selection
|
||||
@@ -43,7 +62,6 @@ export const useTaskLogsData = () => {
|
||||
FINISH_TIME: 'finish_time',
|
||||
DURATION: 'duration',
|
||||
CHANNEL: 'channel',
|
||||
PLATFORM: 'platform',
|
||||
TYPE: 'type',
|
||||
MODEL: 'model',
|
||||
TASK_ID: 'task_id',
|
||||
@@ -61,11 +79,15 @@ export const useTaskLogsData = () => {
|
||||
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
|
||||
|
||||
// User and admin
|
||||
const isAdminUser = isAdmin();
|
||||
const isAdminUser = !organizationMode && isAdmin();
|
||||
// 任务 ID 详情包含完整任务记录,仅系统超级管理员可查看;企业用户始终不可打开
|
||||
const isRootUser = !organizationMode && isRoot();
|
||||
// Role-specific storage key to prevent different roles from overwriting each other
|
||||
const STORAGE_KEY = isAdminUser
|
||||
? 'task-logs-table-columns-admin'
|
||||
: 'task-logs-table-columns-user';
|
||||
const STORAGE_KEY = organizationMode
|
||||
? 'task-logs-table-columns-organization'
|
||||
: isAdminUser
|
||||
? 'task-logs-table-columns-admin'
|
||||
: 'task-logs-table-columns-user';
|
||||
|
||||
// Modal state
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
@@ -81,15 +103,20 @@ export const useTaskLogsData = () => {
|
||||
// Form state
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
|
||||
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后
|
||||
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug)
|
||||
const usesSharedDateRange =
|
||||
organizationMode &&
|
||||
Number.isFinite(Number(sharedStartTimestamp)) &&
|
||||
Number.isFinite(Number(sharedEndTimestamp));
|
||||
|
||||
// 每次调用都返回"此刻"的默认时间范围,默认最近 7 天,避免任务页首屏
|
||||
// 只查当天而遗漏历史任务;返回 Date 对象以便日期控件正确显示。
|
||||
const getFreshDateRange = () => {
|
||||
const now = new Date();
|
||||
const zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
return [
|
||||
timestamp2string(zeroNow.getTime() / 1000),
|
||||
timestamp2string(now.getTime() / 1000 + 3600),
|
||||
];
|
||||
now.setSeconds(0, 0);
|
||||
const start = new Date(
|
||||
now.getTime() - DEFAULT_TASK_RANGE_DAYS * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
return [start, now];
|
||||
};
|
||||
|
||||
const getFreshInitValues = () => ({
|
||||
@@ -163,7 +190,6 @@ export const useTaskLogsData = () => {
|
||||
[COLUMN_KEYS.FINISH_TIME]: true,
|
||||
[COLUMN_KEYS.DURATION]: true,
|
||||
[COLUMN_KEYS.CHANNEL]: isAdminUser,
|
||||
[COLUMN_KEYS.PLATFORM]: true,
|
||||
[COLUMN_KEYS.TYPE]: true,
|
||||
[COLUMN_KEYS.MODEL]: true,
|
||||
[COLUMN_KEYS.TASK_ID]: true,
|
||||
@@ -216,12 +242,17 @@ export const useTaskLogsData = () => {
|
||||
// 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤
|
||||
const formValues = formApi ? formApi.getValues() : formInitValues;
|
||||
|
||||
// 处理时间范围:每次调用时取"此刻"的默认值,避免闭包陈旧
|
||||
// 企业页复用上方已经提交的时间范围;个人/平台任务页使用自己的日期控件。
|
||||
const [freshStart, freshEnd] = getFreshDateRange();
|
||||
let start_timestamp = freshStart;
|
||||
let end_timestamp = freshEnd;
|
||||
let start_timestamp = usesSharedDateRange
|
||||
? Number(sharedStartTimestamp)
|
||||
: freshStart;
|
||||
let end_timestamp = usesSharedDateRange
|
||||
? Number(sharedEndTimestamp)
|
||||
: freshEnd;
|
||||
|
||||
if (
|
||||
!usesSharedDateRange &&
|
||||
formValues.dateRange &&
|
||||
Array.isArray(formValues.dateRange) &&
|
||||
formValues.dateRange.length === 2
|
||||
@@ -305,8 +336,8 @@ export const useTaskLogsData = () => {
|
||||
start_timestamp,
|
||||
end_timestamp,
|
||||
} = getFormValues();
|
||||
let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
|
||||
let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
|
||||
let localStartTimestamp = toUnixTimestamp(start_timestamp);
|
||||
let localEndTimestamp = toUnixTimestamp(end_timestamp);
|
||||
// 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示
|
||||
if (
|
||||
Number.isFinite(localStartTimestamp) &&
|
||||
@@ -334,9 +365,11 @@ export const useTaskLogsData = () => {
|
||||
// 与使用日志对齐:管理员可按 user_id 过滤任务日志
|
||||
if (user_id) params.set('user_id', user_id);
|
||||
}
|
||||
const url = isAdminUser
|
||||
? `/api/task/?${params.toString()}`
|
||||
: `/api/task/self?${params.toString()}`;
|
||||
const url = organizationMode
|
||||
? `/api/org/tasks?${params.toString()}`
|
||||
: isAdminUser
|
||||
? `/api/task/?${params.toString()}`
|
||||
: `/api/task/self?${params.toString()}`;
|
||||
try {
|
||||
const res = await API.get(url);
|
||||
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
|
||||
@@ -421,7 +454,12 @@ export const useTaskLogsData = () => {
|
||||
parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
|
||||
setPageSize(localPageSize);
|
||||
loadLogs(1, localPageSize).then();
|
||||
}, []);
|
||||
}, [
|
||||
organizationMode,
|
||||
sharedStartTimestamp,
|
||||
sharedEndTimestamp,
|
||||
sharedFilterRevision,
|
||||
]);
|
||||
|
||||
// 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求
|
||||
const loadLogsRef = useRef(loadLogs);
|
||||
@@ -473,6 +511,8 @@ export const useTaskLogsData = () => {
|
||||
logCount,
|
||||
pageSize,
|
||||
isAdminUser,
|
||||
isRootUser,
|
||||
usesSharedDateRange,
|
||||
|
||||
// Modal state
|
||||
isModalOpen,
|
||||
|
||||
@@ -418,7 +418,7 @@ export const useLogsData = () => {
|
||||
if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
|
||||
expandDataLocal.push({
|
||||
key: t('渠道信息'),
|
||||
value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
|
||||
value: `${logs[i].channel} - ${logs[i].channel_name || t('[未知]')}`,
|
||||
});
|
||||
}
|
||||
if (other?.ws || other?.audio) {
|
||||
@@ -657,7 +657,7 @@ export const useLogsData = () => {
|
||||
const copyText = async (e, text) => {
|
||||
e.stopPropagation();
|
||||
if (await copy(text)) {
|
||||
showSuccess('已复制:' + text);
|
||||
showSuccess(t('已复制:{{name}}', { name: text }));
|
||||
} else {
|
||||
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
|
||||
}
|
||||
|
||||
@@ -241,6 +241,9 @@ export const useUsersData = () => {
|
||||
if (res === undefined) {
|
||||
return;
|
||||
}
|
||||
if (!res.data?.success || !Array.isArray(res.data.data)) {
|
||||
return;
|
||||
}
|
||||
setGroupOptions(
|
||||
res.data.data.map((group) => ({
|
||||
label: group,
|
||||
|
||||
@@ -19,10 +19,13 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { API } from '../../helpers';
|
||||
import i18next from 'i18next';
|
||||
|
||||
const errorCode = (error) => error?.response?.data?.error?.code || '';
|
||||
const errorMessage = (error) =>
|
||||
error?.response?.data?.error?.message || error?.message || '请求失败';
|
||||
error?.response?.data?.error?.message ||
|
||||
error?.message ||
|
||||
i18next.t('请求失败');
|
||||
|
||||
const readFileAsDataURL = (file) =>
|
||||
new Promise((resolve, reject) => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,602 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 体验中心视频页(WP A1-12)schema 驱动的纯函数:模式 / 图片槽 / 参数合成 / 请求体 / 草稿。
|
||||
// 无 React / i18n 依赖,可直接 node --test。schema 见 controller/creation_models.go。
|
||||
|
||||
import {
|
||||
getDefaultValues,
|
||||
getParamDefault,
|
||||
paramsForMode,
|
||||
snapValues,
|
||||
} from '../../components/creation/params/constraints.js';
|
||||
|
||||
export const DRAFT_STORAGE_KEY = 'video_generation_draft_v3';
|
||||
const LEGACY_DRAFT_KEY = 'video_generation_draft_v2';
|
||||
|
||||
export const MODE_ORDER = [
|
||||
'text2video',
|
||||
'image2video',
|
||||
'first_last_frame',
|
||||
'reference2video',
|
||||
];
|
||||
|
||||
/** 模式显示名(i18n key)。 */
|
||||
export const MODE_LABEL_KEYS = {
|
||||
text2video: '文生视频',
|
||||
image2video: '图生视频',
|
||||
first_last_frame: '首尾帧生视频',
|
||||
reference2video: '参考图生视频',
|
||||
};
|
||||
|
||||
/** 视频请求(VideoGenerateRequest)认识的 schema 参数;其余参数不渲染也不提交。 */
|
||||
export const REQUEST_PARAM_KEYS = new Set([
|
||||
'aspect_ratio',
|
||||
'resolution',
|
||||
'duration',
|
||||
'generate_audio',
|
||||
'watermark',
|
||||
'seed',
|
||||
'negative_prompt',
|
||||
'camera',
|
||||
'return_last_frame',
|
||||
'prompt_extend',
|
||||
]);
|
||||
|
||||
export const EMPTY_IMAGES = Object.freeze({
|
||||
first_frame: null,
|
||||
last_frame: null,
|
||||
reference_images: [],
|
||||
});
|
||||
|
||||
export const DEFAULT_VIDEO_FORM = Object.freeze({
|
||||
mode: 'text2video',
|
||||
selectedTemplate: '',
|
||||
prompt: '',
|
||||
modelName: '',
|
||||
params: {},
|
||||
images: EMPTY_IMAGES,
|
||||
// 按模型记忆的参数(切换模型时优先级第 2 位,方案 §4.3)
|
||||
paramMemory: {},
|
||||
});
|
||||
|
||||
export const modelNameOf = (model) => {
|
||||
if (!model) return '';
|
||||
if (typeof model === 'string') return model;
|
||||
return model.model || model.model_name || model.id || '';
|
||||
};
|
||||
|
||||
/** schema 中可渲染 / 可提交的参数。 */
|
||||
export const requestParamsOf = (model) =>
|
||||
((model && model.params) || []).filter(
|
||||
(p) => p && p.key && REQUEST_PARAM_KEYS.has(p.key),
|
||||
);
|
||||
|
||||
/** 当前模式下可渲染 / 可提交的参数(schema 参数的 modes 不含当前模式时隐藏且不提交)。 */
|
||||
export const requestParamsForMode = (model, mode) =>
|
||||
paramsForMode(requestParamsOf(model), mode || 'text2video');
|
||||
|
||||
/** 模式列表:可用模式 + 因系统配置禁用的模式(带原因),按固定顺序。 */
|
||||
export const modeOptionsOf = (model) => {
|
||||
if (!model) return [];
|
||||
const enabled = new Set(model.modes || []);
|
||||
const disabled = {};
|
||||
(model.disabled_modes || []).forEach((d) => {
|
||||
if (d && d.mode && !enabled.has(d.mode)) disabled[d.mode] = d.reason || '';
|
||||
});
|
||||
const all = new Set([...enabled, ...Object.keys(disabled)]);
|
||||
const order = (m) => {
|
||||
const i = MODE_ORDER.indexOf(m);
|
||||
return i < 0 ? MODE_ORDER.length : i;
|
||||
};
|
||||
return [...all]
|
||||
.sort((a, b) => order(a) - order(b))
|
||||
.map((mode) => ({
|
||||
mode,
|
||||
disabled: !enabled.has(mode),
|
||||
reason: disabled[mode] || '',
|
||||
}));
|
||||
};
|
||||
|
||||
export const isModeEnabled = (model, mode) =>
|
||||
Boolean(model && (model.modes || []).includes(mode));
|
||||
|
||||
const inputUsedBy = (input, mode) =>
|
||||
Boolean(input && Array.isArray(input.modes) && input.modes.includes(mode));
|
||||
|
||||
/** 当前模型 × 模式使用的图片输入:{ first_frame, last_frame, reference_images(max) }。 */
|
||||
export const activeInputsOf = (model, mode) => {
|
||||
const inputs = (model && model.inputs) || {};
|
||||
const out = { first_frame: false, last_frame: false, reference_max: 0 };
|
||||
if (!isModeEnabled(model, mode)) return out;
|
||||
out.first_frame = inputUsedBy(inputs.first_frame, mode);
|
||||
out.last_frame = inputUsedBy(inputs.last_frame, mode);
|
||||
if (inputUsedBy(inputs.reference_images, mode)) {
|
||||
const max = Number(inputs.reference_images.max);
|
||||
out.reference_max = Number.isFinite(max) && max > 0 ? max : 1;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const isReady = (slot) =>
|
||||
Boolean(slot && slot.ref && (slot.status || 'ready') === 'ready');
|
||||
|
||||
/**
|
||||
* 面板要渲染的图片槽。当前模式用到的槽正常显示;用不到但已有图片的槽保留并标为 unused
|
||||
* (方案 §4.3:新模型用不到的图片不删除,置灰标注,切回去自动恢复)。
|
||||
*
|
||||
* @returns {Array<{ key: string, index?: number, label: string, labelIndex?: number,
|
||||
* slot: object|null, active: boolean }>}
|
||||
*/
|
||||
export const imageSlotsOf = (model, mode, images = EMPTY_IMAGES) => {
|
||||
const active = activeInputsOf(model, mode);
|
||||
const list = [];
|
||||
const inputs = (model && model.inputs) || {};
|
||||
if (active.first_frame || images.first_frame) {
|
||||
list.push({
|
||||
key: 'first_frame',
|
||||
label: (inputs.first_frame && inputs.first_frame.label) || '首帧',
|
||||
slot: images.first_frame || null,
|
||||
active: active.first_frame,
|
||||
});
|
||||
}
|
||||
if (active.last_frame || images.last_frame) {
|
||||
list.push({
|
||||
key: 'last_frame',
|
||||
label: (inputs.last_frame && inputs.last_frame.label) || '尾帧',
|
||||
slot: images.last_frame || null,
|
||||
active: active.last_frame,
|
||||
});
|
||||
}
|
||||
const refs = images.reference_images || [];
|
||||
const refActive = active.reference_max > 0;
|
||||
refs.forEach((slot, index) => {
|
||||
list.push({
|
||||
key: 'reference_images',
|
||||
index,
|
||||
label: '参考图',
|
||||
labelIndex: index + 1,
|
||||
slot,
|
||||
// 超过当前模型上限的参考图同样不提交
|
||||
active: refActive && index < active.reference_max,
|
||||
});
|
||||
});
|
||||
if (refActive && refs.length < active.reference_max) {
|
||||
list.push({
|
||||
key: 'reference_images',
|
||||
index: refs.length,
|
||||
label: '参考图',
|
||||
labelIndex: refs.length + 1,
|
||||
slot: null,
|
||||
active: true,
|
||||
});
|
||||
}
|
||||
return list;
|
||||
};
|
||||
|
||||
/** 当前模式真正会提交的图片槽。 */
|
||||
export const activeImageSlots = (model, mode, images) =>
|
||||
imageSlotsOf(model, mode, images).filter((s) => s.active && s.slot);
|
||||
|
||||
/**
|
||||
* 提交前的阻断原因(i18n key + 插值),无阻断返回 null。
|
||||
* 只检查与图片相关的条件;提示词 / 模型 / 并发 / 余额由调用方检查。
|
||||
*/
|
||||
export const imageBlockReason = (model, mode, images = EMPTY_IMAGES) => {
|
||||
if (!model) return null;
|
||||
if (!isModeEnabled(model, mode)) {
|
||||
return { key: '当前模型不支持该生成模式,请切换模式' };
|
||||
}
|
||||
const slots = activeImageSlots(model, mode, images);
|
||||
if (slots.some((s) => s.slot.status === 'uploading')) {
|
||||
return { key: '图片上传中,请稍候' };
|
||||
}
|
||||
if (slots.some((s) => s.slot.status === 'error')) {
|
||||
return { key: '图片上传失败,请重试或移除' };
|
||||
}
|
||||
if (slots.some((s) => s.slot.status === 'expired')) {
|
||||
return { key: '原图已失效,请重新上传' };
|
||||
}
|
||||
const active = activeInputsOf(model, mode);
|
||||
if (active.first_frame && !isReady(images.first_frame)) {
|
||||
return { key: mode === 'image2video' ? '请上传首帧图片' : '缺少首帧' };
|
||||
}
|
||||
if (active.last_frame && !isReady(images.last_frame)) {
|
||||
return { key: '缺少尾帧' };
|
||||
}
|
||||
if (
|
||||
active.reference_max > 0 &&
|
||||
!slots.some((s) => s.key === 'reference_images' && isReady(s.slot))
|
||||
) {
|
||||
return { key: '请至少上传一张参考图' };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换模型后的模式:当前模式可用则保持;否则在可用模式里优先保留已上传的图片(首帧 → 图生),
|
||||
* 再退回文生视频 / 第一个可用模式。
|
||||
*/
|
||||
export const pickModeForModel = (model, mode, images = EMPTY_IMAGES) => {
|
||||
if (!model) return mode || 'text2video';
|
||||
if (isModeEnabled(model, mode)) return mode;
|
||||
const modes = model.modes || [];
|
||||
if (
|
||||
images.first_frame &&
|
||||
images.last_frame &&
|
||||
modes.includes('first_last_frame')
|
||||
) {
|
||||
return 'first_last_frame';
|
||||
}
|
||||
if (images.first_frame && modes.includes('image2video')) return 'image2video';
|
||||
if (
|
||||
(images.reference_images || []).length &&
|
||||
modes.includes('reference2video')
|
||||
) {
|
||||
return 'reference2video';
|
||||
}
|
||||
if (modes.includes('text2video')) return 'text2video';
|
||||
return modes[0] || 'text2video';
|
||||
};
|
||||
|
||||
/**
|
||||
* 合成某模型的参数取值(方案 §4.3 优先级):
|
||||
* 1. 本次会话用户手动设置的值(sessionValues);2. 该模型上次使用时记住的值(memory);
|
||||
* 3. schema 默认值。不合法的值吸附到最近的合法值。
|
||||
*
|
||||
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
|
||||
*/
|
||||
export const composeParams = (
|
||||
model,
|
||||
{ sessionValues = {}, memory = {} } = {},
|
||||
) => {
|
||||
const params = requestParamsOf(model);
|
||||
const merged = getDefaultValues(params);
|
||||
params.forEach((p) => {
|
||||
if (memory && memory[p.key] !== undefined) merged[p.key] = memory[p.key];
|
||||
if (sessionValues && sessionValues[p.key] !== undefined) {
|
||||
merged[p.key] = sessionValues[p.key];
|
||||
}
|
||||
});
|
||||
const { values, adjustments } = snapValues(
|
||||
params,
|
||||
merged,
|
||||
(model && model.constraints) || [],
|
||||
);
|
||||
// 只保留 schema 内的键:其它模型的参数不随请求提交
|
||||
const out = {};
|
||||
params.forEach((p) => {
|
||||
if (values[p.key] !== undefined) out[p.key] = values[p.key];
|
||||
});
|
||||
return { values: out, adjustments };
|
||||
};
|
||||
|
||||
/**
|
||||
* 复用参数 / 再生成 / 换种子再来:任务快照对请求参数是权威的。只按快照参数合成,
|
||||
* 快照缺省的可选参数(随机种子、空负向提示词等)取 schema 默认值,不合并此前的会话值
|
||||
* 与按模型记忆(否则上一次"换种子"的固定种子会泄漏到本次请求)。
|
||||
* @returns {{ values: object, adjustments: Array<{key, from, to}> }}
|
||||
*/
|
||||
export const composePrefillParams = (model, snapshotParams) =>
|
||||
composeParams(model, {
|
||||
sessionValues: { ...(snapshotParams || {}) },
|
||||
memory: {},
|
||||
});
|
||||
|
||||
const isRandomSeed = (v) =>
|
||||
v === undefined || v === null || v === '' || Number.isNaN(Number(v));
|
||||
|
||||
/**
|
||||
* 构造 POST /api/video/generate 请求体(不含 model)。
|
||||
* - 参数只取 schema 内、请求认识、且适用于当前模式(modes)的键;未设置的取 schema 默认值。
|
||||
* - 比例 / 音频同时写入旧字段别名(ratio / audio),兼容旧转换器路径。
|
||||
* - 图片按模式放入 image / last_image / reference_images;当前模式用不到的图片不提交。
|
||||
*/
|
||||
export const buildVideoRequest = (model, form) => {
|
||||
const mode = form.mode || 'text2video';
|
||||
const values = form.params || {};
|
||||
const payload = { mode, prompt: form.prompt || '' };
|
||||
|
||||
requestParamsForMode(model, mode).forEach((p) => {
|
||||
const v = values[p.key] !== undefined ? values[p.key] : getParamDefault(p);
|
||||
switch (p.key) {
|
||||
case 'seed':
|
||||
if (!isRandomSeed(v)) payload.seed = Math.trunc(Number(v));
|
||||
break;
|
||||
case 'negative_prompt':
|
||||
case 'camera':
|
||||
if (typeof v === 'string' && v.trim()) payload[p.key] = v.trim();
|
||||
break;
|
||||
case 'aspect_ratio':
|
||||
if (v !== undefined && v !== null && v !== '') {
|
||||
payload.aspect_ratio = String(v);
|
||||
payload.ratio = String(v);
|
||||
}
|
||||
break;
|
||||
case 'generate_audio':
|
||||
if (typeof v === 'boolean') {
|
||||
payload.generate_audio = v;
|
||||
payload.audio = v;
|
||||
}
|
||||
break;
|
||||
case 'duration': {
|
||||
const n = Number(v);
|
||||
if (Number.isFinite(n) && n > 0) payload.duration = n;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
if (v !== undefined && v !== null && v !== '') payload[p.key] = v;
|
||||
}
|
||||
});
|
||||
|
||||
const images = form.images || EMPTY_IMAGES;
|
||||
const active = activeInputsOf(model, mode);
|
||||
if (active.first_frame && isReady(images.first_frame)) {
|
||||
payload.image = images.first_frame.ref;
|
||||
}
|
||||
if (active.last_frame && isReady(images.last_frame)) {
|
||||
payload.last_image = images.last_frame.ref;
|
||||
}
|
||||
if (active.reference_max > 0) {
|
||||
const refs = (images.reference_images || [])
|
||||
.slice(0, active.reference_max)
|
||||
.filter(isReady)
|
||||
.map((s) => s.ref);
|
||||
if (refs.length) payload.reference_images = refs;
|
||||
}
|
||||
return payload;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 再生成:把任务详情的 request(ExperienceVideoRequestDTO)回填为表单
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const isDisplayableURL = (v) => /^(https?:|data:|blob:)/i.test(String(v || ''));
|
||||
|
||||
const taskImageSlot = (ref, display, id) => {
|
||||
const value = typeof ref === 'string' ? ref.trim() : '';
|
||||
if (!value) return null;
|
||||
const isAsset = value.startsWith('asset://');
|
||||
const preview = isDisplayableURL(display)
|
||||
? display
|
||||
: isDisplayableURL(value)
|
||||
? value
|
||||
: null;
|
||||
return {
|
||||
id,
|
||||
status: 'ready',
|
||||
ref: value,
|
||||
previewUrl: preview,
|
||||
source: isAsset ? 'asset' : 'task',
|
||||
identityType: isAsset ? 'real_person' : 'aigc',
|
||||
};
|
||||
};
|
||||
|
||||
const isBool = (v) => typeof v === 'boolean';
|
||||
const nonEmptyString = (v) => typeof v === 'string' && v.trim() !== '';
|
||||
|
||||
/**
|
||||
* 任务详情 request → 表单回填值(未按 schema 吸附,调用方再走 composeParams)。
|
||||
* 字段映射见 controller/video_generation.go ExperienceVideoRequestDTO:
|
||||
* image_ref|image → 首帧,last_image_ref|last_image → 尾帧,
|
||||
* reference_image_refs[i]|reference_images[i] → 参考图;*_ref 为提交值,无 *_ref 时退回展示地址。
|
||||
*
|
||||
* @returns {{ modelName, mode, prompt, params, images }}
|
||||
*/
|
||||
export const formFromTaskRequest = (request, { newId } = {}) => {
|
||||
const req = request || {};
|
||||
let seq = 0;
|
||||
const makeId =
|
||||
newId || (() => `slot-task-${Date.now().toString(36)}-${seq++}`);
|
||||
|
||||
const params = {};
|
||||
const aspect = req.aspect_ratio || req.ratio;
|
||||
if (nonEmptyString(aspect)) params.aspect_ratio = aspect;
|
||||
if (nonEmptyString(req.resolution)) params.resolution = req.resolution;
|
||||
if (Number(req.duration) > 0) params.duration = Number(req.duration);
|
||||
if (isBool(req.generate_audio)) params.generate_audio = req.generate_audio;
|
||||
else if (isBool(req.audio)) params.generate_audio = req.audio;
|
||||
// watermark / audio 为 omitempty:缺省即 false
|
||||
params.watermark = req.watermark === true;
|
||||
if (typeof req.seed === 'number' && Number.isFinite(req.seed)) {
|
||||
params.seed = req.seed;
|
||||
}
|
||||
if (nonEmptyString(req.negative_prompt)) {
|
||||
params.negative_prompt = req.negative_prompt;
|
||||
}
|
||||
if (nonEmptyString(req.camera)) params.camera = req.camera;
|
||||
if (isBool(req.return_last_frame)) {
|
||||
params.return_last_frame = req.return_last_frame;
|
||||
}
|
||||
if (isBool(req.prompt_extend)) params.prompt_extend = req.prompt_extend;
|
||||
|
||||
const refs = Array.isArray(req.reference_image_refs)
|
||||
? req.reference_image_refs
|
||||
: [];
|
||||
const displays = Array.isArray(req.reference_images)
|
||||
? req.reference_images
|
||||
: [];
|
||||
const refList = refs.length ? refs : displays;
|
||||
const images = {
|
||||
first_frame: taskImageSlot(req.image_ref || req.image, req.image, makeId()),
|
||||
last_frame: taskImageSlot(
|
||||
req.last_image_ref || req.last_image,
|
||||
req.last_image,
|
||||
makeId(),
|
||||
),
|
||||
reference_images: refList
|
||||
.map((ref, i) => taskImageSlot(ref, displays[i], makeId()))
|
||||
.filter(Boolean),
|
||||
};
|
||||
|
||||
return {
|
||||
modelName: typeof req.model === 'string' ? req.model : '',
|
||||
mode: MODE_ORDER.includes(req.mode) ? req.mode : '',
|
||||
prompt: typeof req.prompt === 'string' ? req.prompt : '',
|
||||
params,
|
||||
images,
|
||||
};
|
||||
};
|
||||
|
||||
/** 估价请求的 params(只带定价相关参数)。 */
|
||||
export const quoteParamsOf = (payload) => {
|
||||
const out = {};
|
||||
['duration', 'resolution', 'aspect_ratio'].forEach((k) => {
|
||||
if (payload[k] !== undefined) out[k] = payload[k];
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 草稿(localStorage v3,读写全部 try/catch)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PERSISTABLE_SLOT_FIELDS = [
|
||||
'id',
|
||||
'ref',
|
||||
'previewUrl',
|
||||
'name',
|
||||
'source',
|
||||
'identityType',
|
||||
];
|
||||
|
||||
const persistSlot = (slot, keepInline) => {
|
||||
if (!isReady(slot)) return null;
|
||||
if (!keepInline && String(slot.ref).startsWith('data:')) return null;
|
||||
const out = { status: 'ready' };
|
||||
PERSISTABLE_SLOT_FIELDS.forEach((k) => {
|
||||
if (slot[k] !== undefined && slot[k] !== null) out[k] = slot[k];
|
||||
});
|
||||
// 内联图片的预览就是它自己,不重复存
|
||||
if (String(out.ref).startsWith('data:') && out.previewUrl === out.ref) {
|
||||
delete out.previewUrl;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export const serializeDraft = (form, { keepInline = true } = {}) => {
|
||||
const images = form.images || EMPTY_IMAGES;
|
||||
return JSON.stringify({
|
||||
mode: form.mode,
|
||||
selectedTemplate: form.selectedTemplate || '',
|
||||
prompt: form.prompt || '',
|
||||
modelName: form.modelName || '',
|
||||
params: form.params || {},
|
||||
paramMemory: form.paramMemory || {},
|
||||
images: {
|
||||
first_frame: persistSlot(images.first_frame, keepInline),
|
||||
last_frame: persistSlot(images.last_frame, keepInline),
|
||||
reference_images: (images.reference_images || [])
|
||||
.map((s) => persistSlot(s, keepInline))
|
||||
.filter(Boolean),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const restoreSlot = (slot) => {
|
||||
if (!slot || typeof slot !== 'object' || typeof slot.ref !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const out = { ...slot, status: 'ready' };
|
||||
if (!out.previewUrl && out.ref.startsWith('data:')) out.previewUrl = out.ref;
|
||||
if (!out.id) out.id = `slot-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return out;
|
||||
};
|
||||
|
||||
const isPlainObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
export const parseDraft = (raw) => {
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw);
|
||||
if (!isPlainObject(data)) return null;
|
||||
const images = isPlainObject(data.images) ? data.images : {};
|
||||
return {
|
||||
...DEFAULT_VIDEO_FORM,
|
||||
mode: MODE_ORDER.includes(data.mode) ? data.mode : 'text2video',
|
||||
selectedTemplate:
|
||||
typeof data.selectedTemplate === 'string' ? data.selectedTemplate : '',
|
||||
prompt: typeof data.prompt === 'string' ? data.prompt : '',
|
||||
modelName: typeof data.modelName === 'string' ? data.modelName : '',
|
||||
params: isPlainObject(data.params) ? data.params : {},
|
||||
paramMemory: isPlainObject(data.paramMemory) ? data.paramMemory : {},
|
||||
images: {
|
||||
first_frame: restoreSlot(images.first_frame),
|
||||
last_frame: restoreSlot(images.last_frame),
|
||||
reference_images: Array.isArray(images.reference_images)
|
||||
? images.reference_images.map(restoreSlot).filter(Boolean)
|
||||
: [],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** 读取草稿;v3 不存在时只从 v2 迁移提示词与模板(旧参数口径不同,不迁移)。 */
|
||||
export const loadDraft = (storage) => {
|
||||
try {
|
||||
const v3 = parseDraft(storage.getItem(DRAFT_STORAGE_KEY));
|
||||
if (v3) return v3;
|
||||
} catch (e) {
|
||||
// 草稿损坏时忽略
|
||||
}
|
||||
try {
|
||||
const raw = storage.getItem(LEGACY_DRAFT_KEY);
|
||||
const v2 = raw ? JSON.parse(raw) : null;
|
||||
if (isPlainObject(v2)) {
|
||||
return {
|
||||
...DEFAULT_VIDEO_FORM,
|
||||
prompt: typeof v2.prompt === 'string' ? v2.prompt : '',
|
||||
selectedTemplate:
|
||||
typeof v2.selectedTemplate === 'string' ? v2.selectedTemplate : '',
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略
|
||||
}
|
||||
return { ...DEFAULT_VIDEO_FORM };
|
||||
};
|
||||
|
||||
/** 保存草稿;配额不足时退而不存内联 base64 图片,仍失败则放弃。 */
|
||||
export const saveDraft = (storage, form) => {
|
||||
try {
|
||||
storage.setItem(DRAFT_STORAGE_KEY, serializeDraft(form));
|
||||
return true;
|
||||
} catch (e) {
|
||||
try {
|
||||
storage.setItem(
|
||||
DRAFT_STORAGE_KEY,
|
||||
serializeDraft(form, { keepInline: false }),
|
||||
);
|
||||
return true;
|
||||
} catch (e2) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 轮询退避
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const POLL_STEPS_MS = [3000, 5000, 10000];
|
||||
export const POLL_HIDDEN_MS = 30000;
|
||||
|
||||
/** 第 n 次(从 0 起)连续无变化轮询后的间隔;页面隐藏时降频。 */
|
||||
export const pollDelay = (step, hidden) => {
|
||||
if (hidden) return POLL_HIDDEN_MS;
|
||||
return POLL_STEPS_MS[Math.min(step, POLL_STEPS_MS.length - 1)];
|
||||
};
|
||||
@@ -0,0 +1,362 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
DRAFT_STORAGE_KEY,
|
||||
buildVideoRequest,
|
||||
composeParams,
|
||||
formFromTaskRequest,
|
||||
imageBlockReason,
|
||||
imageSlotsOf,
|
||||
loadDraft,
|
||||
modeOptionsOf,
|
||||
pickModeForModel,
|
||||
pollDelay,
|
||||
saveDraft,
|
||||
} from './videoCreation.js';
|
||||
|
||||
const seedance = {
|
||||
model: 'seedance',
|
||||
modes: ['text2video', 'image2video', 'first_last_frame'],
|
||||
params: [
|
||||
{
|
||||
key: 'aspect_ratio',
|
||||
type: 'ratio',
|
||||
options: ['16:9', '9:16', '1:1'],
|
||||
default: '16:9',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'duration',
|
||||
type: 'segmented',
|
||||
options: [5, 10],
|
||||
default: 5,
|
||||
unit: 's',
|
||||
placement: 'dock',
|
||||
},
|
||||
{
|
||||
key: 'generate_audio',
|
||||
type: 'switch',
|
||||
default: true,
|
||||
placement: 'advanced',
|
||||
},
|
||||
{ key: 'seed', type: 'seed', placement: 'advanced' },
|
||||
{
|
||||
key: 'camera_fixed',
|
||||
type: 'switch',
|
||||
default: false,
|
||||
placement: 'advanced',
|
||||
},
|
||||
{
|
||||
key: 'return_last_frame',
|
||||
type: 'switch',
|
||||
default: true,
|
||||
placement: 'hidden',
|
||||
},
|
||||
],
|
||||
inputs: {
|
||||
first_frame: { label: '首帧', modes: ['image2video', 'first_last_frame'] },
|
||||
last_frame: { label: '尾帧', modes: ['first_last_frame'] },
|
||||
},
|
||||
};
|
||||
|
||||
const vidu = {
|
||||
model: 'vidu',
|
||||
modes: ['text2video', 'reference2video'],
|
||||
disabled_modes: [{ mode: 'image2video', reason: 'COS 未开启' }],
|
||||
params: [
|
||||
{
|
||||
key: 'duration',
|
||||
type: 'segmented',
|
||||
options: [4, 8],
|
||||
default: 4,
|
||||
placement: 'dock',
|
||||
},
|
||||
],
|
||||
inputs: {
|
||||
reference_images: { label: '参考图', modes: ['reference2video'], max: 2 },
|
||||
},
|
||||
};
|
||||
|
||||
const ready = (ref) => ({ id: ref, ref, status: 'ready' });
|
||||
|
||||
test('modeOptionsOf 列出可用与禁用模式并保持顺序', () => {
|
||||
assert.deepEqual(modeOptionsOf(vidu), [
|
||||
{ mode: 'text2video', disabled: false, reason: '' },
|
||||
{ mode: 'image2video', disabled: true, reason: 'COS 未开启' },
|
||||
{ mode: 'reference2video', disabled: false, reason: '' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('首尾帧模式按 inputs 生成带标签的两个槽', () => {
|
||||
const slots = imageSlotsOf(seedance, 'first_last_frame', {
|
||||
first_frame: null,
|
||||
last_frame: null,
|
||||
reference_images: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
slots.map((s) => [s.key, s.label, s.active]),
|
||||
[
|
||||
['first_frame', '首帧', true],
|
||||
['last_frame', '尾帧', true],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('当前模式用不到的图片保留为非激活槽且不提交', () => {
|
||||
const images = {
|
||||
first_frame: ready('cos://playground/1/a.png'),
|
||||
last_frame: ready('cos://playground/1/b.png'),
|
||||
reference_images: [],
|
||||
};
|
||||
const slots = imageSlotsOf(seedance, 'image2video', images);
|
||||
assert.equal(slots.find((s) => s.key === 'last_frame').active, false);
|
||||
const body = buildVideoRequest(seedance, {
|
||||
mode: 'image2video',
|
||||
prompt: 'p',
|
||||
params: {},
|
||||
images,
|
||||
});
|
||||
assert.equal(body.image, 'cos://playground/1/a.png');
|
||||
assert.equal(body.last_image, undefined);
|
||||
});
|
||||
|
||||
test('参考图槽数受 max 限制,超出的不提交', () => {
|
||||
const images = {
|
||||
first_frame: null,
|
||||
last_frame: null,
|
||||
reference_images: [ready('r1'), ready('r2'), ready('r3')],
|
||||
};
|
||||
const slots = imageSlotsOf(vidu, 'reference2video', images);
|
||||
assert.deepEqual(
|
||||
slots.map((s) => [s.labelIndex, s.active]),
|
||||
[
|
||||
[1, true],
|
||||
[2, true],
|
||||
[3, false],
|
||||
],
|
||||
);
|
||||
const body = buildVideoRequest(vidu, {
|
||||
mode: 'reference2video',
|
||||
prompt: 'p',
|
||||
params: {},
|
||||
images,
|
||||
});
|
||||
assert.deepEqual(body.reference_images, ['r1', 'r2']);
|
||||
});
|
||||
|
||||
test('请求体只带 schema 内参数,比例 / 音频写入别名,随机种子不提交', () => {
|
||||
const body = buildVideoRequest(seedance, {
|
||||
mode: 'text2video',
|
||||
prompt: 'hello',
|
||||
params: { aspect_ratio: '9:16', duration: 10, seed: null, fps: 30 },
|
||||
images: undefined,
|
||||
});
|
||||
assert.deepEqual(body, {
|
||||
mode: 'text2video',
|
||||
prompt: 'hello',
|
||||
aspect_ratio: '9:16',
|
||||
ratio: '9:16',
|
||||
duration: 10,
|
||||
generate_audio: true,
|
||||
audio: true,
|
||||
return_last_frame: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('缺图 / 上传中 / 失败时给出阻断原因', () => {
|
||||
const base = { first_frame: null, last_frame: null, reference_images: [] };
|
||||
assert.deepEqual(imageBlockReason(seedance, 'image2video', base), {
|
||||
key: '请上传首帧图片',
|
||||
});
|
||||
assert.deepEqual(
|
||||
imageBlockReason(seedance, 'first_last_frame', {
|
||||
...base,
|
||||
first_frame: ready('a'),
|
||||
}),
|
||||
{ key: '缺少尾帧' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
imageBlockReason(seedance, 'image2video', {
|
||||
...base,
|
||||
first_frame: { id: 'x', status: 'uploading' },
|
||||
}),
|
||||
{ key: '图片上传中,请稍候' },
|
||||
);
|
||||
assert.equal(
|
||||
imageBlockReason(seedance, 'image2video', {
|
||||
...base,
|
||||
first_frame: ready('a'),
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(imageBlockReason(vidu, 'image2video', base), {
|
||||
key: '当前模型不支持该生成模式,请切换模式',
|
||||
});
|
||||
});
|
||||
|
||||
test('切换模型:会话值优先、记忆其次,不合法值吸附并报告', () => {
|
||||
const { values, adjustments } = composeParams(vidu, {
|
||||
sessionValues: { duration: 10, aspect_ratio: '9:16' },
|
||||
memory: { duration: 4 },
|
||||
});
|
||||
assert.deepEqual(values, { duration: 8 });
|
||||
assert.deepEqual(adjustments, [{ key: 'duration', from: 10, to: 8 }]);
|
||||
const kept = composeParams(seedance, { memory: { duration: 10 } });
|
||||
assert.equal(kept.values.duration, 10);
|
||||
assert.equal(kept.values.camera_fixed, undefined);
|
||||
});
|
||||
|
||||
test('切换模型时的模式选择', () => {
|
||||
const images = {
|
||||
first_frame: ready('a'),
|
||||
last_frame: null,
|
||||
reference_images: [],
|
||||
};
|
||||
assert.equal(
|
||||
pickModeForModel(seedance, 'reference2video', images),
|
||||
'image2video',
|
||||
);
|
||||
assert.equal(pickModeForModel(vidu, 'image2video', images), 'text2video');
|
||||
assert.equal(
|
||||
pickModeForModel(seedance, 'first_last_frame', images),
|
||||
'first_last_frame',
|
||||
);
|
||||
});
|
||||
|
||||
const memoryStorage = (quota = Infinity) => {
|
||||
const map = new Map();
|
||||
return {
|
||||
getItem: (k) => (map.has(k) ? map.get(k) : null),
|
||||
setItem: (k, v) => {
|
||||
if (v.length > quota) throw new Error('QuotaExceededError');
|
||||
map.set(k, v);
|
||||
},
|
||||
map,
|
||||
};
|
||||
};
|
||||
|
||||
test('草稿 v3 往返;配额不足时丢弃内联图片', () => {
|
||||
const storage = memoryStorage(400);
|
||||
const form = {
|
||||
mode: 'image2video',
|
||||
prompt: 'cat',
|
||||
selectedTemplate: '',
|
||||
modelName: 'seedance',
|
||||
params: { duration: 5 },
|
||||
paramMemory: {},
|
||||
images: {
|
||||
first_frame: ready(`data:image/png;base64,${'A'.repeat(500)}`),
|
||||
last_frame: { id: 'u', status: 'uploading' },
|
||||
reference_images: [],
|
||||
},
|
||||
};
|
||||
assert.equal(saveDraft(storage, form), true);
|
||||
const loaded = loadDraft(storage);
|
||||
assert.equal(loaded.prompt, 'cat');
|
||||
assert.equal(loaded.images.first_frame, null);
|
||||
assert.equal(loaded.images.last_frame, null);
|
||||
assert.ok(storage.map.has(DRAFT_STORAGE_KEY));
|
||||
});
|
||||
|
||||
test('损坏的草稿与抛异常的存储不影响加载', () => {
|
||||
const broken = {
|
||||
getItem: () => '{not json',
|
||||
};
|
||||
assert.equal(loadDraft(broken).mode, 'text2video');
|
||||
const throwing = {
|
||||
getItem: () => {
|
||||
throw new Error('SecurityError');
|
||||
},
|
||||
setItem: () => {
|
||||
throw new Error('SecurityError');
|
||||
},
|
||||
};
|
||||
assert.equal(loadDraft(throwing).prompt, '');
|
||||
assert.equal(saveDraft(throwing, loadDraft(throwing)), false);
|
||||
});
|
||||
|
||||
test('轮询退避 3s → 5s → 10s,隐藏时降频', () => {
|
||||
assert.deepEqual(
|
||||
[0, 1, 2, 5].map((s) => pollDelay(s, false)),
|
||||
[3000, 5000, 10000, 10000],
|
||||
);
|
||||
assert.equal(pollDelay(0, true), 30000);
|
||||
});
|
||||
|
||||
test('formFromTaskRequest maps v2 request refs and params', () => {
|
||||
let n = 0;
|
||||
const form = formFromTaskRequest(
|
||||
{
|
||||
model: 'seedance',
|
||||
mode: 'first_last_frame',
|
||||
prompt: 'p',
|
||||
resolution: '1080p',
|
||||
duration: 10,
|
||||
ratio: '9:16',
|
||||
aspect_ratio: '9:16',
|
||||
generate_audio: false,
|
||||
audio: true,
|
||||
seed: 0,
|
||||
image: 'https://cos/first.png?sig',
|
||||
image_ref: 'task://t1#first',
|
||||
last_image: 'https://cos/last.png?sig',
|
||||
last_image_ref: 'cos://u/last.png',
|
||||
reference_images: ['asset://a1'],
|
||||
reference_image_refs: ['asset://a1'],
|
||||
},
|
||||
{ newId: () => `id${n++}` },
|
||||
);
|
||||
assert.equal(form.modelName, 'seedance');
|
||||
assert.equal(form.mode, 'first_last_frame');
|
||||
assert.deepEqual(form.params, {
|
||||
aspect_ratio: '9:16',
|
||||
resolution: '1080p',
|
||||
duration: 10,
|
||||
generate_audio: false,
|
||||
watermark: false,
|
||||
seed: 0,
|
||||
});
|
||||
assert.equal(form.images.first_frame.ref, 'task://t1#first');
|
||||
assert.equal(form.images.first_frame.previewUrl, 'https://cos/first.png?sig');
|
||||
assert.equal(form.images.last_frame.ref, 'cos://u/last.png');
|
||||
assert.equal(form.images.reference_images[0].ref, 'asset://a1');
|
||||
assert.equal(form.images.reference_images[0].previewUrl, null);
|
||||
assert.equal(form.images.reference_images[0].identityType, 'real_person');
|
||||
|
||||
// 吸附后 seedance 不支持 resolution,不会出现在请求里
|
||||
const { values } = composeParams(seedance, { sessionValues: form.params });
|
||||
const payload = buildVideoRequest(seedance, { ...form, params: values });
|
||||
assert.equal(payload.resolution, undefined);
|
||||
assert.equal(payload.image, 'task://t1#first');
|
||||
assert.equal(payload.last_image, 'cos://u/last.png');
|
||||
});
|
||||
|
||||
test('formFromTaskRequest falls back to legacy image field', () => {
|
||||
const form = formFromTaskRequest({
|
||||
mode: 'image2video',
|
||||
image: 'https://x/a.png',
|
||||
watermark: true,
|
||||
});
|
||||
assert.equal(form.images.first_frame.ref, 'https://x/a.png');
|
||||
assert.equal(form.images.last_frame, null);
|
||||
assert.equal(form.params.watermark, true);
|
||||
});
|
||||
Reference in New Issue
Block a user