/* 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 . 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'); });