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:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user