mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-08-07 14:30:15 -03:00
feat(downloads): show batch download summary with failure details and retry
This commit is contained in:
438
tests/frontend/components/downloadBatchSummary.test.js
Normal file
438
tests/frontend/components/downloadBatchSummary.test.js
Normal file
@@ -0,0 +1,438 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
SUMMARY_MODULE,
|
||||
I18N_HELPERS_MODULE,
|
||||
UI_HELPERS_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
SUMMARY_MODULE: new URL('../../../static/js/components/DownloadBatchSummaryModal.js', import.meta.url).pathname,
|
||||
I18N_HELPERS_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
const showToastMock = vi.hoisted(() => vi.fn());
|
||||
const openHuggingFaceMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock(I18N_HELPERS_MODULE, () => ({
|
||||
translate: vi.fn((_key, _params, fallback) => fallback ?? ''),
|
||||
}));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: showToastMock,
|
||||
openHuggingFace: openHuggingFaceMock,
|
||||
}));
|
||||
|
||||
// A realistic failure payload from the backend: a JSON envelope whose `error`
|
||||
// field embeds an HTTP status and a nested JSON body (Civitai Early Access).
|
||||
const REAL_ERROR = '{"success": false, "error": "Failed to resolve authenticated Civitai redirect: status=403 body={\\"error\\":\\"Early Access\\",\\"deadline\\":\\"2026-08-12T08:18:36.063Z\\",\\"message\\":\\"This asset is in Early Access. You can use Buzz access it now!\\"}", "download_id": "1786065633067"}';
|
||||
|
||||
// The human-readable error the component should derive from REAL_ERROR.
|
||||
const FORMATTED_REAL_ERROR = 'HTTP 403 — This asset is in Early Access. You can use Buzz access it now!';
|
||||
|
||||
describe('DownloadBatchSummaryModal', () => {
|
||||
let showDownloadBatchSummary;
|
||||
|
||||
beforeEach(async () => {
|
||||
document.body.innerHTML = '';
|
||||
showToastMock.mockClear();
|
||||
openHuggingFaceMock.mockClear();
|
||||
({ showDownloadBatchSummary } = await import(SUMMARY_MODULE));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
delete navigator.clipboard;
|
||||
delete document.execCommand;
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('renders a warning summary with stat cards and a failure table on partial success', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 3,
|
||||
completed: 2,
|
||||
failedItems: [
|
||||
{ item: { displayName: 'LoraA' }, error: 'timeout' },
|
||||
{ item: { name: 'LoraB' }, error: '404' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const modal = document.getElementById('downloadBatchSummaryModal');
|
||||
expect(modal).not.toBeNull();
|
||||
expect(modal.querySelector('.summary-header').classList.contains('warning')).toBe(true);
|
||||
|
||||
// Success / Failed / Total stat cards.
|
||||
const statValues = Array.from(modal.querySelectorAll('.stat-card-value')).map(el => el.textContent);
|
||||
expect(statValues).toEqual(['2', '2', '3']);
|
||||
|
||||
const rows = modal.querySelectorAll('.failure-table tbody tr');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].querySelector('.failure-name').textContent).toBe('LoraA');
|
||||
expect(rows[0].querySelector('.failure-error').textContent).toBe('timeout');
|
||||
expect(rows[1].querySelector('.failure-name').textContent).toBe('LoraB');
|
||||
expect(rows[1].querySelector('.failure-error').textContent).toBe('404');
|
||||
|
||||
expect(modal.querySelector('[data-action="retry-failed"]').textContent).toContain('Retry Failed (2)');
|
||||
expect(modal.querySelector('[data-action="copy-report"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('renders an error header when every download failed', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 2,
|
||||
completed: 0,
|
||||
failedItems: [
|
||||
{ item: { displayName: 'LoraA' }, error: 'timeout' },
|
||||
{ item: { displayName: 'LoraB' }, error: '404' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const modal = document.getElementById('downloadBatchSummaryModal');
|
||||
expect(modal.querySelector('.summary-header').classList.contains('error')).toBe(true);
|
||||
expect(modal.querySelector('.summary-title').textContent).toBe('Download failed');
|
||||
});
|
||||
|
||||
it('renders a success summary without a failure table or retry button', () => {
|
||||
showDownloadBatchSummary({ total: 2, completed: 2, failedItems: [], onRetry: vi.fn() });
|
||||
|
||||
const modal = document.getElementById('downloadBatchSummaryModal');
|
||||
expect(modal.querySelector('.summary-header').classList.contains('success')).toBe(true);
|
||||
expect(modal.querySelector('.failure-table')).toBeNull();
|
||||
expect(modal.querySelector('[data-action="retry-failed"]')).toBeNull();
|
||||
expect(modal.querySelector('.refresh-success-message')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('escapes HTML in failed item names and errors', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [
|
||||
{ item: { name: '<img src=x onerror=alert(1)>', url: 'https://example.com/xss-model' }, error: '<script>bad()</script>' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const nameCell = document.querySelector('.failure-name');
|
||||
const errorCell = document.querySelector('.failure-error');
|
||||
|
||||
// The URL resolves, so the name renders inside the failure link; the
|
||||
// escaped entities must render back to the literal payload as text...
|
||||
expect(nameCell.querySelector('a.failure-link')).not.toBeNull();
|
||||
expect(nameCell.textContent).toContain('<img src=x onerror=alert(1)>');
|
||||
expect(errorCell.textContent).toContain('<script>bad()</script>');
|
||||
// ...and never as live DOM nodes.
|
||||
expect(document.querySelector('.failure-table img')).toBeNull();
|
||||
expect(document.querySelector('.failure-table script')).toBeNull();
|
||||
expect(nameCell.innerHTML).toContain('<img');
|
||||
});
|
||||
|
||||
it('removes the modal and invokes onRetry with the original failed items', () => {
|
||||
const onRetry = vi.fn();
|
||||
const failedItems = [{ item: { displayName: 'LoraA' }, error: 'timeout' }];
|
||||
showDownloadBatchSummary({ total: 3, completed: 2, failedItems, onRetry });
|
||||
|
||||
document.querySelector('[data-action="retry-failed"]').click();
|
||||
|
||||
expect(document.getElementById('downloadBatchSummaryModal')).toBeNull();
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
expect(onRetry).toHaveBeenCalledWith(failedItems);
|
||||
// Same object references, not copies.
|
||||
expect(onRetry.mock.calls[0][0][0]).toBe(failedItems[0]);
|
||||
});
|
||||
|
||||
it('closes the modal via the close action without retrying', () => {
|
||||
const onRetry = vi.fn();
|
||||
showDownloadBatchSummary({
|
||||
total: 2,
|
||||
completed: 1,
|
||||
failedItems: [{ item: { name: 'LoraA' }, error: 'timeout' }],
|
||||
onRetry,
|
||||
});
|
||||
|
||||
document.querySelector('.cancel-btn[data-action="close-modal"]').click();
|
||||
|
||||
expect(document.getElementById('downloadBatchSummaryModal')).toBeNull();
|
||||
expect(onRetry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('copies a plain-text batch report to the clipboard', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
|
||||
|
||||
showDownloadBatchSummary({
|
||||
total: 3,
|
||||
completed: 2,
|
||||
failedItems: [
|
||||
{ item: { displayName: 'LoraA', url: 'https://civitai.red/models/111/lora-a?modelVersionId=222' }, error: 'timeout' },
|
||||
{ item: { name: 'LoraB', url: 'https://example.com/lora-b' }, error: '404' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('[data-action="copy-report"]').click();
|
||||
|
||||
// writeText is invoked synchronously by the click handler.
|
||||
expect(writeText).toHaveBeenCalledTimes(1);
|
||||
const text = writeText.mock.calls[0][0];
|
||||
expect(text).toContain('Batch Download Report');
|
||||
expect(text).toContain('Total: 3');
|
||||
expect(text).toContain('LoraA — timeout');
|
||||
expect(text).toContain('LoraB — 404');
|
||||
|
||||
// Each failed item with a URL gets an indented URL line right after it.
|
||||
expect(text).toContain(' URL: https://civitai.red/models/111/lora-a?modelVersionId=222');
|
||||
expect(text).toContain(' URL: https://example.com/lora-b');
|
||||
// Exactly the two URLs from the failed items — nothing more, no undefined.
|
||||
expect(text.match(/^\s+URL:/gm)).toHaveLength(2);
|
||||
expect(text).not.toContain('URL: undefined');
|
||||
|
||||
// The toast fires after the mocked clipboard promise settles.
|
||||
await vi.waitFor(() => expect(showToastMock).toHaveBeenCalledTimes(1));
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.api.copiedToClipboard', {}, 'success');
|
||||
});
|
||||
|
||||
it('omits the URL line for failed items without a resolvable url', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
|
||||
|
||||
showDownloadBatchSummary({
|
||||
total: 2,
|
||||
completed: 0,
|
||||
failedItems: [
|
||||
{ item: { name: 'WithUrl', url: 'https://example.com/with-url' }, error: 'boom' },
|
||||
{ item: { name: 'NoUrl' }, error: 'boom' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('[data-action="copy-report"]').click();
|
||||
|
||||
const text = writeText.mock.calls[0][0];
|
||||
expect(text).toContain(' URL: https://example.com/with-url');
|
||||
// Only the one URL line exists — the URL-less item contributes none.
|
||||
expect(text.match(/^\s+URL:/gm)).toHaveLength(1);
|
||||
expect(text).not.toContain(' URL: undefined');
|
||||
expect(text).not.toContain(' URL: null');
|
||||
|
||||
await vi.waitFor(() => expect(showToastMock).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
it('falls back to execCommand when navigator.clipboard is unavailable', async () => {
|
||||
// afterEach deletes navigator.clipboard, but be explicit so this test is
|
||||
// robust even if a previous test failed before its cleanup ran.
|
||||
delete navigator.clipboard;
|
||||
// jsdom does not implement document.execCommand, so install a mock for the
|
||||
// fallback path (removed by the afterEach cleanup above).
|
||||
const execCommandMock = vi.fn(() => true);
|
||||
document.execCommand = execCommandMock;
|
||||
|
||||
showDownloadBatchSummary({
|
||||
total: 3,
|
||||
completed: 2,
|
||||
failedItems: [
|
||||
{ item: { displayName: 'LoraA' }, error: 'timeout' },
|
||||
{ item: { name: 'LoraB' }, error: '404' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('[data-action="copy-report"]').click();
|
||||
|
||||
// Without the async Clipboard API the fallback must run synchronously.
|
||||
expect(execCommandMock).toHaveBeenCalledWith('copy');
|
||||
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.api.copiedToClipboard', {}, 'success');
|
||||
});
|
||||
|
||||
it('keeps only a single modal instance across repeated calls', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 2,
|
||||
completed: 1,
|
||||
failedItems: [{ item: { name: 'A' }, error: 'e' }],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
showDownloadBatchSummary({ total: 3, completed: 3, failedItems: [], onRetry: vi.fn() });
|
||||
|
||||
expect(document.querySelectorAll('#downloadBatchSummaryModal')).toHaveLength(1);
|
||||
const modal = document.getElementById('downloadBatchSummaryModal');
|
||||
expect(modal.querySelector('.summary-header').classList.contains('success')).toBe(true);
|
||||
});
|
||||
|
||||
it('resolves failure names from entry.name, item fields, URL paths, or Unknown', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 4,
|
||||
completed: 0,
|
||||
failedItems: [
|
||||
{ name: 'entryName', item: { displayName: 'ItemName' }, error: 'e1' },
|
||||
{ item: { selectedVersion: { name: 'v1.0' } }, error: 'e2' },
|
||||
{ item: { url: 'https://civitai.red/models/837884/midjourney-artful-nsfw?modelVersionId=3153960' }, error: 'e3' },
|
||||
{ item: {}, error: 'e4' },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const names = Array.from(document.querySelectorAll('.failure-name')).map(el => el.textContent);
|
||||
expect(names).toEqual(['entryName', 'v1.0', 'midjourney-artful-nsfw', 'Unknown']);
|
||||
});
|
||||
|
||||
it('formats the real JSON failure payload into a concise HTTP error and truncates long ones', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 2,
|
||||
completed: 0,
|
||||
failedItems: [
|
||||
{ item: { name: 'EarlyAccess' }, error: REAL_ERROR },
|
||||
{ item: { name: 'LongError' }, error: 'x'.repeat(300) },
|
||||
],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const errorCells = document.querySelectorAll('.failure-error');
|
||||
expect(errorCells[0].textContent).toBe(FORMATTED_REAL_ERROR);
|
||||
expect(errorCells[1].textContent).toBe('x'.repeat(220) + '…');
|
||||
});
|
||||
|
||||
it('keeps the raw error string in the error cell title for debugging', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{ item: { name: 'EarlyAccess' }, error: REAL_ERROR }],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
const errorCell = document.querySelector('.failure-error');
|
||||
expect(errorCell.getAttribute('title')).toBe(REAL_ERROR);
|
||||
expect(errorCell.getAttribute('title')).not.toBe(FORMATTED_REAL_ERROR);
|
||||
});
|
||||
|
||||
it('opens the original item url in a new tab when a failure link is clicked', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{
|
||||
item: {
|
||||
url: 'https://civitai.red/models/837884/midjourney-artful-nsfw?modelVersionId=3153960',
|
||||
modelId: '837884',
|
||||
selectedVersion: { id: '3153960' },
|
||||
},
|
||||
error: 'rate limited',
|
||||
}],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('.failure-link').click();
|
||||
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledTimes(1);
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledWith('https://civitai.red/models/837884/midjourney-artful-nsfw?modelVersionId=3153960');
|
||||
// The modal stays open so the user can keep inspecting the failures.
|
||||
expect(document.getElementById('downloadBatchSummaryModal')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('opens the item url directly when selectedVersion is absent', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{
|
||||
item: {
|
||||
modelId: '837884',
|
||||
modelVersionId: '3153960',
|
||||
url: 'https://civitai.red/models/837884/midjourney-artful-nsfw',
|
||||
},
|
||||
error: 'rate limited',
|
||||
}],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('.failure-link').click();
|
||||
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledTimes(1);
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledWith('https://civitai.red/models/837884/midjourney-artful-nsfw');
|
||||
expect(document.getElementById('downloadBatchSummaryModal')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('opens the original huggingface url directly when a huggingface failure link is clicked', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{
|
||||
item: {
|
||||
url: 'https://huggingface.co/user/repo',
|
||||
source: 'huggingface',
|
||||
repo: 'user/repo',
|
||||
filename: 'model.safetensors',
|
||||
revision: 'main',
|
||||
},
|
||||
error: 'download failed',
|
||||
}],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('.failure-link').click();
|
||||
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledTimes(1);
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledWith('https://huggingface.co/user/repo');
|
||||
expect(document.getElementById('downloadBatchSummaryModal')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('opens an arbitrary URL via openHuggingFace for fallback items', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{ item: { url: 'https://example.com/model' }, error: 'boom' }],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('.failure-link').click();
|
||||
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledTimes(1);
|
||||
expect(openHuggingFaceMock).toHaveBeenCalledWith('https://example.com/model');
|
||||
});
|
||||
|
||||
it('renders the failure name as plain text when no URL can be resolved', () => {
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{ item: { modelId: null }, error: 'boom' }],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
expect(document.querySelector('a.failure-link')).toBeNull();
|
||||
expect(document.querySelector('.failure-name').textContent).toBe('Unknown');
|
||||
|
||||
// Without a link there is nothing to open: clicking the cell is inert.
|
||||
document.querySelector('.failure-name').click();
|
||||
expect(openHuggingFaceMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('copies formatted errors (not raw JSON) into the report text', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
|
||||
|
||||
showDownloadBatchSummary({
|
||||
total: 1,
|
||||
completed: 0,
|
||||
failedItems: [{
|
||||
item: {
|
||||
name: 'EarlyAccess',
|
||||
url: 'https://civitai.red/models/123/early-access?modelVersionId=456',
|
||||
},
|
||||
error: REAL_ERROR,
|
||||
}],
|
||||
onRetry: vi.fn(),
|
||||
});
|
||||
|
||||
document.querySelector('[data-action="copy-report"]').click();
|
||||
|
||||
expect(writeText).toHaveBeenCalledTimes(1);
|
||||
const text = writeText.mock.calls[0][0];
|
||||
expect(text).toContain(FORMATTED_REAL_ERROR);
|
||||
expect(text).toContain(' URL: https://civitai.red/models/123/early-access?modelVersionId=456');
|
||||
expect(text).not.toContain('download_id');
|
||||
expect(text).not.toContain('Failed to resolve authenticated Civitai redirect');
|
||||
|
||||
await vi.waitFor(() => expect(showToastMock).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
317
tests/frontend/managers/downloadManager.batchSummary.test.js
Normal file
317
tests/frontend/managers/downloadManager.batchSummary.test.js
Normal file
@@ -0,0 +1,317 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
DOWNLOAD_MANAGER_MODULE,
|
||||
MODAL_MANAGER_MODULE,
|
||||
UI_HELPERS_MODULE,
|
||||
STATE_MODULE,
|
||||
LOADING_MANAGER_MODULE,
|
||||
API_FACTORY_MODULE,
|
||||
STORAGE_HELPERS_MODULE,
|
||||
FOLDER_TREE_MANAGER_MODULE,
|
||||
I18N_HELPERS_MODULE,
|
||||
SUMMARY_MODULE,
|
||||
mockApiClient,
|
||||
mockLoadingManager,
|
||||
showToastMock,
|
||||
showDownloadBatchSummaryMock,
|
||||
resetAndReloadMock,
|
||||
} = vi.hoisted(() => {
|
||||
// Shared API client returned by the mocked getModelApiClient factory.
|
||||
const mockApiClient = {
|
||||
apiConfig: {
|
||||
config: {
|
||||
displayName: 'LoRA',
|
||||
singularName: 'lora',
|
||||
},
|
||||
},
|
||||
downloadModel: vi.fn(),
|
||||
downloadHfModel: vi.fn(),
|
||||
cancelDownload: vi.fn(),
|
||||
};
|
||||
|
||||
// Shared loading manager served both via state.loadingManager and the
|
||||
// LoadingManager constructor mock.
|
||||
const mockLoadingManager = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
showDownloadProgress: vi.fn(() => vi.fn()),
|
||||
setStatus: vi.fn(),
|
||||
showCancelButton: vi.fn(),
|
||||
};
|
||||
|
||||
return {
|
||||
DOWNLOAD_MANAGER_MODULE: new URL('../../../static/js/managers/DownloadManager.js', import.meta.url).pathname,
|
||||
MODAL_MANAGER_MODULE: new URL('../../../static/js/managers/ModalManager.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
|
||||
LOADING_MANAGER_MODULE: new URL('../../../static/js/managers/LoadingManager.js', import.meta.url).pathname,
|
||||
API_FACTORY_MODULE: new URL('../../../static/js/api/modelApiFactory.js', import.meta.url).pathname,
|
||||
STORAGE_HELPERS_MODULE: new URL('../../../static/js/utils/storageHelpers.js', import.meta.url).pathname,
|
||||
FOLDER_TREE_MANAGER_MODULE: new URL('../../../static/js/components/FolderTreeManager.js', import.meta.url).pathname,
|
||||
I18N_HELPERS_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
SUMMARY_MODULE: new URL('../../../static/js/components/DownloadBatchSummaryModal.js', import.meta.url).pathname,
|
||||
mockApiClient,
|
||||
mockLoadingManager,
|
||||
showToastMock: vi.fn(),
|
||||
showDownloadBatchSummaryMock: vi.fn(),
|
||||
resetAndReloadMock: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock(MODAL_MANAGER_MODULE, () => ({
|
||||
modalManager: {
|
||||
showModal: vi.fn(),
|
||||
closeModal: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: showToastMock,
|
||||
}));
|
||||
|
||||
vi.mock(STATE_MODULE, () => ({
|
||||
state: {
|
||||
global: {
|
||||
settings: {},
|
||||
},
|
||||
loadingManager: mockLoadingManager,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(LOADING_MANAGER_MODULE, () => ({
|
||||
LoadingManager: vi.fn(() => mockLoadingManager),
|
||||
}));
|
||||
|
||||
vi.mock(API_FACTORY_MODULE, () => ({
|
||||
getModelApiClient: vi.fn(() => mockApiClient),
|
||||
resetAndReload: resetAndReloadMock,
|
||||
}));
|
||||
|
||||
vi.mock(STORAGE_HELPERS_MODULE, () => ({
|
||||
getStorageItem: vi.fn((_key, defaultValue) => defaultValue),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(FOLDER_TREE_MANAGER_MODULE, () => ({
|
||||
FolderTreeManager: vi.fn(() => ({
|
||||
clearSelection: vi.fn(),
|
||||
init: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock(I18N_HELPERS_MODULE, () => ({
|
||||
translate: vi.fn((_, __, fallback) => fallback ?? ''),
|
||||
}));
|
||||
|
||||
vi.mock(SUMMARY_MODULE, () => ({
|
||||
showDownloadBatchSummary: showDownloadBatchSummaryMock,
|
||||
}));
|
||||
|
||||
/**
|
||||
* Fake WebSocket used by executeBatchDownload. Resolves `onopen` on the
|
||||
* microtask queue right after construction (which happens after the real
|
||||
* code has assigned `onopen`), so the open promise resolves deterministically
|
||||
* without real timers.
|
||||
*/
|
||||
class FakeWebSocket {
|
||||
static instances = [];
|
||||
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.onopen = null;
|
||||
this.onmessage = null;
|
||||
this.onerror = null;
|
||||
this.close = vi.fn();
|
||||
FakeWebSocket.instances.push(this);
|
||||
queueMicrotask(() => {
|
||||
if (this.onopen) this.onopen();
|
||||
});
|
||||
}
|
||||
|
||||
static get lastInstance() {
|
||||
return FakeWebSocket.instances[FakeWebSocket.instances.length - 1];
|
||||
}
|
||||
}
|
||||
|
||||
describe('DownloadManager batch download summary flow', () => {
|
||||
let DownloadManager;
|
||||
let manager;
|
||||
|
||||
const options = { modelRoot: '/models/loras', targetFolder: '', useDefaultPaths: true };
|
||||
|
||||
const makeItem = (modelId, versionId, name) => ({
|
||||
modelId,
|
||||
displayName: name,
|
||||
selectedVersion: { id: versionId, name, existsLocally: false },
|
||||
});
|
||||
|
||||
const item0 = makeItem('111', 'v1', 'Model A');
|
||||
const item1 = makeItem('222', 'v2', 'Model B');
|
||||
|
||||
beforeEach(async () => {
|
||||
document.body.innerHTML = '';
|
||||
FakeWebSocket.instances = [];
|
||||
|
||||
// Reset the shared mocks so mockResolvedValueOnce queues and call
|
||||
// history never leak between tests.
|
||||
mockApiClient.downloadModel.mockReset();
|
||||
mockApiClient.downloadHfModel.mockReset();
|
||||
mockApiClient.cancelDownload.mockReset();
|
||||
showToastMock.mockClear();
|
||||
showDownloadBatchSummaryMock.mockClear();
|
||||
resetAndReloadMock.mockClear();
|
||||
mockLoadingManager.hide.mockClear();
|
||||
mockLoadingManager.setStatus.mockClear();
|
||||
mockLoadingManager.showCancelButton.mockClear();
|
||||
mockLoadingManager.showDownloadProgress.mockClear();
|
||||
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
vi.resetModules();
|
||||
({ DownloadManager } = await import(DOWNLOAD_MANAGER_MODULE));
|
||||
manager = new DownloadManager();
|
||||
// The constructor leaves apiClient null; executeBatchDownload reads it
|
||||
// directly, so point it at the shared mocked client.
|
||||
manager.apiClient = mockApiClient;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('shows the success toast when every item downloads successfully', async () => {
|
||||
mockApiClient.downloadModel.mockResolvedValue({ success: true });
|
||||
|
||||
await manager.executeBatchDownload([item0, item1], options);
|
||||
|
||||
expect(mockApiClient.downloadModel).toHaveBeenCalledTimes(2);
|
||||
// Each item is downloaded with its own modelId + versionId.
|
||||
expect(mockApiClient.downloadModel.mock.calls[0][0]).toBe('111');
|
||||
expect(mockApiClient.downloadModel.mock.calls[0][1]).toBe('v1');
|
||||
expect(mockApiClient.downloadModel.mock.calls[1][0]).toBe('222');
|
||||
expect(mockApiClient.downloadModel.mock.calls[1][1]).toBe('v2');
|
||||
|
||||
expect(showDownloadBatchSummaryMock).not.toHaveBeenCalled();
|
||||
expect(showToastMock).toHaveBeenCalledTimes(1);
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.loras.allDownloadSuccessful', { count: 2 }, 'success');
|
||||
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('shows a partial-failure summary when some items fail', async () => {
|
||||
// The failing item has no displayName/filename, so the resolved entry
|
||||
// name falls back to the selected version name.
|
||||
const unnamedItem = { modelId: '333', selectedVersion: { id: 'v3', name: 'V3', existsLocally: false } };
|
||||
mockApiClient.downloadModel
|
||||
.mockResolvedValueOnce({ success: false, error: 'rate limited' })
|
||||
.mockResolvedValueOnce({ success: true });
|
||||
|
||||
await manager.executeBatchDownload([unnamedItem, item1], options);
|
||||
|
||||
expect(showDownloadBatchSummaryMock).toHaveBeenCalledTimes(1);
|
||||
const summary = showDownloadBatchSummaryMock.mock.calls[0][0];
|
||||
expect(summary.total).toBe(2);
|
||||
expect(summary.completed).toBe(1);
|
||||
expect(summary.failedItems).toHaveLength(1);
|
||||
expect(summary.failedItems[0].item).toBe(unnamedItem);
|
||||
expect(summary.failedItems[0].error).toBe('rate limited');
|
||||
// The resolved display name is carried on the failed entry.
|
||||
expect(summary.failedItems[0].name).toBe('V3');
|
||||
expect(summary.onRetry).toEqual(expect.any(Function));
|
||||
|
||||
// No success toast and no downloadPartialSuccess toast for this path.
|
||||
expect(showToastMock).not.toHaveBeenCalledWith('toast.loras.allDownloadSuccessful', expect.anything(), 'success');
|
||||
expect(showToastMock).not.toHaveBeenCalledWith('toast.loras.downloadPartialSuccess', expect.anything(), expect.anything());
|
||||
});
|
||||
|
||||
it('shows an all-failed summary when every item fails', async () => {
|
||||
mockApiClient.downloadModel.mockResolvedValue({ success: false, error: 'x' });
|
||||
|
||||
await manager.executeBatchDownload([item0, item1], options);
|
||||
|
||||
expect(showDownloadBatchSummaryMock).toHaveBeenCalledTimes(1);
|
||||
const summary = showDownloadBatchSummaryMock.mock.calls[0][0];
|
||||
expect(summary.total).toBe(2);
|
||||
expect(summary.completed).toBe(0);
|
||||
expect(summary.failedItems).toHaveLength(2);
|
||||
expect(summary.failedItems[0].item).toBe(item0);
|
||||
expect(summary.failedItems[1].item).toBe(item1);
|
||||
expect(showToastMock).not.toHaveBeenCalledWith('toast.loras.allDownloadSuccessful', expect.anything(), expect.anything());
|
||||
});
|
||||
|
||||
it('records the error message when downloadModel rejects', async () => {
|
||||
// The item carries a filename but no displayName, so the resolved entry
|
||||
// name comes from the filename.
|
||||
const filenameItem = { modelId: '444', filename: 'model.safetensors', selectedVersion: { id: 'v4' } };
|
||||
mockApiClient.downloadModel.mockRejectedValue(new Error('network down'));
|
||||
|
||||
await manager.executeBatchDownload([filenameItem], options);
|
||||
|
||||
expect(showDownloadBatchSummaryMock).toHaveBeenCalledTimes(1);
|
||||
const summary = showDownloadBatchSummaryMock.mock.calls[0][0];
|
||||
expect(summary.total).toBe(1);
|
||||
expect(summary.completed).toBe(0);
|
||||
expect(summary.failedItems).toHaveLength(1);
|
||||
expect(summary.failedItems[0].item).toBe(filenameItem);
|
||||
expect(summary.failedItems[0].error).toBe('network down');
|
||||
expect(summary.failedItems[0].name).toBe('model.safetensors');
|
||||
});
|
||||
|
||||
it('retries the failed subset through onRetry with unwrapped items', async () => {
|
||||
mockApiClient.downloadModel
|
||||
.mockResolvedValueOnce({ success: false, error: 'rate limited' })
|
||||
.mockResolvedValueOnce({ success: true });
|
||||
|
||||
await manager.executeBatchDownload([item0, item1], options);
|
||||
|
||||
expect(showDownloadBatchSummaryMock).toHaveBeenCalledTimes(1);
|
||||
const summary = showDownloadBatchSummaryMock.mock.calls[0][0];
|
||||
expect(summary.failedItems).toHaveLength(1);
|
||||
|
||||
// Retry the exact failed subset returned by the summary. The onRetry
|
||||
// callback unwraps the { item, error } entries back into raw model items
|
||||
// before re-running executeBatchDownload. Make the retried item fail
|
||||
// again so a second summary is produced.
|
||||
mockApiClient.downloadModel.mockResolvedValueOnce({ success: false, error: 'still rate limited' });
|
||||
await summary.onRetry(summary.failedItems);
|
||||
|
||||
// downloadModel is called a third time — only for the failed item (item0),
|
||||
// NOT for the item that already succeeded (item1).
|
||||
expect(mockApiClient.downloadModel).toHaveBeenCalledTimes(3);
|
||||
const retryCall = mockApiClient.downloadModel.mock.calls[2];
|
||||
expect(retryCall[0]).toBe(item0.modelId);
|
||||
expect(retryCall[1]).toBe(item0.selectedVersion.id);
|
||||
|
||||
// A fresh summary is produced for the retry run (call count 1 -> 2).
|
||||
expect(showDownloadBatchSummaryMock).toHaveBeenCalledTimes(2);
|
||||
const retrySummary = showDownloadBatchSummaryMock.mock.calls[1][0];
|
||||
expect(retrySummary.total).toBe(1);
|
||||
expect(retrySummary.completed).toBe(0);
|
||||
expect(retrySummary.failedItems).toHaveLength(1);
|
||||
expect(retrySummary.failedItems[0].item).toBe(item0);
|
||||
expect(retrySummary.failedItems[0].error).toBe('still rate limited');
|
||||
});
|
||||
|
||||
it('stops the batch without showing a summary when cancelled before downloads start', async () => {
|
||||
const downloadPromise = manager.executeBatchDownload([item0, item1], options);
|
||||
|
||||
// showCancelButton captured the cancel callback synchronously. Invoking it
|
||||
// sets `cancelled = true` before the download loop runs (the loop only
|
||||
// starts after the WebSocket open promise resolves on the microtask queue).
|
||||
const cancelCallback = mockLoadingManager.showCancelButton.mock.calls[0][0];
|
||||
const cancelPromise = cancelCallback();
|
||||
|
||||
await Promise.all([downloadPromise, cancelPromise]);
|
||||
|
||||
expect(mockApiClient.downloadModel).not.toHaveBeenCalled();
|
||||
expect(showDownloadBatchSummaryMock).not.toHaveBeenCalled();
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.downloads.downloadStopped',
|
||||
expect.anything(),
|
||||
'info',
|
||||
expect.stringContaining('Download cancelled')
|
||||
);
|
||||
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user