feat(models): show Civitai model/version ids in model modal, always-on hash/id search

- Model modal hash footnote now shows Civitai model id and version id
  (right-aligned, quick-copy buttons); hidden for non-Civitai models
- Hash/id exact search (sha256/autov2/autov3/civitai ids) is now always
  on: the search-options "hash" toggle is removed and the search_hash
  query param is silently ignored for API compatibility
- Footnote render condition relaxed so autov3-only and id-only models
  still show the line
- i18n: 4 new keys translated in all 9 locales; filters.hash key removed
This commit is contained in:
Will Miao
2026-10-03 09:46:46 +08:00
parent 515469054c
commit f8aba393fe
22 changed files with 254 additions and 167 deletions
@@ -1,120 +0,0 @@
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();
});
});
@@ -165,12 +165,76 @@ describe('Model modal hash rendering', () => {
expect(rows[0].querySelector('.hash-kind').textContent).toBe('SHA256');
});
it('hides the hashes item entirely when sha256 is empty', async () => {
it('renders autov3 alone when sha256 is empty', async () => {
await renderModal(makeModel({ sha256: '', autov3: AUTOV3 }));
const rows = document.querySelectorAll('.hash-footnote .hash-entry');
expect(rows).toHaveLength(1);
expect(rows[0].querySelector('.hash-kind').textContent).toBe('AutoV3');
});
it('hides the footnote entirely when there are no hashes and no civitai ids', async () => {
await renderModal(makeModel({ sha256: '', autov3: '', civitai: {} }));
expect(document.querySelector('.hash-footnote')).toBeNull();
});
it('renders civitai model and version ids with copy buttons', async () => {
await renderModal(makeModel({ civitai: { modelId: 12345, id: 67890 } }));
const group = document.querySelector('.hash-footnote .civitai-id-group');
expect(group).not.toBeNull();
const entries = group.querySelectorAll('.civitai-id-entry');
expect(entries).toHaveLength(2);
expect(entries[0].querySelector('.hash-kind').textContent).toBe('Model ID');
expect(entries[0].querySelector('.model-hash-value').textContent).toBe('12345');
expect(entries[0].querySelector('[data-action="copy-hash"]').dataset.hash).toBe('12345');
expect(entries[1].querySelector('.hash-kind').textContent).toBe('Version ID');
expect(entries[1].querySelector('.model-hash-value').textContent).toBe('67890');
expect(entries[1].querySelector('[data-action="copy-hash"]').dataset.hash).toBe('67890');
});
it('hides civitai ids for models without civitai data', async () => {
await renderModal(makeModel({ civitai: {} }));
expect(document.querySelector('.hash-footnote .civitai-id-group')).toBeNull();
});
it.each([0, '0', null, undefined, ''])('treats civitai id %s as missing', async (missingId) => {
await renderModal(makeModel({ civitai: { modelId: missingId, id: missingId } }));
expect(document.querySelector('.hash-footnote .civitai-id-group')).toBeNull();
});
it('falls back to snake_case model_id', async () => {
await renderModal(makeModel({ civitai: { model_id: 777, id: 888 } }));
const group = document.querySelector('.hash-footnote .civitai-id-group');
const entries = group.querySelectorAll('.civitai-id-entry');
expect(entries[0].querySelector('.model-hash-value').textContent).toBe('777');
expect(entries[1].querySelector('.model-hash-value').textContent).toBe('888');
});
it('still renders the footnote when only civitai ids exist', async () => {
await renderModal(makeModel({ sha256: '', autov3: '', civitai: { modelId: 12345, id: 67890 } }));
const footnote = document.querySelector('.hash-footnote');
expect(footnote).not.toBeNull();
expect(footnote.querySelectorAll('.civitai-id-entry')).toHaveLength(2);
});
it('copies the version id with the civitai toast when its copy button is clicked', async () => {
await renderModal(makeModel({ civitai: { modelId: 12345, id: 67890 } }));
const entries = document.querySelectorAll('.civitai-id-entry [data-action="copy-hash"]');
entries[1].click();
expect(copyToClipboard).toHaveBeenCalledWith('67890', 'Civitai ID copied to clipboard');
});
it('copies the full hash when the copy button is clicked', async () => {
await renderModal(makeModel());
+49 -12
View File
@@ -13,20 +13,13 @@ SHA256 = "abcdef1234567890" + "f" * 48 # 64-char hex
AUTOV2 = SHA256[:10]
AUTOV3 = "0123456789ab"
# Hash/id exact matching is always on; these options only disable the
# scope-based branches so tests exercise the hash branch in isolation.
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,
}
@@ -88,9 +81,11 @@ class TestSearchStrategyHash:
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_hash_matching_is_always_on(self, strategy):
# There is no hash option anymore: exact hash/id matching happens
# regardless of the search scope options.
assert len(strategy.apply([make_item()], SHA256, HASH_ONLY_OPTIONS)) == 1
assert len(strategy.apply([make_item()], AUTOV3, HASH_ONLY_OPTIONS)) == 1
def test_fuzzy_mode_still_exact(self, strategy):
# Fuzzy matching must never apply to the hash field
@@ -104,6 +99,48 @@ class TestSearchStrategyHash:
assert strategy.apply([item], SHA256, HASH_ONLY_OPTIONS) == []
class TestSearchStrategyCivitaiIds:
"""Hash search also exact-matches Civitai model/version ids."""
def test_version_id_matches(self, strategy):
item = make_item(civitai={"modelId": 12345, "id": 67890})
assert len(strategy.apply([item], "67890", HASH_ONLY_OPTIONS)) == 1
def test_model_id_matches(self, strategy):
item = make_item(civitai={"modelId": 12345, "id": 67890})
assert len(strategy.apply([item], "12345", HASH_ONLY_OPTIONS)) == 1
def test_model_id_matches_all_versions_of_the_model(self, strategy):
v1 = make_item(file_name="v1.safetensors", civitai={"modelId": 12345, "id": 111})
v2 = make_item(file_name="v2.safetensors", civitai={"modelId": 12345, "id": 222})
other = make_item(file_name="other.safetensors", civitai={"modelId": 999, "id": 333})
result = strategy.apply([v1, v2, other], "12345", HASH_ONLY_OPTIONS)
assert {r["file_name"] for r in result} == {"v1.safetensors", "v2.safetensors"}
def test_snake_case_model_id_matches(self, strategy):
item = make_item(civitai={"model_id": 12345, "id": 67890})
assert len(strategy.apply([item], "12345", HASH_ONLY_OPTIONS)) == 1
def test_string_ids_match(self, strategy):
item = make_item(civitai={"modelId": "12345", "id": "67890"})
assert len(strategy.apply([item], "67890", HASH_ONLY_OPTIONS)) == 1
def test_unknown_id_does_not_match(self, strategy):
item = make_item(civitai={"modelId": 12345, "id": 67890})
assert strategy.apply([item], "555", HASH_ONLY_OPTIONS) == []
@pytest.mark.parametrize("missing", [0, "0", None, ""])
def test_placeholder_ids_do_not_match(self, strategy, missing):
item = make_item(sha256="", autov3=None, civitai={"modelId": missing, "id": missing})
assert strategy.apply([item], "0", HASH_ONLY_OPTIONS) == []
def test_missing_civitai_data_does_not_match(self, strategy):
item = make_item(sha256="", autov3=None, civitai=None)
assert strategy.apply([item], "12345", HASH_ONLY_OPTIONS) == []
item = make_item(sha256="", autov3=None)
assert strategy.apply([item], "12345", HASH_ONLY_OPTIONS) == []
class TestFormatResponseAutov3:
"""format_response should pass the autov3 field through unchanged."""