mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-08-24 06:21:26 -03:00
feat(ui): add hash search option and de-emphasized hash display in model modal
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
BASE_MODEL_API_MODULE,
|
||||
STATE_MODULE,
|
||||
UI_HELPERS_MODULE,
|
||||
I18N_MODULE,
|
||||
STORAGE_MODULE,
|
||||
API_CONFIG_MODULE,
|
||||
API_FACTORY_MODULE,
|
||||
SIDEBAR_MANAGER_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
BASE_MODEL_API_MODULE: new URL('../../../static/js/api/baseModelApi.js', import.meta.url).pathname,
|
||||
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
I18N_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
STORAGE_MODULE: new URL('../../../static/js/utils/storageHelpers.js', import.meta.url).pathname,
|
||||
API_CONFIG_MODULE: new URL('../../../static/js/api/apiConfig.js', import.meta.url).pathname,
|
||||
API_FACTORY_MODULE: new URL('../../../static/js/api/modelApiFactory.js', import.meta.url).pathname,
|
||||
SIDEBAR_MANAGER_MODULE: new URL('../../../static/js/components/SidebarManager.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
vi.mock(STATE_MODULE, () => ({
|
||||
state: {
|
||||
global: { settings: {} },
|
||||
},
|
||||
getCurrentPageState: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(I18N_MODULE, () => ({
|
||||
translate: vi.fn((key) => key),
|
||||
}));
|
||||
|
||||
vi.mock(STORAGE_MODULE, () => ({
|
||||
getStorageItem: vi.fn(),
|
||||
getSessionItem: vi.fn(() => null),
|
||||
removeSessionItem: vi.fn(),
|
||||
saveMapToStorage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(API_CONFIG_MODULE, () => ({
|
||||
getCompleteApiConfig: vi.fn(() => ({
|
||||
endpoints: {},
|
||||
config: { displayName: 'LoRA', singularName: 'LoRA', supportsLetterFilter: false },
|
||||
})),
|
||||
getCurrentModelType: vi.fn(() => 'loras'),
|
||||
isValidModelType: vi.fn(() => true),
|
||||
DOWNLOAD_ENDPOINTS: {},
|
||||
HF_ENDPOINTS: {},
|
||||
WS_ENDPOINTS: {},
|
||||
}));
|
||||
|
||||
vi.mock(API_FACTORY_MODULE, () => ({
|
||||
resetAndReload: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(SIDEBAR_MANAGER_MODULE, () => ({
|
||||
sidebarManager: { refresh: vi.fn() },
|
||||
}));
|
||||
|
||||
async function createClient() {
|
||||
const { BaseModelApiClient } = await import(BASE_MODEL_API_MODULE);
|
||||
class TestClient extends BaseModelApiClient {}
|
||||
return new TestClient('loras');
|
||||
}
|
||||
|
||||
function makePageState(searchOptions) {
|
||||
return {
|
||||
viewMode: 'active',
|
||||
activeFolder: null,
|
||||
showFavoritesOnly: false,
|
||||
showUpdateAvailableOnly: false,
|
||||
filters: { search: 'abc123' },
|
||||
searchOptions: {
|
||||
filename: true,
|
||||
modelname: true,
|
||||
tags: false,
|
||||
creator: false,
|
||||
recursive: true,
|
||||
...searchOptions,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('BaseModelApiClient._buildQueryParams hash search option', () => {
|
||||
it('appends search_hash=true when the hash option is enabled', async () => {
|
||||
const client = await createClient();
|
||||
const params = client._buildQueryParams({}, makePageState({ hash: true }));
|
||||
|
||||
expect(params.get('search_hash')).toBe('true');
|
||||
expect(params.get('search')).toBe('abc123');
|
||||
});
|
||||
|
||||
it('appends search_hash=false when the hash option is disabled', async () => {
|
||||
const client = await createClient();
|
||||
const params = client._buildQueryParams({}, makePageState({ hash: false }));
|
||||
|
||||
expect(params.get('search_hash')).toBe('false');
|
||||
});
|
||||
|
||||
it('omits search_hash when the option is absent (backend defaults to false)', async () => {
|
||||
const client = await createClient();
|
||||
const params = client._buildQueryParams({}, makePageState({}));
|
||||
|
||||
expect(params.get('search_hash')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not send search_hash without an active search term', async () => {
|
||||
const client = await createClient();
|
||||
const pageState = makePageState({ hash: true });
|
||||
pageState.filters.search = '';
|
||||
const params = client._buildQueryParams({}, pageState);
|
||||
|
||||
expect(params.get('search_hash')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, beforeEach, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
MODAL_MODULE,
|
||||
API_FACTORY,
|
||||
UI_HELPERS_MODULE,
|
||||
MODAL_MANAGER_MODULE,
|
||||
SHOWCASE_MODULE,
|
||||
MODEL_TAGS_MODULE,
|
||||
UTILS_MODULE,
|
||||
TRIGGER_WORDS_MODULE,
|
||||
PRESET_TAGS_MODULE,
|
||||
MODEL_VERSIONS_MODULE,
|
||||
RECIPE_TAB_MODULE,
|
||||
I18N_HELPERS_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
MODAL_MODULE: new URL('../../../static/js/components/shared/ModelModal.js', import.meta.url).pathname,
|
||||
API_FACTORY: new URL('../../../static/js/api/modelApiFactory.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
MODAL_MANAGER_MODULE: new URL('../../../static/js/managers/ModalManager.js', import.meta.url).pathname,
|
||||
SHOWCASE_MODULE: new URL('../../../static/js/components/shared/showcase/ShowcaseView.js', import.meta.url).pathname,
|
||||
MODEL_TAGS_MODULE: new URL('../../../static/js/components/shared/ModelTags.js', import.meta.url).pathname,
|
||||
UTILS_MODULE: new URL('../../../static/js/components/shared/utils.js', import.meta.url).pathname,
|
||||
TRIGGER_WORDS_MODULE: new URL('../../../static/js/components/shared/TriggerWords.js', import.meta.url).pathname,
|
||||
PRESET_TAGS_MODULE: new URL('../../../static/js/components/shared/PresetTags.js', import.meta.url).pathname,
|
||||
MODEL_VERSIONS_MODULE: new URL('../../../static/js/components/shared/ModelVersionsTab.js', import.meta.url).pathname,
|
||||
RECIPE_TAB_MODULE: new URL('../../../static/js/components/shared/RecipeTab.js', import.meta.url).pathname,
|
||||
I18N_HELPERS_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: vi.fn(),
|
||||
openCivitai: vi.fn(),
|
||||
copyToClipboard: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(MODAL_MANAGER_MODULE, () => ({
|
||||
modalManager: {
|
||||
showModal: vi.fn((id, html) => {
|
||||
document.body.innerHTML = `<div id="${id}">${html}</div>`;
|
||||
}),
|
||||
closeModal: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(SHOWCASE_MODULE, () => ({
|
||||
scrollToTop: vi.fn(),
|
||||
loadExampleImages: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(MODEL_TAGS_MODULE, () => ({
|
||||
setupTagEditMode: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(UTILS_MODULE, async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
renderCompactTags: vi.fn(() => ''),
|
||||
setupTagTooltip: vi.fn(),
|
||||
formatFileSize: vi.fn(() => '1 MB'),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock(TRIGGER_WORDS_MODULE, () => ({
|
||||
renderTriggerWords: vi.fn(() => ''),
|
||||
setupTriggerWordsEditMode: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(PRESET_TAGS_MODULE, () => ({
|
||||
parsePresets: vi.fn(() => ({})),
|
||||
renderPresetTags: vi.fn(() => ''),
|
||||
}));
|
||||
|
||||
vi.mock(MODEL_VERSIONS_MODULE, () => ({
|
||||
initVersionsTab: vi.fn(() => ({
|
||||
load: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock(RECIPE_TAB_MODULE, () => ({
|
||||
loadRecipesForModel: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(I18N_HELPERS_MODULE, () => ({
|
||||
translate: vi.fn((_, __, fallback) => fallback || ''),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings'
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock(API_FACTORY, () => ({
|
||||
getModelApiClient: vi.fn(),
|
||||
}));
|
||||
|
||||
const SHA256 = 'abcdef1234567890' + 'f'.repeat(48);
|
||||
const AUTOV3 = '0123456789ab';
|
||||
|
||||
function makeModel(overrides = {}) {
|
||||
return {
|
||||
model_name: 'Hash Model',
|
||||
file_path: 'models/hash.safetensors',
|
||||
file_name: 'hash.safetensors',
|
||||
sha256: SHA256,
|
||||
autov3: AUTOV3,
|
||||
civitai: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('Model modal hash rendering', () => {
|
||||
let getModelApiClient;
|
||||
let copyToClipboard;
|
||||
|
||||
beforeEach(async () => {
|
||||
document.body.innerHTML = '';
|
||||
({ getModelApiClient } = await import(API_FACTORY));
|
||||
({ copyToClipboard } = await import(UI_HELPERS_MODULE));
|
||||
getModelApiClient.mockReset();
|
||||
copyToClipboard.mockReset();
|
||||
getModelApiClient.mockReturnValue({
|
||||
fetchModelMetadata: vi.fn().mockResolvedValue(null),
|
||||
saveModelMetadata: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
async function renderModal(model) {
|
||||
const { showModelModal } = await import(MODAL_MODULE);
|
||||
await showModelModal(model, 'loras');
|
||||
}
|
||||
|
||||
it('renders sha256 middle-truncated with the full hash in title and copy button', async () => {
|
||||
await renderModal(makeModel());
|
||||
|
||||
const hashItem = document.querySelector('.hash-footnote');
|
||||
expect(hashItem).not.toBeNull();
|
||||
|
||||
const value = hashItem.querySelector('.model-hash-value');
|
||||
expect(value.textContent).toBe(`${SHA256.slice(0, 10)}\u2026${SHA256.slice(-6)}`);
|
||||
expect(value.getAttribute('title')).toBe(SHA256);
|
||||
|
||||
const copyBtn = hashItem.querySelector('[data-action="copy-hash"]');
|
||||
expect(copyBtn.dataset.hash).toBe(SHA256);
|
||||
});
|
||||
|
||||
it('renders autov3 in full', async () => {
|
||||
await renderModal(makeModel());
|
||||
|
||||
const rows = document.querySelectorAll('.hash-footnote .hash-entry');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[1].querySelector('.model-hash-value').textContent).toBe(AUTOV3);
|
||||
expect(rows[1].querySelector('[data-action="copy-hash"]').dataset.hash).toBe(AUTOV3);
|
||||
});
|
||||
|
||||
it.each([null, undefined, ''])('hides the autov3 row when autov3 is %s', async (autov3) => {
|
||||
await renderModal(makeModel({ autov3 }));
|
||||
|
||||
const rows = document.querySelectorAll('.hash-footnote .hash-entry');
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].querySelector('.hash-kind').textContent).toBe('SHA256');
|
||||
});
|
||||
|
||||
it('hides the hashes item entirely when sha256 is empty', async () => {
|
||||
await renderModal(makeModel({ sha256: '', autov3: AUTOV3 }));
|
||||
|
||||
expect(document.querySelector('.hash-footnote')).toBeNull();
|
||||
});
|
||||
|
||||
it('copies the full hash when the copy button is clicked', async () => {
|
||||
await renderModal(makeModel());
|
||||
|
||||
const copyBtn = document.querySelector('.hash-footnote [data-action="copy-hash"]');
|
||||
copyBtn.click();
|
||||
|
||||
expect(copyToClipboard).toHaveBeenCalledWith(SHA256, expect.any(String));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Tests for SearchStrategy hash-based exact matching and autov3 passthrough."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from py.services.checkpoint_service import CheckpointService
|
||||
from py.services.embedding_service import EmbeddingService
|
||||
from py.services.lora_service import LoraService
|
||||
from py.services.model_query import SearchStrategy
|
||||
|
||||
SHA256 = "abcdef1234567890" + "f" * 48 # 64-char hex
|
||||
AUTOV2 = SHA256[:10]
|
||||
AUTOV3 = "0123456789ab"
|
||||
|
||||
HASH_ONLY_OPTIONS = {
|
||||
"filename": False,
|
||||
"modelname": False,
|
||||
"tags": False,
|
||||
"creator": False,
|
||||
"hash": True,
|
||||
}
|
||||
|
||||
HASH_OFF_OPTIONS = {
|
||||
"filename": False,
|
||||
"modelname": False,
|
||||
"tags": False,
|
||||
"creator": False,
|
||||
"hash": False,
|
||||
}
|
||||
|
||||
|
||||
def make_item(**overrides):
|
||||
item = {
|
||||
"file_name": "model.safetensors",
|
||||
"model_name": "Some Model",
|
||||
"tags": [],
|
||||
"sha256": SHA256,
|
||||
"autov3": AUTOV3,
|
||||
}
|
||||
item.update(overrides)
|
||||
return item
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def strategy():
|
||||
return SearchStrategy()
|
||||
|
||||
|
||||
class TestSearchStrategyHash:
|
||||
"""Hash search matches exactly against sha256, autov2, and autov3."""
|
||||
|
||||
def test_full_sha256_matches(self, strategy):
|
||||
items = [make_item(), make_item(file_name="other.safetensors", sha256="0" * 64)]
|
||||
result = strategy.apply(items, SHA256, HASH_ONLY_OPTIONS)
|
||||
assert [item["file_name"] for item in result] == ["model.safetensors"]
|
||||
|
||||
def test_autov2_prefix_matches(self, strategy):
|
||||
result = strategy.apply([make_item()], AUTOV2, HASH_ONLY_OPTIONS)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_autov3_matches(self, strategy):
|
||||
result = strategy.apply([make_item()], AUTOV3, HASH_ONLY_OPTIONS)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_query_is_case_insensitive(self, strategy):
|
||||
result = strategy.apply([make_item()], SHA256.upper(), HASH_ONLY_OPTIONS)
|
||||
assert len(result) == 1
|
||||
result = strategy.apply([make_item()], AUTOV3.upper(), HASH_ONLY_OPTIONS)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_query_whitespace_is_stripped(self, strategy):
|
||||
result = strategy.apply([make_item()], f" {AUTOV3} ", HASH_ONLY_OPTIONS)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_partial_hash_does_not_match(self, strategy):
|
||||
# Exact semantics: a 5-char fragment is neither autov2 nor autov3
|
||||
result = strategy.apply([make_item()], SHA256[:5], HASH_ONLY_OPTIONS)
|
||||
assert result == []
|
||||
|
||||
def test_autov3_none_is_skipped(self, strategy):
|
||||
item = make_item(autov3=None)
|
||||
assert strategy.apply([item], AUTOV3, HASH_ONLY_OPTIONS) == []
|
||||
# sha256 matching still works
|
||||
assert len(strategy.apply([item], SHA256, HASH_ONLY_OPTIONS)) == 1
|
||||
|
||||
def test_autov3_empty_string_is_skipped(self, strategy):
|
||||
item = make_item(autov3="")
|
||||
assert strategy.apply([item], AUTOV3, HASH_ONLY_OPTIONS) == []
|
||||
|
||||
def test_hash_option_disabled(self, strategy):
|
||||
assert strategy.apply([make_item()], SHA256, HASH_OFF_OPTIONS) == []
|
||||
assert strategy.apply([make_item()], AUTOV3, HASH_OFF_OPTIONS) == []
|
||||
|
||||
def test_fuzzy_mode_still_exact(self, strategy):
|
||||
# Fuzzy matching must never apply to the hash field
|
||||
result = strategy.apply([make_item()], AUTOV3, HASH_ONLY_OPTIONS, fuzzy=True)
|
||||
assert len(result) == 1
|
||||
result = strategy.apply([make_item()], SHA256[:5], HASH_ONLY_OPTIONS, fuzzy=True)
|
||||
assert result == []
|
||||
|
||||
def test_missing_sha256_does_not_match(self, strategy):
|
||||
item = make_item(sha256="", autov3=None)
|
||||
assert strategy.apply([item], SHA256, HASH_ONLY_OPTIONS) == []
|
||||
|
||||
|
||||
class TestFormatResponseAutov3:
|
||||
"""format_response should pass the autov3 field through unchanged."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_scanner(self):
|
||||
scanner = MagicMock()
|
||||
scanner._hash_index = MagicMock()
|
||||
return scanner
|
||||
|
||||
def make_model_data(self, autov3):
|
||||
return {
|
||||
"model_name": "Test Model",
|
||||
"file_name": "test_model",
|
||||
"base_model": "SDXL",
|
||||
"folder": "",
|
||||
"sha256": SHA256,
|
||||
"autov3": autov3,
|
||||
"file_path": "/models/test_model.safetensors",
|
||||
"size": 1000,
|
||||
"modified": 1234567890.0,
|
||||
"tags": [],
|
||||
"from_civitai": True,
|
||||
"civitai": {},
|
||||
}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("autov3", [AUTOV3, "", None])
|
||||
async def test_lora_format_response_autov3(self, mock_scanner, autov3):
|
||||
service = LoraService(mock_scanner)
|
||||
result = await service.format_response(self.make_model_data(autov3))
|
||||
assert result["autov3"] == autov3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("autov3", [AUTOV3, "", None])
|
||||
async def test_checkpoint_format_response_autov3(self, mock_scanner, autov3):
|
||||
service = CheckpointService(mock_scanner)
|
||||
result = await service.format_response(self.make_model_data(autov3))
|
||||
assert result["autov3"] == autov3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("autov3", [AUTOV3, "", None])
|
||||
async def test_embedding_format_response_autov3(self, mock_scanner, autov3):
|
||||
service = EmbeddingService(mock_scanner)
|
||||
result = await service.format_response(self.make_model_data(autov3))
|
||||
assert result["autov3"] == autov3
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_autov3_defaults_to_none(self, mock_scanner):
|
||||
data = self.make_model_data(AUTOV3)
|
||||
del data["autov3"]
|
||||
result = await LoraService(mock_scanner).format_response(data)
|
||||
assert result["autov3"] is None
|
||||
Reference in New Issue
Block a user