cb9d836227
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
788 lines
25 KiB
JavaScript
788 lines
25 KiB
JavaScript
import {
|
||
useCallback,
|
||
useContext,
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
} from 'react';
|
||
import { useTranslation } from 'react-i18next';
|
||
import { API, showError, showInfo } from '../../helpers';
|
||
import {
|
||
getExperienceCenterBool,
|
||
getExperienceCenterPositiveInt,
|
||
} from '../../helpers/experienceCenter';
|
||
import { StatusContext } from '../../context/Status';
|
||
import {
|
||
budgetShortfallOf,
|
||
classifyCreationError,
|
||
describeCreationError,
|
||
} from '../../helpers/creationError';
|
||
import { trackCreationEvent } from '../../helpers/creationEvents';
|
||
import {
|
||
optionLabel,
|
||
paramLabel,
|
||
} from '../../components/creation/params/labels';
|
||
import { useCreationModels } from './useCreationModels';
|
||
import { useCreationQuote } from './useCreationQuote';
|
||
import { autoSubmitDecision } from './creationCompare';
|
||
import { openBatchConfirm } from '../../components/creation/batchConfirm';
|
||
import {
|
||
adapterOf,
|
||
allImageSlots,
|
||
applyPrefill,
|
||
buildPayload,
|
||
buildQuoteRequest,
|
||
formBlockReason,
|
||
initialModelOf,
|
||
loadForm,
|
||
markExpiredSlots,
|
||
modelNameOf,
|
||
normalizeSubmitError,
|
||
patchImageSlotById,
|
||
saveForm,
|
||
switchModel,
|
||
visibleParamsOf,
|
||
writeImageSlot,
|
||
} from './creationForm';
|
||
import { templateModelFor, templateParamsFor } from './creationDock';
|
||
|
||
// 不经上传接口、内联 base64 提交时的单张图片上限(与旧图像表单一致)
|
||
const INLINE_MAX_MB = 20;
|
||
|
||
const SUBMIT_ENDPOINTS = {
|
||
image: '/api/images/generations',
|
||
video: '/api/video/generate',
|
||
};
|
||
|
||
const getStorage = () => {
|
||
try {
|
||
return window.localStorage;
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
};
|
||
|
||
const newSlotId = () =>
|
||
`slot-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||
|
||
const readAsDataURL = (file) =>
|
||
new Promise((resolve, reject) => {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => resolve(e.target.result);
|
||
reader.onerror = () => reject(reader.error || new Error('read failed'));
|
||
reader.readAsDataURL(file);
|
||
});
|
||
|
||
/** 默认提交:直接调用既有接口,返回与 useImageTaskManagement.addTask 相同的结构。 */
|
||
const defaultSubmitter = (kind) => async (payload) => {
|
||
try {
|
||
const res = await API.post(SUBMIT_ENDPOINTS[kind], payload, {
|
||
skipErrorHandler: true,
|
||
});
|
||
if (!res?.data?.success) throw { data: res?.data };
|
||
return { ok: true, data: res.data.data };
|
||
} catch (error) {
|
||
const e = normalizeSubmitError(error);
|
||
return {
|
||
ok: false,
|
||
code: e.code,
|
||
message: e.message,
|
||
status: Number(error?.response?.status) || 0,
|
||
data: { running_tasks: e.running, max_running_tasks: e.max },
|
||
};
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 新创作台共用的表单状态机(WP B-2):模型 / 模式 / 提示词 / 参数 / 图片槽、按模型记忆、
|
||
* 参数优先级与吸附(方案 §4.3)、估价、提交与并发上限。
|
||
*
|
||
* @param {'image'|'video'} kind
|
||
* @param {{
|
||
* submitter?: (payload) => Promise<{ ok: boolean, code?: string, message?: string, data?: object }>,
|
||
* 默认直接 POST 既有接口;图像作品流可传 useImageTaskManagement.addTask 以便列表即时出现新任务。
|
||
* onSubmitted?: (result, payload) => void, 提交成功后回调(作品流乐观插入新任务)
|
||
* localRunning?: number, 作品流中进行中的任务数(与服务端数字取大)
|
||
* }} [options]
|
||
*/
|
||
export const useCreationForm = (
|
||
kind,
|
||
{ submitter, onSubmitted, localRunning = 0 } = {},
|
||
) => {
|
||
const { t } = useTranslation();
|
||
const [statusState] = useContext(StatusContext);
|
||
const status = statusState?.status;
|
||
const adapter = adapterOf(kind);
|
||
|
||
const {
|
||
data: creationData,
|
||
models,
|
||
loading: modelsLoading,
|
||
error: modelsError,
|
||
reload: reloadModels,
|
||
} = useCreationModels(kind);
|
||
|
||
const [form, setForm] = useState(() => loadForm(kind, getStorage()));
|
||
const formRef = useRef(form);
|
||
formRef.current = form;
|
||
const commit = useCallback((next) => {
|
||
formRef.current = next;
|
||
setForm(next);
|
||
}, []);
|
||
|
||
// 本次会话用户手动设置过的参数(优先级 1)
|
||
const sessionValuesRef = useRef({});
|
||
const schemaAppliedRef = useRef(false);
|
||
const fileStoreRef = useRef(new Map()); // slotId → File(重试用,不进存储)
|
||
// 最近一次吸附的明细,供界面展示(同时会 toast)
|
||
const [adjustments, setAdjustments] = useState([]);
|
||
// 请求创作台展开并聚焦提示词(复用参数 / 编辑此图等外部操作后递增,CreationDock 监听)
|
||
const [focusTick, setFocusTick] = useState(0);
|
||
const requestFocus = useCallback(() => setFocusTick((n) => n + 1), []);
|
||
// 再生成:回填后待提交(下一次渲染 payload 更新后执行)
|
||
const autoSubmitRef = useRef(false);
|
||
|
||
const selectedModel = useMemo(
|
||
() => models.find((m) => m.model === form.modelName) || null,
|
||
[models, form.modelName],
|
||
);
|
||
// 全部模型都被等级锁定(方案 §4.6):卡片可见,创作台给出升级入口
|
||
const allLocked =
|
||
models.length > 0 && models.every((m) => m && m.level_locked);
|
||
|
||
// 记忆写入(防抖)
|
||
useEffect(() => {
|
||
const timer = setTimeout(() => saveForm(kind, getStorage(), form), 800);
|
||
return () => clearTimeout(timer);
|
||
}, [kind, form]);
|
||
|
||
const notifyAdjustments = useCallback(
|
||
(model, list, modeChange) => {
|
||
const params = adapter.requestParamsOf(model);
|
||
const items = (list || []).map((a) => {
|
||
const param = params.find((p) => p.key === a.key) || { key: a.key };
|
||
return `${paramLabel(t, param)} ${optionLabel(t, param, a.from)} → ${optionLabel(t, param, a.to)}`;
|
||
});
|
||
if (modeChange) {
|
||
const labels = adapter.modeLabels;
|
||
items.unshift(
|
||
`${t('生成模式')} ${t(labels[modeChange.from] || modeChange.from)} → ${t(labels[modeChange.to] || modeChange.to)}`,
|
||
);
|
||
}
|
||
setAdjustments(items);
|
||
if (items.length) {
|
||
showInfo(
|
||
t('已按新模型调整:{{list}}(该模型不支持原取值)', {
|
||
list: items.join(';'),
|
||
}),
|
||
);
|
||
}
|
||
},
|
||
[adapter, t],
|
||
);
|
||
|
||
const applyModel = useCallback(
|
||
(next, { silent = false } = {}) => {
|
||
if (!next) return;
|
||
const from = formRef.current.modelName || '';
|
||
const r = switchModel(kind, formRef.current, next, {
|
||
sessionValues: sessionValuesRef.current,
|
||
});
|
||
commit(r.form);
|
||
if (!silent) {
|
||
notifyAdjustments(next, r.adjustments, r.modeChange);
|
||
trackCreationEvent('model_switch', {
|
||
kind,
|
||
from,
|
||
to: next.model,
|
||
migrated_params: (r.adjustments || []).map((a) => a.key),
|
||
});
|
||
}
|
||
},
|
||
[kind, commit, notifyAdjustments],
|
||
);
|
||
|
||
// schema 加载后:沿用记忆中的模型(仍可调用时)并按最新 schema 静默吸附一次
|
||
useEffect(() => {
|
||
if (modelsLoading || models.length === 0) return;
|
||
const current = models.find((m) => m.model === formRef.current.modelName);
|
||
if (current && !current.level_locked && schemaAppliedRef.current) return;
|
||
const target = initialModelOf(models, formRef.current.modelName);
|
||
if (target) {
|
||
schemaAppliedRef.current = true;
|
||
applyModel(target, { silent: true });
|
||
}
|
||
}, [models, modelsLoading, applyModel]);
|
||
|
||
const selectModel = useCallback(
|
||
(modelOrName) => {
|
||
const name = modelNameOf(modelOrName);
|
||
const next = models.find((m) => m.model === name);
|
||
if (!next) return false;
|
||
if (next.level_locked) {
|
||
showError(t('当前等级无权调用此模型,请选择其他模型'));
|
||
return false;
|
||
}
|
||
if (name === formRef.current.modelName) return true;
|
||
applyModel(next);
|
||
return true;
|
||
},
|
||
[models, applyModel, t],
|
||
);
|
||
|
||
const setMode = useCallback(
|
||
(mode) => {
|
||
if (selectedModel && !adapter.isModeEnabled(selectedModel, mode)) return;
|
||
commit({ ...formRef.current, mode, preferredMode: mode });
|
||
},
|
||
[adapter, selectedModel, commit],
|
||
);
|
||
|
||
const setPrompt = useCallback(
|
||
(prompt) => commit({ ...formRef.current, prompt: prompt || '' }),
|
||
[commit],
|
||
);
|
||
|
||
const setParam = useCallback(
|
||
(key, value) => {
|
||
sessionValuesRef.current = { ...sessionValuesRef.current, [key]: value };
|
||
const prev = formRef.current;
|
||
commit({ ...prev, params: { ...prev.params, [key]: value } });
|
||
},
|
||
[commit],
|
||
);
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 图片槽:COS + 上传开关都开启时先上传按 cos:// 引用提交,否则内联 base64
|
||
// ---------------------------------------------------------------------------
|
||
const cosEnabled =
|
||
status?.experience_center_cos_enabled === true ||
|
||
(kind === 'video' && creationData.image_input_enabled === true);
|
||
let fileUploadEnabled = false;
|
||
let uploadMaxMB = 10;
|
||
try {
|
||
fileUploadEnabled = getExperienceCenterBool(
|
||
status,
|
||
'experience_center_enable_file_upload',
|
||
'experience_center_enable_file_upload',
|
||
false,
|
||
);
|
||
uploadMaxMB = getExperienceCenterPositiveInt(
|
||
status,
|
||
'experience_center_upload_max_size',
|
||
'experience_center_upload_max_size',
|
||
10,
|
||
);
|
||
} catch (e) {
|
||
// localStorage 不可用时按默认值
|
||
}
|
||
const uploadByReference = cosEnabled && fileUploadEnabled;
|
||
const maxFileMB =
|
||
uploadByReference || kind === 'video' ? uploadMaxMB : INLINE_MAX_MB;
|
||
|
||
const patchSlot = useCallback(
|
||
(id, patch) => {
|
||
const prev = formRef.current;
|
||
commit({ ...prev, images: patchImageSlotById(prev.images, id, patch) });
|
||
},
|
||
[commit],
|
||
);
|
||
|
||
const uploadSlotFile = useCallback(
|
||
async (id, file) => {
|
||
const fd = new FormData();
|
||
fd.append('file', file);
|
||
try {
|
||
const res = await API.post('/api/user/upload/file', fd, {
|
||
skipErrorHandler: true,
|
||
});
|
||
const data = res?.data?.data;
|
||
if (!res?.data?.success || !data?.cos_path) {
|
||
throw new Error(res?.data?.message || t('上传失败'));
|
||
}
|
||
fileStoreRef.current.delete(id);
|
||
const current = allImageSlots(formRef.current.images).find(
|
||
(s) => s.id === id,
|
||
);
|
||
patchSlot(id, {
|
||
status: 'ready',
|
||
ref: `cos://${data.cos_path}`,
|
||
previewUrl: data.url || current?.previewUrl,
|
||
error: null,
|
||
});
|
||
} catch (err) {
|
||
patchSlot(id, {
|
||
status: 'error',
|
||
error: err?.response?.data?.message || err?.message || t('上传失败'),
|
||
});
|
||
}
|
||
},
|
||
[patchSlot, t],
|
||
);
|
||
|
||
/** 选择 / 拖入 / 粘贴图片放入槽位(参考图 index 缺省为追加)。 */
|
||
const pickImage = useCallback(
|
||
async (key, index, file) => {
|
||
if (!file) return false;
|
||
if (file.type && !file.type.startsWith('image/')) {
|
||
showError(t('请上传图片'));
|
||
return false;
|
||
}
|
||
if (maxFileMB > 0 && file.size > maxFileMB * 1024 * 1024) {
|
||
showError(t('图片不能超过 {{size}}MB', { size: maxFileMB }));
|
||
return false;
|
||
}
|
||
let dataUrl;
|
||
try {
|
||
dataUrl = await readAsDataURL(file);
|
||
} catch (e) {
|
||
showError(t('读取图片失败,请重新选择'));
|
||
return false;
|
||
}
|
||
const id = newSlotId();
|
||
const base = {
|
||
id,
|
||
name: file.name,
|
||
previewUrl: dataUrl,
|
||
identityType: 'aigc',
|
||
};
|
||
const slot = uploadByReference
|
||
? { ...base, status: 'uploading', source: 'upload' }
|
||
: { ...base, status: 'ready', ref: dataUrl, source: 'inline' };
|
||
const prev = formRef.current;
|
||
commit({
|
||
...prev,
|
||
images: writeImageSlot(prev.images, key, index, slot),
|
||
});
|
||
if (uploadByReference) {
|
||
fileStoreRef.current.set(id, file);
|
||
uploadSlotFile(id, file);
|
||
}
|
||
return true;
|
||
},
|
||
[t, maxFileMB, uploadByReference, uploadSlotFile, commit],
|
||
);
|
||
|
||
/** 放入一张可直接引用的图片(task:// / cos:// / 内联),不经上传。 */
|
||
const setImageRef = useCallback(
|
||
(key, index, { ref, previewUrl, source = 'task' }) => {
|
||
if (!ref) return;
|
||
const prev = formRef.current;
|
||
commit({
|
||
...prev,
|
||
images: writeImageSlot(prev.images, key, index, {
|
||
id: newSlotId(),
|
||
status: 'ready',
|
||
ref,
|
||
previewUrl: previewUrl || null,
|
||
source,
|
||
identityType: 'aigc',
|
||
}),
|
||
});
|
||
},
|
||
[commit],
|
||
);
|
||
|
||
const removeImage = useCallback(
|
||
(key, index) => {
|
||
const prev = formRef.current;
|
||
const target =
|
||
key === 'reference_images'
|
||
? (prev.images.reference_images || [])[index]
|
||
: prev.images[key];
|
||
if (target?.id) fileStoreRef.current.delete(target.id);
|
||
commit({
|
||
...prev,
|
||
images: writeImageSlot(prev.images, key, index, null),
|
||
});
|
||
},
|
||
[commit],
|
||
);
|
||
|
||
/** 整体替换图片槽(调整顺序 / 首尾帧切回图生等,槽对象原样保留)。 */
|
||
const setImages = useCallback(
|
||
(images) => {
|
||
if (!images) return;
|
||
commit({ ...formRef.current, images });
|
||
},
|
||
[commit],
|
||
);
|
||
|
||
const retryImage = useCallback(
|
||
(key, index, slot) => {
|
||
const file = slot?.id ? fileStoreRef.current.get(slot.id) : null;
|
||
if (!file) {
|
||
// 刷新页面后原文件已不在内存中:移除该槽,让用户重新选择
|
||
removeImage(key, index);
|
||
return;
|
||
}
|
||
patchSlot(slot.id, { status: 'uploading', error: null });
|
||
uploadSlotFile(slot.id, file);
|
||
},
|
||
[removeImage, patchSlot, uploadSlotFile],
|
||
);
|
||
|
||
/**
|
||
* 外部回填(复用参数 / 再生成)。filled = { modelName, mode, prompt, params, images }。
|
||
* autoSubmit(再生成):参数原样有效(无模型回退、无吸附、无模式变化)时回填后立即提交,
|
||
* 否则只回填并提示,由用户确认后再生成。notice:替换默认的"已回填参数"提示。
|
||
* @returns {boolean}
|
||
*/
|
||
const prefill = useCallback(
|
||
(filled, { autoSubmit = false, notice = '' } = {}) => {
|
||
const r = applyPrefill(kind, formRef.current, filled, models);
|
||
if (r.error) {
|
||
showError(
|
||
t('原模型 {{model}} 已不可用,请先选择可用模型', {
|
||
model: r.originalName || '-',
|
||
}),
|
||
);
|
||
return false;
|
||
}
|
||
if (r.fallback) {
|
||
showInfo(
|
||
t('原模型 {{model}} 已不可用,已保留当前模型', {
|
||
model: r.originalName,
|
||
}),
|
||
);
|
||
}
|
||
allImageSlots(formRef.current.images).forEach(
|
||
(slot) => slot.id && fileStoreRef.current.delete(slot.id),
|
||
);
|
||
sessionValuesRef.current = r.sessionValues;
|
||
schemaAppliedRef.current = true;
|
||
commit(r.form);
|
||
const target = models.find((m) => m.model === r.form.modelName);
|
||
const changed = Boolean(
|
||
r.fallback || r.adjustments.length || r.modeChange,
|
||
);
|
||
if (r.adjustments.length || r.modeChange) {
|
||
notifyAdjustments(target, r.adjustments, r.modeChange);
|
||
} else if (!autoSubmit) {
|
||
showInfo(notice || t('已回填参数'));
|
||
}
|
||
if (autoSubmit && !changed) {
|
||
autoSubmitRef.current = true;
|
||
} else {
|
||
if (autoSubmit) showInfo(t('参数已按当前模型调整,请确认后生成'));
|
||
requestFocus();
|
||
}
|
||
return true;
|
||
},
|
||
[kind, models, commit, notifyAdjustments, requestFocus, t],
|
||
);
|
||
|
||
/** 清空提示词与图片,参数回到当前模型的记忆 / 默认值(保留模型)。 */
|
||
const reset = useCallback(() => {
|
||
const prev = formRef.current;
|
||
allImageSlots(prev.images).forEach(
|
||
(slot) => slot.id && fileStoreRef.current.delete(slot.id),
|
||
);
|
||
sessionValuesRef.current = {};
|
||
const cleared = {
|
||
...prev,
|
||
prompt: '',
|
||
preferredMode: '',
|
||
mode: adapter.defaultMode,
|
||
images: { first_frame: null, last_frame: null, reference_images: [] },
|
||
};
|
||
if (selectedModel) {
|
||
const { values } = adapter.composeParams(selectedModel, {});
|
||
cleared.params = values;
|
||
cleared.mode = adapter.pickMode(selectedModel, adapter.defaultMode, {});
|
||
}
|
||
commit(cleared);
|
||
setAdjustments([]);
|
||
}, [adapter, selectedModel, commit]);
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 并发上限、估价、提交
|
||
// ---------------------------------------------------------------------------
|
||
const [serverRunning, setServerRunning] = useState(0);
|
||
const [maxRunningOverride, setMaxRunningOverride] = useState(0);
|
||
useEffect(() => {
|
||
setServerRunning(Number(creationData.running_tasks) || 0);
|
||
}, [creationData.running_tasks]);
|
||
// 作品流中有任务结束时,以本地统计为准(服务端数字只在加载 / 429 时刷新)
|
||
const prevLocalRef = useRef(localRunning);
|
||
useEffect(() => {
|
||
if (localRunning < prevLocalRef.current) setServerRunning(0);
|
||
prevLocalRef.current = localRunning;
|
||
}, [localRunning]);
|
||
const maxRunning =
|
||
maxRunningOverride || Number(creationData.max_running_tasks) || 0;
|
||
const runningCount = Math.max(localRunning, serverRunning);
|
||
const runningLimitReached = maxRunning > 0 && runningCount >= maxRunning;
|
||
|
||
const payload = useMemo(
|
||
() => buildPayload(kind, selectedModel, form),
|
||
[kind, selectedModel, form],
|
||
);
|
||
const quoteRequest = useMemo(
|
||
() => buildQuoteRequest(kind, selectedModel, payload),
|
||
[kind, selectedModel, payload],
|
||
);
|
||
const quoteState = useCreationQuote(quoteRequest);
|
||
const budgetShortfall = useMemo(
|
||
() => budgetShortfallOf(quoteState.quote),
|
||
[quoteState.quote],
|
||
);
|
||
|
||
// 埋点:每次拿到新的估价结果记一次 quote_shown
|
||
useEffect(() => {
|
||
const q = quoteState.quote;
|
||
if (!q) return;
|
||
trackCreationEvent('quote_shown', {
|
||
kind,
|
||
model: formRef.current.modelName,
|
||
approximate: Boolean(q.approximate || q.items?.[0]?.approximate),
|
||
});
|
||
}, [kind, quoteState.quote]);
|
||
|
||
// 最近一次提交失败(统一错误映射,创作台内联展示 + 下一步动作)
|
||
const [lastError, setLastError] = useState(null);
|
||
const clearError = useCallback(() => setLastError(null), []);
|
||
const clearAdjustments = useCallback(() => setAdjustments([]), []);
|
||
|
||
const submitBlock = useMemo(() => {
|
||
if (modelsLoading) return t('模型列表加载中');
|
||
if (modelsError && models.length === 0) return t('模型列表加载失败');
|
||
if (allLocked) return t('当前等级暂无可用模型,升级后即可使用');
|
||
const reason = formBlockReason(kind, selectedModel, form);
|
||
if (reason) return t(reason.key);
|
||
if (runningLimitReached) {
|
||
return t('已有 {{n}} 个任务进行中,完成后可继续', { n: runningCount });
|
||
}
|
||
return '';
|
||
}, [
|
||
kind,
|
||
modelsLoading,
|
||
modelsError,
|
||
models.length,
|
||
allLocked,
|
||
selectedModel,
|
||
form,
|
||
runningLimitReached,
|
||
runningCount,
|
||
t,
|
||
]);
|
||
|
||
const [submitting, setSubmitting] = useState(false);
|
||
const submittingRef = useRef(false);
|
||
const submitFn = useMemo(
|
||
() => submitter || defaultSubmitter(kind),
|
||
[submitter, kind],
|
||
);
|
||
|
||
const submit = useCallback(async () => {
|
||
if (submittingRef.current) return false;
|
||
if (submitBlock) {
|
||
showError(submitBlock);
|
||
return false;
|
||
}
|
||
if (!payload) return false;
|
||
submittingRef.current = true;
|
||
setSubmitting(true);
|
||
setLastError(null);
|
||
try {
|
||
const result = await submitFn(payload);
|
||
if (result?.ok) {
|
||
if (kind === 'video') showInfo(t('视频生成任务已提交,请稍候...'));
|
||
setAdjustments([]);
|
||
trackCreationEvent('submit', {
|
||
kind,
|
||
model: payload.model,
|
||
mode: payload.mode || formRef.current.mode,
|
||
batch_size: Number(payload.n) || 1,
|
||
});
|
||
if (onSubmitted) onSubmitted(result, payload);
|
||
return true;
|
||
}
|
||
const running = Number(result?.data?.running_tasks) || 0;
|
||
if (result?.code === 'too_many_running_tasks') {
|
||
const max = Number(result.data?.max_running_tasks) || 0;
|
||
if (running > 0) setServerRunning(running);
|
||
if (max > 0) setMaxRunningOverride(max);
|
||
}
|
||
const info = classifyCreationError(
|
||
{
|
||
code: result?.code,
|
||
message: result?.message,
|
||
status: result?.status,
|
||
},
|
||
{ running },
|
||
);
|
||
// 引用的原图已失效:标记可能失效的槽位,用户点槽位即可重新上传
|
||
if (info.category === 'image_expired') {
|
||
const marked = markExpiredSlots(formRef.current.images);
|
||
if (marked.count) commit({ ...formRef.current, images: marked.images });
|
||
}
|
||
const text = describeCreationError(t, info);
|
||
setLastError({ ...info, ...text });
|
||
showError(text.detail ? `${text.title}:${text.detail}` : text.title);
|
||
return false;
|
||
} finally {
|
||
submittingRef.current = false;
|
||
setSubmitting(false);
|
||
}
|
||
}, [submitBlock, payload, submitFn, kind, onSubmitted, commit, t]);
|
||
|
||
/**
|
||
* 套用灵感模板(WP B-7 模板墙 / 模板弹层):推荐模型可用时切换(静默吸附),
|
||
* 再填入提示词与推荐参数(只套用新模型支持的合法值),最后展开并聚焦创作台。
|
||
*/
|
||
const applyTemplate = useCallback(
|
||
(tpl) => {
|
||
if (!tpl) return false;
|
||
const target = templateModelFor(kind, tpl, models, selectedModel);
|
||
if (target && target.model !== formRef.current.modelName) {
|
||
applyModel(target, { silent: true });
|
||
}
|
||
const values = templateParamsFor(
|
||
adapter.requestParamsOf(target || selectedModel),
|
||
tpl.params,
|
||
);
|
||
sessionValuesRef.current = { ...sessionValuesRef.current, ...values };
|
||
const prev = formRef.current;
|
||
commit({
|
||
...prev,
|
||
prompt: tpl.prompt || prev.prompt,
|
||
params: { ...prev.params, ...values },
|
||
});
|
||
setLastError(null);
|
||
requestFocus();
|
||
return true;
|
||
},
|
||
[kind, models, selectedModel, applyModel, adapter, commit, requestFocus],
|
||
);
|
||
|
||
// 再生成 / 换种子再来:回填已提交到状态后执行一次提交;被阻断(如并发上限)时提示并聚焦创作台。
|
||
// 多张(n>1)与手动提交同一金额阈值:等当前参数的估价返回,超阈值弹同一二次确认,
|
||
// 拿不到估价时不自动提交(WP D-1)。
|
||
const confirmThreshold = status?.experience_center_batch_confirm_threshold;
|
||
useEffect(() => {
|
||
if (!autoSubmitRef.current) return;
|
||
if (submitBlock) {
|
||
autoSubmitRef.current = false;
|
||
showError(submitBlock);
|
||
requestFocus();
|
||
return;
|
||
}
|
||
const n = Number(payload?.n) || 1;
|
||
const decision = autoSubmitDecision({
|
||
n,
|
||
threshold: confirmThreshold,
|
||
quote: quoteState.quote,
|
||
quoteFresh: quoteState.fresh && !quoteState.loading,
|
||
quoteFailed: quoteState.failed,
|
||
});
|
||
if (decision === 'wait') return;
|
||
autoSubmitRef.current = false;
|
||
if (decision === 'confirm') {
|
||
openBatchConfirm({
|
||
t,
|
||
n,
|
||
quote: quoteState.quote,
|
||
onOk: submit,
|
||
onCancel: requestFocus,
|
||
});
|
||
return;
|
||
}
|
||
if (decision === 'manual') {
|
||
// 多张但暂时拿不到估价:只回填,由用户看过价格后手动生成
|
||
showInfo(t('已回填参数'));
|
||
requestFocus();
|
||
return;
|
||
}
|
||
submit();
|
||
}, [
|
||
form,
|
||
payload,
|
||
submitBlock,
|
||
submit,
|
||
requestFocus,
|
||
confirmThreshold,
|
||
quoteState.quote,
|
||
quoteState.fresh,
|
||
quoteState.loading,
|
||
quoteState.failed,
|
||
t,
|
||
]);
|
||
|
||
const modeOptions = useMemo(
|
||
() => adapter.modeOptionsOf(selectedModel),
|
||
[adapter, selectedModel],
|
||
);
|
||
const imageSlots = useMemo(
|
||
() =>
|
||
selectedModel
|
||
? adapter.slotsOf(selectedModel, form.mode, form.images)
|
||
: [],
|
||
[adapter, selectedModel, form.mode, form.images],
|
||
);
|
||
// 只显示适用于当前模式的参数(schema modes),与 buildPayload 的提交口径一致
|
||
const visibleParams = useMemo(
|
||
() => visibleParamsOf(kind, selectedModel, form.mode),
|
||
[kind, selectedModel, form.mode],
|
||
);
|
||
|
||
return {
|
||
kind,
|
||
form,
|
||
// 模型 schema
|
||
creationData,
|
||
models,
|
||
modelsLoading,
|
||
modelsError,
|
||
reloadModels,
|
||
selectedModel,
|
||
selectModel,
|
||
// 模式 / 提示词 / 参数
|
||
mode: form.mode,
|
||
modeOptions,
|
||
setMode,
|
||
prompt: form.prompt,
|
||
setPrompt,
|
||
params: form.params,
|
||
visibleParams,
|
||
setParam,
|
||
adjustments,
|
||
clearAdjustments,
|
||
applyTemplate,
|
||
allLocked,
|
||
// 图片
|
||
imageSlots,
|
||
pickImage,
|
||
setImageRef,
|
||
removeImage,
|
||
retryImage,
|
||
setImages,
|
||
uploadByReference,
|
||
cosEnabled,
|
||
// 估价 / 提交
|
||
payload,
|
||
quote: quoteState.quote,
|
||
quoteLoading: quoteState.loading,
|
||
quoteFailed: quoteState.failed,
|
||
// 估价对应当前参数且已返回(不是上一次参数的残留结果)
|
||
quoteFresh: quoteState.fresh && !quoteState.loading,
|
||
budgetShortfall,
|
||
lastError,
|
||
clearError,
|
||
estSeconds: selectedModel?.est_seconds?.p50 || 0,
|
||
submitBlock,
|
||
submitting,
|
||
runningCount,
|
||
maxRunning,
|
||
submit,
|
||
// 回填
|
||
prefill,
|
||
reset,
|
||
focusTick,
|
||
requestFocus,
|
||
};
|
||
};
|
||
|
||
export default useCreationForm;
|