Files
monkey-ai-web/src/hooks/creation/creationTasks.test.js
T
qiubaishen 6160a23117 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 里登录页只显示站内登录方式
2026-11-10 11:05:34 +08:00

445 lines
14 KiB
JavaScript

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import {
activeFilterCount,
appendPage,
applyUpdates,
aspectRatioOf,
buildListParams,
chunkIds,
elapsedSeconds,
facetsOf,
filterTasks,
finishedTransitions,
formatSeconds,
groupTasksByDate,
mergeTask,
nextPollDelay,
nextPollStep,
normalizeImageTask,
normalizeVideoTask,
optimisticTask,
parseLegacyFavorites,
pickPollBatch,
serverFilterKey,
taskImageRef,
taskStatusOf,
toMs,
upsertTop,
CLIENT_FILTER_EMPTY_PAGE_LIMIT,
hasClientFilter,
nextEmptyStreak,
shouldAutoLoad,
isSlowTask,
taskLastFrameRef,
variationParams,
} from './creationTasks.js';
test('taskStatusOf maps backend statuses', () => {
assert.equal(taskStatusOf('NOT_START'), 'queued');
assert.equal(taskStatusOf('SUBMITTED'), 'queued');
assert.equal(taskStatusOf('QUEUED'), 'queued');
assert.equal(taskStatusOf('IN_PROGRESS'), 'running');
assert.equal(taskStatusOf('SUCCESS'), 'success');
assert.equal(taskStatusOf('FAILURE'), 'failed');
assert.equal(taskStatusOf('UNKNOWN'), 'running');
});
test('toMs accepts seconds, ms, numeric strings and ISO', () => {
assert.equal(toMs(1700000000), 1700000000000);
assert.equal(toMs(1700000000000), 1700000000000);
assert.equal(toMs('1700000000'), 1700000000000);
assert.equal(
toMs('2024-01-01T00:00:00Z'),
Date.parse('2024-01-01T00:00:00Z'),
);
assert.equal(toMs(0), 0);
assert.equal(toMs('bad'), 0);
});
test('normalizeImageTask reads results, refunds and favorites', () => {
const task = normalizeImageTask({
id: 7,
task_id: 'img_1',
status: 'SUCCESS',
progress: '100%',
created_at: 1700000000,
properties: { input: 'from props', origin_model_name: 'gpt-image-1' },
data: JSON.stringify({
size: '1024x1536',
n: 2,
data: [
{ url: 'https://a/1.png', reusable_as_input: true },
{ b64_json: 'xx' },
],
}),
refunded_quota: 0,
quoted_quota: 500,
favorited: true,
});
assert.equal(task.id, 'img_1');
assert.equal(task.status, 'success');
assert.equal(task.prompt, 'from props');
assert.equal(task.model, 'gpt-image-1');
assert.equal(task.width, 1024);
assert.equal(task.height, 1536);
assert.equal(task.n, 2);
assert.deepEqual(task.images, [
{ url: 'https://a/1.png', reusable: true, hasB64: false },
{ url: '', reusable: false, hasB64: true },
]);
assert.equal(task.favorited, true);
assert.equal(task.quotedQuota, 500);
assert.equal(task.createdAt, 1700000000000);
});
test('normalizeVideoTask reads detail fields', () => {
const list = normalizeVideoTask({
task_id: 'v1',
status: 'SUCCESS',
model: 'seedance',
prompt: 'p',
created_at: 1700000000,
});
assert.equal(list.hydrated, false);
assert.equal(list.videoUrl, '');
const detail = normalizeVideoTask({
task_id: 'v1',
status: 'SUCCESS',
data: { video_url: ' https://v/1.mp4 ' },
request: { duration: 5, aspect_ratio: '9:16', resolution: '720p' },
refunded_quota: 120,
cancelable: false,
reusable_as_input: true,
});
assert.equal(detail.hydrated, true);
assert.equal(detail.videoUrl, 'https://v/1.mp4');
assert.equal(detail.duration, 5);
assert.equal(detail.ratio, '9:16');
assert.equal(detail.refundedQuota, 120);
assert.equal(detail.reusableAsInput, true);
});
test('optimisticTask builds a queued card from the submit response', () => {
const img = optimisticTask(
'image',
{ id: 1, task_id: 'img_9', status: 'NOT_START', created_at: 1700000000 },
{ model: 'm', prompt: 'cat', size: '512x512', n: 4 },
);
assert.equal(img.id, 'img_9');
assert.equal(img.status, 'queued');
assert.equal(img.n, 4);
assert.equal(img.prompt, 'cat');
assert.equal(img.optimistic, true);
const vid = optimisticTask(
'video',
{ task_id: 'v9', status: 'SUBMITTED' },
{ model: 'k', prompt: 'run', duration: 5, aspect_ratio: '16:9' },
);
assert.equal(vid.id, 'v9');
assert.equal(vid.duration, 5);
assert.equal(vid.ratio, '16:9');
assert.equal(vid.model, 'k');
});
test('mergeTask keeps detail fields that the poll result lacks', () => {
const prev = normalizeVideoTask({
task_id: 'v1',
status: 'IN_PROGRESS',
request: { duration: 5, prompt: 'p' },
data: { video_url: 'https://v/old.mp4' },
});
const next = normalizeVideoTask({
task_id: 'v1',
status: 'SUCCESS',
progress: '100%',
});
const merged = mergeTask(prev, next);
assert.equal(merged.status, 'success');
assert.equal(merged.duration, 5);
assert.equal(merged.videoUrl, 'https://v/old.mp4');
assert.deepEqual(merged.request, { duration: 5, prompt: 'p' });
assert.equal(merged.hydrated, true);
});
test('applyUpdates / appendPage / upsertTop keep order and dedupe', () => {
const a = { id: 'a', kind: 'image', status: 'running', progress: 0 };
const b = { id: 'b', kind: 'image', status: 'success', progress: 100 };
const list = [a, b];
assert.equal(applyUpdates(list, []), list);
const updated = applyUpdates(list, [
{ ...a, status: 'success' },
{ id: 'zzz', kind: 'image', status: 'success' },
]);
assert.deepEqual(
updated.map((t) => [t.id, t.status]),
[
['a', 'success'],
['b', 'success'],
],
);
const appended = appendPage(list, [{ ...b, prompt: 'x' }, { id: 'c' }]);
assert.deepEqual(
appended.map((t) => t.id),
['a', 'b', 'c'],
);
assert.equal(appended[1].prompt, 'x');
const top = upsertTop(list, { ...b, status: 'queued' });
assert.deepEqual(
top.map((t) => t.id),
['b', 'a'],
);
assert.equal(top[0].status, 'queued');
});
test('finishedTransitions reports tasks that left the active state', () => {
const prev = [
{ id: 'a', status: 'running' },
{ id: 'b', status: 'queued' },
{ id: 'c', status: 'success' },
];
const out = finishedTransitions(prev, [
{ id: 'a', status: 'success' },
{ id: 'b', status: 'running' },
{ id: 'c', status: 'success' },
]);
assert.deepEqual(
out.map((t) => t.id),
['a'],
);
});
test('pickPollBatch rotates when more than the limit are active', () => {
const ids = Array.from({ length: 25 }, (_, i) => `t${i}`);
const first = pickPollBatch(ids, 0, 20);
assert.equal(first.batch.length, 20);
assert.equal(first.batch[0], 't0');
const second = pickPollBatch(ids, first.cursor, 20);
assert.equal(second.batch[0], 't20');
assert.ok(second.batch.includes('t24'));
assert.ok(second.batch.includes('t0'));
const small = pickPollBatch(['a', 'a', 'b'], 5, 20);
assert.deepEqual(small, { batch: ['a', 'b'], cursor: 0 });
});
test('backoff schedule is 3s → 5s → 10s, slow when hidden', () => {
let step = 0;
const delays = [];
for (let i = 0; i < 4; i += 1) {
delays.push(nextPollDelay(step, false));
step = nextPollStep(step, false);
}
assert.deepEqual(delays, [3000, 5000, 10000, 10000]);
assert.equal(nextPollStep(3, true), 0);
assert.equal(nextPollDelay(0, true), 30000);
});
test('chunkIds splits into batches of 20', () => {
const ids = Array.from({ length: 41 }, (_, i) => String(i));
assert.deepEqual(
chunkIds(ids).map((c) => c.length),
[20, 20, 1],
);
});
test('buildListParams uses p= and server-side filters', () => {
assert.deepEqual(buildListParams({}, 2), { p: 2, page_size: 20 });
assert.deepEqual(
buildListParams({ status: 'success', favoritesOnly: true }, 1, 10),
{ p: 1, page_size: 10, status: 'SUCCESS', favorited: 'true' },
);
assert.deepEqual(buildListParams({ status: 'failed' }, 0), {
p: 1,
page_size: 20,
status: 'FAILURE',
});
// "进行中" 包含多个后端状态,只在本地过滤
assert.deepEqual(buildListParams({ status: 'active' }), {
p: 1,
page_size: 20,
});
assert.equal(
serverFilterKey({ status: 'active', keyword: 'x' }),
serverFilterKey({}),
);
assert.notEqual(
serverFilterKey({ favoritesOnly: true }),
serverFilterKey({}),
);
});
test('filterTasks applies status, model, size, keyword and favorites', () => {
const list = [
{ id: '1', status: 'running', model: 'a', size: '1x1', prompt: 'Cat' },
{ id: '2', status: 'success', model: 'b', size: '2x2', prompt: 'dog' },
{
id: '3',
status: 'failed',
model: 'a',
size: '2x2',
prompt: 'bird',
favorited: true,
},
];
const ids = (f) => filterTasks(list, f).map((t) => t.id);
assert.deepEqual(ids({}), ['1', '2', '3']);
assert.deepEqual(ids({ status: 'active' }), ['1']);
assert.deepEqual(ids({ model: 'a' }), ['1', '3']);
assert.deepEqual(ids({ size: '2x2' }), ['2', '3']);
assert.deepEqual(ids({ keyword: ' CAT ' }), ['1']);
assert.deepEqual(ids({ keyword: 'b' }), ['2', '3']); // 匹配模型名
assert.deepEqual(ids({ favoritesOnly: true }), ['3']);
assert.equal(activeFilterCount({ status: 'failed', keyword: 'x' }), 2);
assert.deepEqual(facetsOf(list), {
models: ['a', 'b'],
sizes: ['1x1', '2x2'],
});
});
test('groupTasksByDate puts active tasks first then by day', () => {
const now = new Date(2026, 10, 1, 15, 0, 0).getTime();
const day = 24 * 3600 * 1000;
const list = [
{ id: 'old', status: 'success', createdAt: now - 30 * day },
{ id: 'run', status: 'running', createdAt: now - 3 * day },
{ id: 'today1', status: 'success', createdAt: now - 3600 * 1000 },
{ id: 'today2', status: 'failed', createdAt: now - 60 * 1000 },
{ id: 'yday', status: 'success', createdAt: now - day },
{ id: 'week', status: 'success', createdAt: now - 4 * day },
];
const groups = groupTasksByDate(list, now);
assert.deepEqual(
groups.map((g) => [g.key, g.tasks.map((t) => t.id)]),
[
['active', ['run']],
['today', ['today2', 'today1']],
['yesterday', ['yday']],
['week', ['week']],
['older', ['old']],
],
);
assert.deepEqual(groupTasksByDate([], now), []);
});
test('elapsed / format helpers', () => {
assert.equal(elapsedSeconds({ startedAt: 1000 }, 43500), 42);
assert.equal(elapsedSeconds({}, 5000), 0);
assert.equal(formatSeconds(42), '42s');
assert.equal(formatSeconds(65), '1:05');
assert.equal(formatSeconds(3723), '1:02:03');
});
test('aspectRatioOf clamps extreme ratios', () => {
assert.equal(aspectRatioOf({ kind: 'image', width: 1024, height: 1024 }), 1);
assert.equal(aspectRatioOf({ kind: 'video', ratio: '16:9' }), 16 / 9);
assert.equal(aspectRatioOf({ kind: 'video', ratio: '9:16' }), 3 / 4);
assert.equal(aspectRatioOf({ kind: 'video', ratio: '' }), 16 / 9);
assert.equal(
aspectRatioOf({ kind: 'image', width: 4000, height: 1000 }),
16 / 9,
);
});
test('parseLegacyFavorites tolerates bad data', () => {
assert.deepEqual(parseLegacyFavorites(null), []);
assert.deepEqual(parseLegacyFavorites('{oops'), []);
assert.deepEqual(parseLegacyFavorites('{"a":1}'), []);
assert.deepEqual(
parseLegacyFavorites('["a", " a ", 12, 1.5, -1, null, "b"]'),
['a', '12', 'b'],
);
});
test('taskImageRef uses 0-based fragments', () => {
assert.equal(taskImageRef('t1'), 'task://t1');
assert.equal(taskImageRef('t1', 2), 'task://t1#2');
});
test('client-side filters stop auto-loading after empty pages', () => {
assert.equal(hasClientFilter({}), false);
assert.equal(
hasClientFilter({ status: 'success', favoritesOnly: true }),
false,
);
assert.equal(hasClientFilter({ status: 'active' }), true);
assert.equal(hasClientFilter({ keyword: ' cat ' }), true);
assert.equal(hasClientFilter({ model: 'm' }), true);
assert.equal(hasClientFilter({ size: '1024x1024' }), true);
assert.equal(nextEmptyStreak(2, 5, 6), 0);
assert.equal(nextEmptyStreak(2, 5, 5), 3);
const f = { keyword: 'cat' };
assert.equal(shouldAutoLoad(f, CLIENT_FILTER_EMPTY_PAGE_LIMIT - 1), true);
assert.equal(shouldAutoLoad(f, CLIENT_FILTER_EMPTY_PAGE_LIMIT), false);
// 服务端筛选不受限制
assert.equal(shouldAutoLoad({ status: 'failed' }, 99), true);
});
test('C-2 batch_id:列表项归一化、乐观插入、合并保留', () => {
const task = normalizeImageTask({
task_id: 't',
status: 'SUCCESS',
batch_id: 'b-1',
});
assert.equal(task.batchId, 'b-1');
assert.equal(normalizeImageTask({ task_id: 't' }).batchId, '');
const optimistic = optimisticTask(
'image',
{ task_id: 'o' },
{ model: 'm', batch_id: 'b-2' },
);
assert.equal(optimistic.batchId, 'b-2');
// 轮询口径没带 batch_id 时保留
assert.equal(
mergeTask(optimistic, { ...optimistic, batchId: '' }).batchId,
'b-2',
);
});
test('C-4 isSlowTask:进行中且超过 p90', () => {
const now = 1_800_000_000_000;
const running = { status: 'running', startedAt: now - 100_000 };
assert.equal(isSlowTask(running, 90, now), true);
assert.equal(isSlowTask(running, 120, now), false);
assert.equal(isSlowTask(running, 0, now), false);
assert.equal(isSlowTask({ ...running, status: 'success' }, 10, now), false);
});
test('C-3 variationParams / taskLastFrameRef', () => {
const seq = [0.5, 0.5];
const rand = () => seq.shift() ?? 0;
const r = variationParams(
{ seed: 7, size: '1x1' },
{ min: 0, max: 100 },
rand,
);
assert.equal(r.size, '1x1');
assert.equal(r.seed, 50);
// 与原种子相同时换一个
assert.notEqual(
variationParams({ seed: 50 }, { min: 0, max: 100 }, () => 0.5).seed,
50,
);
const d = variationParams({}, null, () => 0.999999);
assert.ok(d.seed >= 0 && d.seed <= 2147483647);
assert.equal(taskLastFrameRef('v1'), 'task://v1#last_frame');
});