feat(download-history): add downloaded status UX

This commit is contained in:
Will Miao
2026-04-13 19:51:04 +08:00
parent ba1800095e
commit a95c518b30
17 changed files with 417 additions and 16 deletions

View File

@@ -349,4 +349,59 @@ describe('ModelVersionsTab media rendering', () => {
);
expect(firstBadges).toContain('Newer Version');
});
it('shows downloaded badge only for previously downloaded versions that are not in library', async () => {
fetchModelUpdateVersions.mockResolvedValue({
success: true,
record: {
shouldIgnore: false,
inLibraryVersionIds: [8],
versions: [
{
versionId: 9,
name: 'History only',
baseModel: 'SDXL',
previewUrl: '/api/lm/previews/v9.png',
sizeBytes: 1024,
isInLibrary: false,
hasBeenDownloaded: true,
shouldIgnore: false,
},
{
versionId: 8,
name: 'Local copy',
baseModel: 'SDXL',
previewUrl: '/api/lm/previews/v8.png',
sizeBytes: 2048,
isInLibrary: true,
hasBeenDownloaded: true,
shouldIgnore: false,
},
],
},
});
const { initVersionsTab } = await import(MODEL_VERSIONS_MODULE);
const controller = initVersionsTab({
modalId: 'model-versions-modal',
modelType: 'loras',
modelId: 654,
currentVersionId: 8,
});
await controller.load();
const rows = document.querySelectorAll('.model-version-row');
const historyBadges = Array.from(rows[0].querySelectorAll('.version-badge')).map(
badge => badge.textContent?.trim()
);
const localBadges = Array.from(rows[1].querySelectorAll('.version-badge')).map(
badge => badge.textContent?.trim()
);
expect(historyBadges).toContain('Downloaded');
expect(historyBadges).not.toContain('In Library');
expect(localBadges).toContain('In Library');
expect(localBadges).not.toContain('Downloaded');
});
});

View File

@@ -0,0 +1,139 @@
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,
} = vi.hoisted(() => ({
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,
}));
vi.mock(MODAL_MANAGER_MODULE, () => ({
modalManager: {
showModal: vi.fn(),
closeModal: vi.fn(),
},
}));
vi.mock(UI_HELPERS_MODULE, () => ({
showToast: vi.fn(),
}));
vi.mock(STATE_MODULE, () => ({
state: {
global: {
settings: {},
},
},
}));
vi.mock(LOADING_MANAGER_MODULE, () => ({
LoadingManager: vi.fn(() => ({
showSimpleLoading: vi.fn(),
hide: vi.fn(),
restoreProgressBar: vi.fn(),
showDownloadProgress: vi.fn(() => vi.fn()),
setStatus: vi.fn(),
})),
}));
vi.mock(API_FACTORY_MODULE, () => ({
getModelApiClient: vi.fn(() => ({
apiConfig: {
config: {
displayName: 'LoRA',
singularName: 'lora',
},
},
})),
resetAndReload: vi.fn(),
}));
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 ?? ''),
}));
describe('DownloadManager version history badges', () => {
let DownloadManager;
beforeEach(async () => {
vi.resetModules();
document.body.innerHTML = `
<div id="urlStep"></div>
<div id="versionStep"></div>
<div id="versionList"></div>
<button id="nextFromVersion"></button>
`;
({ DownloadManager } = await import(DOWNLOAD_MANAGER_MODULE));
});
afterEach(() => {
document.body.innerHTML = '';
});
it('shows downloaded badge only for versions missing locally', () => {
const manager = new DownloadManager();
manager.versions = [
{
id: 101,
name: 'History only',
images: [],
files: [{ sizeKB: 2048 }],
createdAt: '2026-01-01T00:00:00Z',
existsLocally: false,
hasBeenDownloaded: true,
},
{
id: 102,
name: 'Still local',
images: [],
files: [{ sizeKB: 2048 }],
createdAt: '2026-01-01T00:00:00Z',
existsLocally: true,
hasBeenDownloaded: true,
localPath: '/models/still-local.safetensors',
},
];
manager.showVersionStep();
const items = document.querySelectorAll('.version-item');
expect(items).toHaveLength(2);
expect(items[0].querySelector('.downloaded-badge')?.textContent).toContain('Downloaded');
expect(items[0].querySelector('.downloaded-info')?.textContent).toContain(
'Previously downloaded, but it is not currently in your library.'
);
expect(items[0].querySelector('.local-badge')).toBeNull();
expect(items[1].querySelector('.local-badge')).not.toBeNull();
expect(items[1].querySelector('.local-path')?.textContent).toContain('/models/still-local.safetensors');
expect(items[1].querySelector('.downloaded-badge')).toBeNull();
});
});

View File

@@ -7,6 +7,7 @@ import pytest
from py.config import config
from py.routes.handlers.model_handlers import ModelUpdateHandler
from py.services.service_registry import ServiceRegistry
from py.utils.metadata_manager import MetadataManager
from py.services.model_update_service import ModelUpdateRecord, ModelVersionRecord
@@ -91,7 +92,75 @@ async def test_build_version_context_includes_static_urls():
overrides = await handler._build_version_context(record)
expected = config.get_preview_static_url("/tmp/previews/example.png")
assert overrides == {123: {"file_path": None, "file_name": None, "preview_override": expected}}
assert overrides == {
123: {
"file_path": None,
"file_name": None,
"preview_override": expected,
"has_been_downloaded": False,
}
}
@pytest.mark.asyncio
async def test_build_version_context_includes_download_history(monkeypatch):
cache = SimpleNamespace(version_index={})
service = DummyService(cache)
handler = ModelUpdateHandler(
service=service,
update_service=SimpleNamespace(),
metadata_provider_selector=lambda *_: None,
settings_service=SimpleNamespace(get=lambda *_: False),
logger=logging.getLogger(__name__),
)
class DummyHistoryService:
async def get_downloaded_version_ids(self, model_type, model_id):
assert model_type == "lora"
assert model_id == 42
return [123]
async def fake_history_service_factory():
return DummyHistoryService()
monkeypatch.setattr(
ServiceRegistry,
"get_downloaded_version_history_service",
staticmethod(fake_history_service_factory),
)
record = ModelUpdateRecord(
model_type="lora",
model_id=42,
versions=[
ModelVersionRecord(
version_id=123,
name="Downloaded",
base_model=None,
released_at=None,
size_bytes=None,
preview_url=None,
is_in_library=False,
should_ignore=False,
),
ModelVersionRecord(
version_id=124,
name="Fresh",
base_model=None,
released_at=None,
size_bytes=None,
preview_url=None,
is_in_library=False,
should_ignore=False,
),
],
last_checked_at=None,
should_ignore_model=False,
)
overrides = await handler._build_version_context(record)
assert overrides[123]["has_been_downloaded"] is True
assert overrides[124]["has_been_downloaded"] is False
@pytest.mark.asyncio