From d435968df46ddf512ec609c4cb50a2713e8d3b8f Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Thu, 18 Jun 2026 20:55:31 +1200 Subject: [PATCH 01/22] feat(assets): group model library by model_type tags Group the asset-mode Model Library by namespaced model_type:* tags. When an asset carries model_type:* tags, the stripped values are the authoritative categories and all other tags are disregarded; otherwise fall back to the legacy bare-tag top-level grouping. A shared getAssetCategories helper keeps the "By type" nav and category filtering in agreement. Resolve node-provider lookup from the same tags via getAssetNodeCategory: prefer the most specific (deepest parent/child) candidate so a flat model_type:LLM does not shadow a resolvable hierarchical tag, and strip the model_type: prefix before the modelNodeMappings lookup. --- .../composables/useAssetBrowser.test.ts | 12 ++++ .../assets/composables/useAssetBrowser.ts | 6 +- .../assets/utils/assetFilterUtils.test.ts | 13 +++- src/platform/assets/utils/assetFilterUtils.ts | 17 ++--- .../assets/utils/assetMetadataUtils.test.ts | 66 +++++++++++++++++++ .../assets/utils/assetMetadataUtils.ts | 59 +++++++++++++++++ 6 files changed, 156 insertions(+), 17 deletions(-) diff --git a/src/platform/assets/composables/useAssetBrowser.test.ts b/src/platform/assets/composables/useAssetBrowser.test.ts index c767c5c2161..552f17f00bb 100644 --- a/src/platform/assets/composables/useAssetBrowser.test.ts +++ b/src/platform/assets/composables/useAssetBrowser.test.ts @@ -668,6 +668,18 @@ describe('useAssetBrowser', () => { ]) }) + it('groups by model_type:* value and ignores other tags', () => { + const assets = [ + createApiAsset({ tags: ['models', 'model_type:checkpoints', 'sdxl'] }), + createApiAsset({ tags: ['models', 'model_type:LLM'] }) + ] + + const { navItems } = useAssetBrowser(ref(assets)) + + const typeGroup = navItems.value[2] as { items: { id: string }[] } + expect(typeGroup.items.map((i) => i.id)).toEqual(['LLM', 'checkpoints']) + }) + it('handles assets with no category tag', () => { const assets = [ createApiAsset({ tags: ['models'] }), // No second tag diff --git a/src/platform/assets/composables/useAssetBrowser.ts b/src/platform/assets/composables/useAssetBrowser.ts index 03f042a4de9..69471093f65 100644 --- a/src/platform/assets/composables/useAssetBrowser.ts +++ b/src/platform/assets/composables/useAssetBrowser.ts @@ -19,6 +19,7 @@ import { } from '@/platform/assets/utils/assetFilterUtils' import { getAssetBaseModels, + getAssetCategories, getAssetFilename } from '@/platform/assets/utils/assetMetadataUtils' import { MODELS_TAG } from '@/platform/assets/services/assetService' @@ -124,10 +125,7 @@ export function useAssetBrowser( const typeCategories = computed(() => { const categories = assets.value .filter((asset) => asset.tags.includes(MODELS_TAG)) - .flatMap((asset) => - asset.tags.filter((tag) => tag !== MODELS_TAG && tag.length > 0) - ) - .map((tag) => tag.split('/')[0]) + .flatMap(getAssetCategories) return Array.from(new Set(categories)) .sort() diff --git a/src/platform/assets/utils/assetFilterUtils.test.ts b/src/platform/assets/utils/assetFilterUtils.test.ts index 24d35e90e11..8ba5205681d 100644 --- a/src/platform/assets/utils/assetFilterUtils.test.ts +++ b/src/platform/assets/utils/assetFilterUtils.test.ts @@ -34,7 +34,18 @@ describe('filterByCategory', () => { tags: ['models', 'checkpoint/xl'], expected: true }, - { category: 'xl', tags: ['models', 'checkpoint/xl'], expected: false } + { category: 'xl', tags: ['models', 'checkpoint/xl'], expected: false }, + { + category: 'checkpoints', + tags: ['models', 'model_type:checkpoints'], + expected: true + }, + { category: 'LLM', tags: ['models', 'model_type:LLM'], expected: true }, + { + category: 'sdxl', + tags: ['models', 'model_type:checkpoints', 'sdxl'], + expected: false + } ])( 'category=$category with tags=$tags returns $expected', ({ category, tags, expected }) => { diff --git a/src/platform/assets/utils/assetFilterUtils.ts b/src/platform/assets/utils/assetFilterUtils.ts index cdcc1946b17..80ce97578f1 100644 --- a/src/platform/assets/utils/assetFilterUtils.ts +++ b/src/platform/assets/utils/assetFilterUtils.ts @@ -1,21 +1,14 @@ import type { AssetItem } from '@/platform/assets/schemas/assetSchema' import type { OwnershipOption } from '@/platform/assets/types/filterTypes' -import { getAssetBaseModels } from '@/platform/assets/utils/assetMetadataUtils' +import { + getAssetBaseModels, + getAssetCategories +} from '@/platform/assets/utils/assetMetadataUtils' export function filterByCategory(category: string) { return (asset: AssetItem) => { if (category === 'all') return true - - // Check if any tag matches the category (for exact matches) - if (asset.tags.includes(category)) return true - - // Check if any tag's top-level folder matches the category - return asset.tags.some((tag) => { - if (typeof tag === 'string' && tag.includes('/')) { - return tag.split('/')[0] === category - } - return false - }) + return getAssetCategories(asset).includes(category) } } diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index 43516a62afa..ea4b7f05c89 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -6,12 +6,14 @@ import { getAssetBaseModel, getAssetBaseModels, getAssetCardTitle, + getAssetCategories, getAssetDescription, getAssetDisplayFilename, getAssetDisplayName, getAssetFilename, getAssetMetadataDimensions, getAssetModelType, + getAssetNodeCategory, getAssetSourceUrl, getAssetStoredFilename, getAssetTriggerPhrases, @@ -580,3 +582,67 @@ describe('assetMetadataUtils', () => { }) }) }) + +describe('getAssetCategories', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('uses model_type:* values as the group and disregards other tags', () => { + expect( + getAssetCategories(asset(['models', 'model_type:checkpoints', 'sdxl'])) + ).toEqual(['checkpoints']) + }) + + it('preserves the model_type value casing', () => { + expect(getAssetCategories(asset(['models', 'model_type:LLM']))).toEqual([ + 'LLM' + ]) + }) + + it('falls back to non-model tags when no model_type tag is present', () => { + expect(getAssetCategories(asset(['models', 'checkpoints']))).toEqual([ + 'checkpoints' + ]) + }) +}) + +describe('getAssetNodeCategory', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('prefers the most specific (deepest) tag over a flat model_type value', () => { + expect( + getAssetNodeCategory( + asset(['models', 'model_type:LLM', 'LLM/Qwen-VL/Qwen3-0.6B']) + ) + ).toBe('LLM/Qwen-VL/Qwen3-0.6B') + }) + + it('strips the model_type: prefix when it is the only candidate', () => { + expect(getAssetNodeCategory(asset(['models', 'model_type:vae']))).toBe( + 'vae' + ) + }) + + it('lets a model_type value win ties against a bare tag', () => { + expect( + getAssetNodeCategory(asset(['models', 'model_type:checkpoints', 'sdxl'])) + ).toBe('checkpoints') + }) + + it('keeps a hierarchical legacy tag intact', () => { + expect( + getAssetNodeCategory(asset(['models', 'chatterbox/chatterbox_vc'])) + ).toBe('chatterbox/chatterbox_vc') + }) + + it('returns undefined when only reserved tags are present', () => { + expect(getAssetNodeCategory(asset(['models', 'missing']))).toBeUndefined() + }) +}) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index dfcb115607e..017339685ca 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -1,4 +1,8 @@ import type { AssetItem } from '@/platform/assets/schemas/assetSchema' +import { + MISSING_TAG, + MODELS_TAG +} from '@/platform/assets/services/assetService' import { isCloud } from '@/platform/distribution/types' import { isCivitaiUrl } from '@/utils/formatUtil' @@ -150,6 +154,61 @@ export function getAssetModelType(asset: AssetItem): string | null { return typeTag ?? null } +const MODEL_TYPE_TAG_PREFIX = 'model_type:' + +function getModelTypeTagValues(asset: AssetItem): string[] { + return asset.tags + .filter((tag) => tag.startsWith(MODEL_TYPE_TAG_PREFIX)) + .map((tag) => tag.slice(MODEL_TYPE_TAG_PREFIX.length)) + .filter((tag) => tag.length > 0) +} + +/** + * Resolves the category keys a model asset is grouped under. + * + * When the asset carries `model_type:*` tags (the namespaced tag scheme), the + * `*` values are authoritative and every other tag is disregarded. Otherwise + * we fall back to treating each non-`models` tag's top-level segment as a + * category, preserving the pre-namespace behavior. + */ +export function getAssetCategories(asset: AssetItem): string[] { + const modelTypes = getModelTypeTagValues(asset) + if (modelTypes.length > 0) return modelTypes + + return asset.tags + .filter((tag) => tag !== MODELS_TAG && tag.length > 0) + .map((tag) => tag.split('/')[0]) +} + +function pathDepth(tag: string): number { + return tag.split('/').length +} + +/** + * Resolves the model-type key used to look up a node provider for an asset. + * + * Unlike {@link getAssetCategories}, this keeps the full (possibly + * hierarchical) value so `modelToNodeStore`'s `parent/child` fallback still + * works. Candidates are the stripped `model_type:*` values plus any other + * non-reserved tags, and the most specific (deepest `parent/child`) candidate + * wins so a flat `model_type:LLM` never shadows a resolvable + * `LLM/Qwen-VL/...` tag. `model_type:*` values win ties. + */ +export function getAssetNodeCategory(asset: AssetItem): string | undefined { + const otherTags = asset.tags.filter( + (tag) => + tag !== MODELS_TAG && + tag !== MISSING_TAG && + !tag.startsWith(MODEL_TYPE_TAG_PREFIX) + ) + const candidates = [...getModelTypeTagValues(asset), ...otherTags] + if (candidates.length === 0) return undefined + + return candidates.reduce((best, candidate) => + pathDepth(candidate) > pathDepth(best) ? candidate : best + ) +} + /** * Extracts user description from asset user_metadata * @param asset - The asset to extract user description from From 01a51fc8385b33eeabb7e411f83660771350889c Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Fri, 19 Jun 2026 11:07:06 +1200 Subject: [PATCH 02/22] refactor(assets): gate model_type grouping on supports_model_type_tags Drive the model_type: grouping/resolution off the backend-reported supports_model_type_tags capability (getServerFeature) instead of sniffing tags per asset. Default false preserves the legacy bare-tag grouping, so a backend that does not declare the capability is unchanged. When the flag is true, assets group by their model_type: values and an uncovered asset (no model_type: tag) still routes by its bare tags. The thread-through is a modelTypeMode flag on getAssetCategories / getAssetNodeCategory / filterByCategory (keeping them pure); call sites read the capability via useFeatureFlags. --- src/composables/useFeatureFlags.ts | 9 +++- .../composables/useAssetBrowser.test.ts | 30 ++++++++++- .../assets/composables/useAssetBrowser.ts | 10 +++- .../assets/utils/assetFilterUtils.test.ts | 40 +++++++++++--- src/platform/assets/utils/assetFilterUtils.ts | 4 +- .../assets/utils/assetMetadataUtils.test.ts | 54 +++++++++++++------ .../assets/utils/assetMetadataUtils.ts | 50 +++++++++++------ 7 files changed, 153 insertions(+), 44 deletions(-) diff --git a/src/composables/useFeatureFlags.ts b/src/composables/useFeatureFlags.ts index de12ec49613..feb94ec6990 100644 --- a/src/composables/useFeatureFlags.ts +++ b/src/composables/useFeatureFlags.ts @@ -37,7 +37,8 @@ export enum ServerFeatureFlag { CONSOLIDATED_BILLING_ENABLED = 'consolidated_billing_enabled', BILLING_CONTROL_ENABLED = 'billing_control_enabled', FREE_TIER_JOB_ALLOWANCE_ENABLED = 'free_tier_job_allowance_enabled', - SIGNUP_TURNSTILE = 'signup_turnstile' + SIGNUP_TURNSTILE = 'signup_turnstile', + SUPPORTS_MODEL_TYPE_TAGS = 'supports_model_type_tags' } /** @@ -236,6 +237,12 @@ export function useFeatureFlags() { remoteConfig.value.signup_turnstile, 'off' ) + }, + get supportsModelTypeTags() { + return api.getServerFeature( + ServerFeatureFlag.SUPPORTS_MODEL_TYPE_TAGS, + false + ) } }) diff --git a/src/platform/assets/composables/useAssetBrowser.test.ts b/src/platform/assets/composables/useAssetBrowser.test.ts index 552f17f00bb..ea100565ae2 100644 --- a/src/platform/assets/composables/useAssetBrowser.test.ts +++ b/src/platform/assets/composables/useAssetBrowser.test.ts @@ -25,10 +25,22 @@ vi.mock('@/i18n', () => ({ d: (date: Date) => date.toLocaleDateString() })) +const mockSupportsModelTypeTags = vi.hoisted(() => ({ value: false })) +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get supportsModelTypeTags() { + return mockSupportsModelTypeTags.value + } + } + }) +})) + describe('useAssetBrowser', () => { beforeEach(() => { setActivePinia(createPinia()) vi.restoreAllMocks() + mockSupportsModelTypeTags.value = false }) // Test fixtures - minimal data focused on functionality being tested @@ -668,7 +680,8 @@ describe('useAssetBrowser', () => { ]) }) - it('groups by model_type:* value and ignores other tags', () => { + it('groups by model_type:* value and ignores other tags when the flag is on', () => { + mockSupportsModelTypeTags.value = true const assets = [ createApiAsset({ tags: ['models', 'model_type:checkpoints', 'sdxl'] }), createApiAsset({ tags: ['models', 'model_type:LLM'] }) @@ -680,6 +693,21 @@ describe('useAssetBrowser', () => { expect(typeGroup.items.map((i) => i.id)).toEqual(['LLM', 'checkpoints']) }) + it('ignores model_type: and groups by bare tags when the flag is off', () => { + const assets = [ + createApiAsset({ tags: ['models', 'model_type:checkpoints'] }), + createApiAsset({ tags: ['models', 'model_type:LLM'] }) + ] + + const { navItems } = useAssetBrowser(ref(assets)) + + const typeGroup = navItems.value[2] as { items: { id: string }[] } + expect(typeGroup.items.map((i) => i.id)).toEqual([ + 'model_type:LLM', + 'model_type:checkpoints' + ]) + }) + it('handles assets with no category tag', () => { const assets = [ createApiAsset({ tags: ['models'] }), // No second tag diff --git a/src/platform/assets/composables/useAssetBrowser.ts b/src/platform/assets/composables/useAssetBrowser.ts index 69471093f65..eba491ae7b6 100644 --- a/src/platform/assets/composables/useAssetBrowser.ts +++ b/src/platform/assets/composables/useAssetBrowser.ts @@ -24,6 +24,7 @@ import { } from '@/platform/assets/utils/assetMetadataUtils' import { MODELS_TAG } from '@/platform/assets/services/assetService' import { sortAssets } from '@/platform/assets/utils/assetSortUtils' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useAssetDownloadStore } from '@/stores/assetDownloadStore' import type { NavGroupData, NavItemData } from '@/types/navTypes' @@ -94,6 +95,7 @@ export function useAssetBrowser( const assets = computed(() => assetsSource.value ?? []) const assetDownloadStore = useAssetDownloadStore() const { sessionDownloadCount } = storeToRefs(assetDownloadStore) + const { flags } = useFeatureFlags() // State const searchQuery = ref('') @@ -125,7 +127,9 @@ export function useAssetBrowser( const typeCategories = computed(() => { const categories = assets.value .filter((asset) => asset.tags.includes(MODELS_TAG)) - .flatMap(getAssetCategories) + .flatMap((asset) => + getAssetCategories(asset, flags.supportsModelTypeTags) + ) return Array.from(new Set(categories)) .sort() @@ -189,7 +193,9 @@ export function useAssetBrowser( // Category-filtered assets for filter options (before search/format/base model filters) const categoryFilteredAssets = computed(() => { - return assets.value.filter(filterByCategory(selectedCategory.value)) + return assets.value.filter( + filterByCategory(selectedCategory.value, flags.supportsModelTypeTags) + ) }) const { availableFileFormats, availableBaseModels } = useAssetFilterOptions( diff --git a/src/platform/assets/utils/assetFilterUtils.test.ts b/src/platform/assets/utils/assetFilterUtils.test.ts index 8ba5205681d..06de879dc8e 100644 --- a/src/platform/assets/utils/assetFilterUtils.test.ts +++ b/src/platform/assets/utils/assetFilterUtils.test.ts @@ -26,30 +26,54 @@ function createAsset( describe('filterByCategory', () => { it.for([ - { category: 'all', tags: ['checkpoint'], expected: true }, - { category: 'checkpoint', tags: ['checkpoint'], expected: true }, - { category: 'lora', tags: ['checkpoint'], expected: false }, + { category: 'all', tags: ['checkpoint'], mode: false, expected: true }, + { + category: 'checkpoint', + tags: ['checkpoint'], + mode: false, + expected: true + }, + { category: 'lora', tags: ['checkpoint'], mode: false, expected: false }, { category: 'checkpoint', tags: ['models', 'checkpoint/xl'], + mode: false, expected: true }, - { category: 'xl', tags: ['models', 'checkpoint/xl'], expected: false }, + { + category: 'xl', + tags: ['models', 'checkpoint/xl'], + mode: false, + expected: false + }, { category: 'checkpoints', tags: ['models', 'model_type:checkpoints'], + mode: true, + expected: true + }, + { + category: 'LLM', + tags: ['models', 'model_type:LLM'], + mode: true, expected: true }, - { category: 'LLM', tags: ['models', 'model_type:LLM'], expected: true }, { category: 'sdxl', tags: ['models', 'model_type:checkpoints', 'sdxl'], + mode: true, + expected: false + }, + { + category: 'checkpoints', + tags: ['models', 'model_type:checkpoints'], + mode: false, expected: false } ])( - 'category=$category with tags=$tags returns $expected', - ({ category, tags, expected }) => { - const filter = filterByCategory(category) + 'category=$category tags=$tags mode=$mode returns $expected', + ({ category, tags, mode, expected }) => { + const filter = filterByCategory(category, mode) const asset = createAsset('model.safetensors', { tags }) expect(filter(asset)).toBe(expected) } diff --git a/src/platform/assets/utils/assetFilterUtils.ts b/src/platform/assets/utils/assetFilterUtils.ts index 80ce97578f1..a6f567c97a8 100644 --- a/src/platform/assets/utils/assetFilterUtils.ts +++ b/src/platform/assets/utils/assetFilterUtils.ts @@ -5,10 +5,10 @@ import { getAssetCategories } from '@/platform/assets/utils/assetMetadataUtils' -export function filterByCategory(category: string) { +export function filterByCategory(category: string, modelTypeMode = false) { return (asset: AssetItem) => { if (category === 'all') return true - return getAssetCategories(asset).includes(category) + return getAssetCategories(asset, modelTypeMode).includes(category) } } diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index ea4b7f05c89..d0c9e4efcff 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -590,23 +590,32 @@ describe('getAssetCategories', () => { tags }) - it('uses model_type:* values as the group and disregards other tags', () => { + it('uses model_type:* values as the group and disregards other tags in model_type mode', () => { expect( - getAssetCategories(asset(['models', 'model_type:checkpoints', 'sdxl'])) + getAssetCategories( + asset(['models', 'model_type:checkpoints', 'sdxl']), + true + ) ).toEqual(['checkpoints']) }) it('preserves the model_type value casing', () => { - expect(getAssetCategories(asset(['models', 'model_type:LLM']))).toEqual([ - 'LLM' - ]) + expect( + getAssetCategories(asset(['models', 'model_type:LLM']), true) + ).toEqual(['LLM']) }) - it('falls back to non-model tags when no model_type tag is present', () => { - expect(getAssetCategories(asset(['models', 'checkpoints']))).toEqual([ + it('routes an uncovered asset by its bare tags in model_type mode', () => { + expect(getAssetCategories(asset(['models', 'checkpoints']), true)).toEqual([ 'checkpoints' ]) }) + + it('ignores model_type: and uses bare-tag grouping when mode is off (default)', () => { + expect( + getAssetCategories(asset(['models', 'model_type:checkpoints', 'sdxl'])) + ).toEqual(['model_type:checkpoints', 'sdxl']) + }) }) describe('getAssetNodeCategory', () => { @@ -619,30 +628,45 @@ describe('getAssetNodeCategory', () => { it('prefers the most specific (deepest) tag over a flat model_type value', () => { expect( getAssetNodeCategory( - asset(['models', 'model_type:LLM', 'LLM/Qwen-VL/Qwen3-0.6B']) + asset(['models', 'model_type:LLM', 'LLM/Qwen-VL/Qwen3-0.6B']), + true ) ).toBe('LLM/Qwen-VL/Qwen3-0.6B') }) it('strips the model_type: prefix when it is the only candidate', () => { - expect(getAssetNodeCategory(asset(['models', 'model_type:vae']))).toBe( - 'vae' - ) + expect( + getAssetNodeCategory(asset(['models', 'model_type:vae']), true) + ).toBe('vae') }) it('lets a model_type value win ties against a bare tag', () => { expect( - getAssetNodeCategory(asset(['models', 'model_type:checkpoints', 'sdxl'])) + getAssetNodeCategory( + asset(['models', 'model_type:checkpoints', 'sdxl']), + true + ) ).toBe('checkpoints') }) - it('keeps a hierarchical legacy tag intact', () => { + it('keeps a hierarchical tag intact', () => { expect( - getAssetNodeCategory(asset(['models', 'chatterbox/chatterbox_vc'])) + getAssetNodeCategory(asset(['models', 'chatterbox/chatterbox_vc']), true) ).toBe('chatterbox/chatterbox_vc') }) it('returns undefined when only reserved tags are present', () => { - expect(getAssetNodeCategory(asset(['models', 'missing']))).toBeUndefined() + expect( + getAssetNodeCategory(asset(['models', 'missing']), true) + ).toBeUndefined() + }) + + it('uses the first non-reserved tag verbatim when mode is off (default)', () => { + expect(getAssetNodeCategory(asset(['models', 'model_type:vae']))).toBe( + 'model_type:vae' + ) + expect(getAssetNodeCategory(asset(['models', 'checkpoints']))).toBe( + 'checkpoints' + ) }) }) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 017339685ca..53af8faff47 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -163,21 +163,31 @@ function getModelTypeTagValues(asset: AssetItem): string[] { .filter((tag) => tag.length > 0) } +function getBareTagCategories(asset: AssetItem): string[] { + return asset.tags + .filter((tag) => tag !== MODELS_TAG && tag.length > 0) + .map((tag) => tag.split('/')[0]) +} + /** * Resolves the category keys a model asset is grouped under. * - * When the asset carries `model_type:*` tags (the namespaced tag scheme), the - * `*` values are authoritative and every other tag is disregarded. Otherwise - * we fall back to treating each non-`models` tag's top-level segment as a - * category, preserving the pre-namespace behavior. + * `modelTypeMode` reflects whether the backend declares the `model_type:` tag + * scheme (the `supports_model_type_tags` capability). When true, an asset's + * `model_type:*` values are authoritative; an asset with no `model_type:` tag + * still routes by its bare tags. When false (the default) categories come from + * the legacy bare-tag top-level grouping and `model_type:` is ignored. */ -export function getAssetCategories(asset: AssetItem): string[] { - const modelTypes = getModelTypeTagValues(asset) - if (modelTypes.length > 0) return modelTypes +export function getAssetCategories( + asset: AssetItem, + modelTypeMode = false +): string[] { + if (modelTypeMode) { + const modelTypes = getModelTypeTagValues(asset) + if (modelTypes.length > 0) return modelTypes + } - return asset.tags - .filter((tag) => tag !== MODELS_TAG && tag.length > 0) - .map((tag) => tag.split('/')[0]) + return getBareTagCategories(asset) } function pathDepth(tag: string): number { @@ -189,12 +199,22 @@ function pathDepth(tag: string): number { * * Unlike {@link getAssetCategories}, this keeps the full (possibly * hierarchical) value so `modelToNodeStore`'s `parent/child` fallback still - * works. Candidates are the stripped `model_type:*` values plus any other - * non-reserved tags, and the most specific (deepest `parent/child`) candidate - * wins so a flat `model_type:LLM` never shadows a resolvable - * `LLM/Qwen-VL/...` tag. `model_type:*` values win ties. + * works. + * + * In `modelTypeMode` (backend declares `supports_model_type_tags`), candidates + * are the stripped `model_type:*` values plus any other non-reserved tags, and + * the most specific (deepest `parent/child`) candidate wins so a flat + * `model_type:LLM` never shadows a resolvable `LLM/Qwen-VL/...` tag. Otherwise + * we use the legacy first-non-reserved tag verbatim. */ -export function getAssetNodeCategory(asset: AssetItem): string | undefined { +export function getAssetNodeCategory( + asset: AssetItem, + modelTypeMode = false +): string | undefined { + if (!modelTypeMode) { + return asset.tags.find((tag) => tag !== MODELS_TAG && tag !== MISSING_TAG) + } + const otherTags = asset.tags.filter( (tag) => tag !== MODELS_TAG && From 86faaee3e104e9d16bd15925e6020d1df205fe23 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Fri, 19 Jun 2026 21:54:48 +1200 Subject: [PATCH 03/22] refactor(assets): run model-asset store on non-cloud builds Unwrap the if (isCloud) gate in assetsStore getModelState so the asset-mode Model Library works on non-cloud distributions (it previously returned an empty no-op store off-cloud, leaving the library blank even with the asset API enabled). Scoped to the model-asset store only; the rest of the isCloud forks are out of scope here. --- src/stores/assetsStore.test.ts | 29 ++ src/stores/assetsStore.ts | 851 ++++++++++++++++----------------- 2 files changed, 445 insertions(+), 435 deletions(-) diff --git a/src/stores/assetsStore.test.ts b/src/stores/assetsStore.test.ts index 7427e1279f4..f4ed1cd86f2 100644 --- a/src/stores/assetsStore.test.ts +++ b/src/stores/assetsStore.test.ts @@ -1875,6 +1875,35 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { }) }) +describe('assetsStore - Model Assets Cache (non-cloud)', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + mockIsCloud.value = false + vi.clearAllMocks() + }) + + it('caches model assets fetched by tag on non-cloud builds', async () => { + const store = useAssetsStore() + vi.mocked(assetService.getAssetsByTag).mockResolvedValue([ + { + id: 'm1', + name: 'sd_xl_base_1.0.safetensors', + tags: ['checkpoints', 'models'] + }, + { id: 'm2', name: 'lora.safetensors', tags: ['loras', 'models'] } + ]) + + await store.updateModelsForTag('models') + + expect(assetService.getAssetsByTag).toHaveBeenCalledWith( + 'models', + true, + expect.anything() + ) + expect(store.getAssets('tag:models')).toHaveLength(2) + }) +}) + describe('assetsStore - Deletion State and Input Mapping', () => { beforeEach(() => { setActivePinia(createTestingPinia({ stubActions: false })) diff --git a/src/stores/assetsStore.ts b/src/stores/assetsStore.ts index 5a15da82ebf..6587a374cea 100644 --- a/src/stores/assetsStore.ts +++ b/src/stores/assetsStore.ts @@ -410,504 +410,485 @@ export const useAssetsStore = defineStore('assets', () => { * Multiple node types sharing the same category share the same cache entry. * Public API accepts nodeType for backwards compatibility but translates * to category internally using modelToNodeStore.getCategoryForNodeType(). - * Cloud-only feature - empty Maps in desktop builds */ const getModelState = () => { - if (isCloud) { - const modelStateByCategory = ref(new Map()) - - const assetsArrayCache = new Map< - string, - { source: Map; array: AssetItem[] } - >() - - const pendingRequestByCategory = new Map() - const pendingPromiseByCategory = new Map>() - const abortByCategory = new Map() - - function createState( - existingAssets?: Map - ): ModelPaginationState { - const assets = new Map(existingAssets) - return reactive({ - assets, - offset: 0, - nextCursor: undefined, - hasMore: true, - isLoading: true - }) - } + const modelStateByCategory = ref(new Map()) + + const assetsArrayCache = new Map< + string, + { source: Map; array: AssetItem[] } + >() + + const pendingRequestByCategory = new Map() + const pendingPromiseByCategory = new Map>() + const abortByCategory = new Map() + + function createState( + existingAssets?: Map + ): ModelPaginationState { + const assets = new Map(existingAssets) + return reactive({ + assets, + offset: 0, + nextCursor: undefined, + hasMore: true, + isLoading: true + }) + } - function isStale(category: string, state: ModelPaginationState): boolean { - const committed = modelStateByCategory.value.get(category) - const pending = pendingRequestByCategory.get(category) - return committed !== state && pending !== state - } + function isStale(category: string, state: ModelPaginationState): boolean { + const committed = modelStateByCategory.value.get(category) + const pending = pendingRequestByCategory.get(category) + return committed !== state && pending !== state + } - const EMPTY_ASSETS: AssetItem[] = [] + const EMPTY_ASSETS: AssetItem[] = [] - /** - * Resolve a key to a category. Handles both nodeType and tag:xxx formats. - * @param key Either a nodeType (e.g., 'CheckpointLoaderSimple') or tag key (e.g., 'tag:models') - * @returns The category or undefined if not resolvable - */ - function resolveCategory(key: string): string | undefined { - if (key.startsWith('tag:')) { - return key - } - return modelToNodeStore.getCategoryForNodeType(key) + /** + * Resolve a key to a category. Handles both nodeType and tag:xxx formats. + * @param key Either a nodeType (e.g., 'CheckpointLoaderSimple') or tag key (e.g., 'tag:models') + * @returns The category or undefined if not resolvable + */ + function resolveCategory(key: string): string | undefined { + if (key.startsWith('tag:')) { + return key } + return modelToNodeStore.getCategoryForNodeType(key) + } - /** - * Get assets by nodeType or tag key. - * Translates nodeType to category internally for cache lookup. - * @param key Either a nodeType (e.g., 'CheckpointLoaderSimple') or tag key (e.g., 'tag:models') - */ - function getAssets(key: string): AssetItem[] { - const category = resolveCategory(key) - if (!category) return EMPTY_ASSETS - - const state = modelStateByCategory.value.get(category) - const assetsMap = state?.assets - if (!assetsMap) return EMPTY_ASSETS - - const cached = assetsArrayCache.get(category) - if (cached && cached.source === assetsMap) { - return cached.array - } + /** + * Get assets by nodeType or tag key. + * Translates nodeType to category internally for cache lookup. + * @param key Either a nodeType (e.g., 'CheckpointLoaderSimple') or tag key (e.g., 'tag:models') + */ + function getAssets(key: string): AssetItem[] { + const category = resolveCategory(key) + if (!category) return EMPTY_ASSETS - const array = Array.from(assetsMap.values()) - assetsArrayCache.set(category, { source: assetsMap, array }) - return array - } + const state = modelStateByCategory.value.get(category) + const assetsMap = state?.assets + if (!assetsMap) return EMPTY_ASSETS - function isLoading(key: string): boolean { - const category = resolveCategory(key) - if (!category) return false - return modelStateByCategory.value.get(category)?.isLoading ?? false + const cached = assetsArrayCache.get(category) + if (cached && cached.source === assetsMap) { + return cached.array } - function getError(key: string): Error | undefined { - const category = resolveCategory(key) - if (!category) return undefined - return modelStateByCategory.value.get(category)?.error - } + const array = Array.from(assetsMap.values()) + assetsArrayCache.set(category, { source: assetsMap, array }) + return array + } - function hasMore(key: string): boolean { - const category = resolveCategory(key) - if (!category) return false - return modelStateByCategory.value.get(category)?.hasMore ?? false - } + function isLoading(key: string): boolean { + const category = resolveCategory(key) + if (!category) return false + return modelStateByCategory.value.get(category)?.isLoading ?? false + } - function hasAssetKey(key: string): boolean { - const category = resolveCategory(key) - if (!category) return false - return modelStateByCategory.value.has(category) - } + function getError(key: string): Error | undefined { + const category = resolveCategory(key) + if (!category) return undefined + return modelStateByCategory.value.get(category)?.error + } - /** - * Check if a category exists in the cache. - * Checks both direct category keys and tag-prefixed keys. - * @param category The category to check (e.g., 'checkpoints', 'loras') - */ - function hasCategory(category: string): boolean { - return ( - modelStateByCategory.value.has(category) || - modelStateByCategory.value.has(`tag:${category}`) - ) + function hasMore(key: string): boolean { + const category = resolveCategory(key) + if (!category) return false + return modelStateByCategory.value.get(category)?.hasMore ?? false + } + + function hasAssetKey(key: string): boolean { + const category = resolveCategory(key) + if (!category) return false + return modelStateByCategory.value.has(category) + } + + /** + * Check if a category exists in the cache. + * Checks both direct category keys and tag-prefixed keys. + * @param category The category to check (e.g., 'checkpoints', 'loras') + */ + function hasCategory(category: string): boolean { + return ( + modelStateByCategory.value.has(category) || + modelStateByCategory.value.has(`tag:${category}`) + ) + } + + /** + * Internal helper to fetch and cache assets for a category. + * Loads first batch immediately, then progressively loads remaining batches. + * Keeps existing data visible until new data is successfully fetched. + * + * Concurrent calls for the same category are short-circuited: if a request + * is already in progress (tracked via pendingRequestByCategory), subsequent + * calls return immediately to avoid redundant work. + */ + async function updateModelsForCategory( + category: string, + fetcher: (options: AssetPaginationOptions) => Promise + ): Promise { + if (pendingPromiseByCategory.has(category)) { + return pendingPromiseByCategory.get(category)! } - /** - * Internal helper to fetch and cache assets for a category. - * Loads first batch immediately, then progressively loads remaining batches. - * Keeps existing data visible until new data is successfully fetched. - * - * Concurrent calls for the same category are short-circuited: if a request - * is already in progress (tracked via pendingRequestByCategory), subsequent - * calls return immediately to avoid redundant work. - */ - async function updateModelsForCategory( - category: string, - fetcher: (options: AssetPaginationOptions) => Promise - ): Promise { - if (pendingPromiseByCategory.has(category)) { - return pendingPromiseByCategory.get(category)! - } + const existingState = modelStateByCategory.value.get(category) + const state = createState(existingState?.assets) - const existingState = modelStateByCategory.value.get(category) - const state = createState(existingState?.assets) + abortByCategory.get(category)?.abort() + const controller = new AbortController() + abortByCategory.set(category, controller) - abortByCategory.get(category)?.abort() - const controller = new AbortController() - abortByCategory.set(category, controller) + const seenIds = new Set() - const seenIds = new Set() + const hasExistingData = modelStateByCategory.value.has(category) + if (hasExistingData) { + pendingRequestByCategory.set(category, state) + } else { + // Also track in pending map for initial loads to prevent concurrent calls + pendingRequestByCategory.set(category, state) + modelStateByCategory.value.set(category, state) + } - const hasExistingData = modelStateByCategory.value.has(category) - if (hasExistingData) { - pendingRequestByCategory.set(category, state) - } else { - // Also track in pending map for initial loads to prevent concurrent calls - pendingRequestByCategory.set(category, state) - modelStateByCategory.value.set(category, state) - } + async function loadBatches(): Promise { + let isFirstBatch = true + // Only prune unseen cached ids when the walk reaches a genuine end + // of list; bailing out on an anomaly (empty page, cursor cycle, + // batch cap) must not delete assets we simply never re-fetched. + let walkCompleted = false + // Cursors already requested this walk. A repeat means the server is + // cycling (immediate A->A or alternating A->B->A...), so we stop. + const seenCursors = new Set() + let batchCount = 0 + while (state.hasMore) { + if (batchCount++ >= MAX_PAGINATION_BATCHES) { + state.hasMore = false + break + } + try { + // Keyset cursor walk when the server provides one (stable under + // concurrent inserts/deletes); offset walk otherwise. The first + // batch sends offset 0, which the service omits from the request. + const after = state.nextCursor + const response = await fetcher( + after !== undefined + ? { + limit: MODEL_BATCH_SIZE, + after, + signal: controller.signal + } + : { + limit: MODEL_BATCH_SIZE, + offset: state.offset, + signal: controller.signal + } + ) - async function loadBatches(): Promise { - let isFirstBatch = true - // Only prune unseen cached ids when the walk reaches a genuine end - // of list; bailing out on an anomaly (empty page, cursor cycle, - // batch cap) must not delete assets we simply never re-fetched. - let walkCompleted = false - // Cursors already requested this walk. A repeat means the server is - // cycling (immediate A->A or alternating A->B->A...), so we stop. - const seenCursors = new Set() - let batchCount = 0 - while (state.hasMore) { - if (batchCount++ >= MAX_PAGINATION_BATCHES) { - state.hasMore = false - break - } - try { - // Keyset cursor walk when the server provides one (stable under - // concurrent inserts/deletes); offset walk otherwise. The first - // batch sends offset 0, which the service omits from the request. - const after = state.nextCursor - const response = await fetcher( - after !== undefined - ? { - limit: MODEL_BATCH_SIZE, - after, - signal: controller.signal - } - : { - limit: MODEL_BATCH_SIZE, - offset: state.offset, - signal: controller.signal - } - ) - - if (isStale(category, state)) return - - const newAssets = response.assets - - if (isFirstBatch) { - assetsArrayCache.delete(category) - if (hasExistingData) { - pendingRequestByCategory.delete(category) - modelStateByCategory.value.set(category, state) - } - } + if (isStale(category, state)) return - // Merge new assets into existing map and track seen IDs - for (const asset of newAssets) { - seenIds.add(asset.id) - state.assets.set(asset.id, asset) + const newAssets = response.assets + + if (isFirstBatch) { + assetsArrayCache.delete(category) + if (hasExistingData) { + pendingRequestByCategory.delete(category) + modelStateByCategory.value.set(category, state) } - state.assets = new Map(state.assets) + } - state.offset += newAssets.length + // Merge new assets into existing map and track seen IDs + for (const asset of newAssets) { + seenIds.add(asset.id) + state.assets.set(asset.id, asset) + } + state.assets = new Map(state.assets) - if (!response.has_more) { - // Server signalled a genuine end of list — safe to prune ids - // that no longer exist server-side. - state.hasMore = false - walkCompleted = true - } else if (newAssets.length === 0) { - // Anomaly: server claims more but returned an empty page. Stop, - // but do not prune — unseen cached assets may still live on a - // page we never received. + state.offset += newAssets.length + + if (!response.has_more) { + // Server signalled a genuine end of list — safe to prune ids + // that no longer exist server-side. + state.hasMore = false + walkCompleted = true + } else if (newAssets.length === 0) { + // Anomaly: server claims more but returned an empty page. Stop, + // but do not prune — unseen cached assets may still live on a + // page we never received. + state.hasMore = false + } else if (response.next_cursor !== undefined) { + if (seenCursors.has(response.next_cursor)) { + // Repeated cursor: the server is cycling. Stop without + // pruning rather than loop forever. state.hasMore = false - } else if (response.next_cursor !== undefined) { - if (seenCursors.has(response.next_cursor)) { - // Repeated cursor: the server is cycling. Stop without - // pruning rather than loop forever. - state.hasMore = false - } else { - seenCursors.add(response.next_cursor) - state.nextCursor = response.next_cursor - } } else { - // Cursor-less backend: legacy offset walk. A short page is the - // reliable natural end of the list, so it is safe to prune. - state.nextCursor = undefined - if (newAssets.length < MODEL_BATCH_SIZE) { - state.hasMore = false - walkCompleted = true - } + seenCursors.add(response.next_cursor) + state.nextCursor = response.next_cursor } - - if (isFirstBatch) { - state.isLoading = false - isFirstBatch = false - } - - if (state.hasMore) { - await delay(50, { signal: controller.signal }) - } - } catch (err) { - if (controller.signal.aborted) { - if (isFirstBatch) state.isLoading = false - return + } else { + // Cursor-less backend: legacy offset walk. A short page is the + // reliable natural end of the list, so it is safe to prune. + state.nextCursor = undefined + if (newAssets.length < MODEL_BATCH_SIZE) { + state.hasMore = false + walkCompleted = true } - if (isStale(category, state)) return - console.error(`Error loading batch for ${category}:`, err) + } - state.error = err instanceof Error ? err : new Error(String(err)) - state.hasMore = false + if (isFirstBatch) { state.isLoading = false - pendingRequestByCategory.delete(category) + isFirstBatch = false + } + if (state.hasMore) { + await delay(50, { signal: controller.signal }) + } + } catch (err) { + if (controller.signal.aborted) { + if (isFirstBatch) state.isLoading = false return } - } + if (isStale(category, state)) return + console.error(`Error loading batch for ${category}:`, err) - // Prune ids that vanished server-side, but only after a complete - // walk — an early bail-out hasn't seen the whole list, so unseen - // cached assets must be kept rather than deleted. - if (walkCompleted) { - const staleIds = [...state.assets.keys()].filter( - (id) => !seenIds.has(id) - ) - for (const id of staleIds) { - state.assets.delete(id) - } + state.error = err instanceof Error ? err : new Error(String(err)) + state.hasMore = false + state.isLoading = false + pendingRequestByCategory.delete(category) + + return } - assetsArrayCache.delete(category) - pendingRequestByCategory.delete(category) } - const promise = loadBatches() - pendingPromiseByCategory.set(category, promise) - try { - await promise - } finally { - // Only clear the guards if this walk still owns them — an - // invalidateCategory() + fresh walk can register a newer promise and - // controller for the same category before this teardown runs. - if (pendingPromiseByCategory.get(category) === promise) { - pendingPromiseByCategory.delete(category) - } - if (abortByCategory.get(category) === controller) { - abortByCategory.delete(category) + // Prune ids that vanished server-side, but only after a complete + // walk — an early bail-out hasn't seen the whole list, so unseen + // cached assets must be kept rather than deleted. + if (walkCompleted) { + const staleIds = [...state.assets.keys()].filter( + (id) => !seenIds.has(id) + ) + for (const id of staleIds) { + state.assets.delete(id) } } + assetsArrayCache.delete(category) + pendingRequestByCategory.delete(category) } - /** - * Fetch and cache model assets for a specific node type. - * Translates nodeType to category internally - multiple node types - * sharing the same category will share the same cache entry. - * @param nodeType The node type to fetch assets for (e.g., 'CheckpointLoaderSimple') - */ - async function updateModelsForNodeType(nodeType: string): Promise { - const category = modelToNodeStore.getCategoryForNodeType(nodeType) - if (!category) return - - // Use category as cache key but fetch using nodeType for API compatibility - await updateModelsForCategory(category, (opts) => - assetService.getAssetsPageForNodeType(nodeType, opts) - ) + const promise = loadBatches() + pendingPromiseByCategory.set(category, promise) + try { + await promise + } finally { + // Only clear the guards if this walk still owns them — an + // invalidateCategory() + fresh walk can register a newer promise and + // controller for the same category before this teardown runs. + if (pendingPromiseByCategory.get(category) === promise) { + pendingPromiseByCategory.delete(category) + } + if (abortByCategory.get(category) === controller) { + abortByCategory.delete(category) + } } + } - /** - * Fetch and cache model assets for a specific tag - * @param tag The tag to fetch assets for (e.g., 'models') - */ - async function updateModelsForTag(tag: string): Promise { - const category = `tag:${tag}` - await updateModelsForCategory(category, (opts) => - assetService.getAssetsPageByTag(tag, true, opts) - ) - } + /** + * Fetch and cache model assets for a specific node type. + * Translates nodeType to category internally - multiple node types + * sharing the same category will share the same cache entry. + * @param nodeType The node type to fetch assets for (e.g., 'CheckpointLoaderSimple') + */ + async function updateModelsForNodeType(nodeType: string): Promise { + const category = modelToNodeStore.getCategoryForNodeType(nodeType) + if (!category) return - /** - * Invalidate the cache for a specific category. - * Forces a refetch on next access. - * @param category The category to invalidate (e.g., 'checkpoints', 'loras') - */ - function invalidateCategory(category: string): void { - abortByCategory.get(category)?.abort() - abortByCategory.delete(category) - modelStateByCategory.value.delete(category) - assetsArrayCache.delete(category) - pendingRequestByCategory.delete(category) - pendingPromiseByCategory.delete(category) - } + // Use category as cache key but fetch using nodeType for API compatibility + await updateModelsForCategory(category, (opts) => + assetService.getAssetsPageForNodeType(nodeType, opts) + ) + } - /** - * Optimistically update an asset in the cache - * @param assetId The asset ID to update - * @param updates Partial asset data to merge - * @param cacheKey Optional cache key to target (nodeType or 'tag:xxx') - */ - function updateAssetInCache( - assetId: string, - updates: Partial, - cacheKey?: string - ) { - const category = cacheKey ? resolveCategory(cacheKey) : undefined - if (cacheKey && !category) return - - const categoriesToCheck = category - ? [category] - : Array.from(modelStateByCategory.value.keys()) - - for (const cat of categoriesToCheck) { - const state = modelStateByCategory.value.get(cat) - if (!state?.assets) continue - - const existingAsset = state.assets.get(assetId) - if (existingAsset) { - const updatedAsset = { ...existingAsset, ...updates } - state.assets.set(assetId, updatedAsset) - assetsArrayCache.delete(cat) - if (cacheKey) return - } + /** + * Fetch and cache model assets for a specific tag + * @param tag The tag to fetch assets for (e.g., 'models') + */ + async function updateModelsForTag(tag: string): Promise { + const category = `tag:${tag}` + await updateModelsForCategory(category, (opts) => + assetService.getAssetsPageByTag(tag, true, opts) + ) + } + + /** + * Invalidate the cache for a specific category. + * Forces a refetch on next access. + * @param category The category to invalidate (e.g., 'checkpoints', 'loras') + */ + function invalidateCategory(category: string): void { + abortByCategory.get(category)?.abort() + abortByCategory.delete(category) + modelStateByCategory.value.delete(category) + assetsArrayCache.delete(category) + pendingRequestByCategory.delete(category) + pendingPromiseByCategory.delete(category) + } + + /** + * Optimistically update an asset in the cache + * @param assetId The asset ID to update + * @param updates Partial asset data to merge + * @param cacheKey Optional cache key to target (nodeType or 'tag:xxx') + */ + function updateAssetInCache( + assetId: string, + updates: Partial, + cacheKey?: string + ) { + const category = cacheKey ? resolveCategory(cacheKey) : undefined + if (cacheKey && !category) return + + const categoriesToCheck = category + ? [category] + : Array.from(modelStateByCategory.value.keys()) + + for (const cat of categoriesToCheck) { + const state = modelStateByCategory.value.get(cat) + if (!state?.assets) continue + + const existingAsset = state.assets.get(assetId) + if (existingAsset) { + const updatedAsset = { ...existingAsset, ...updates } + state.assets.set(assetId, updatedAsset) + assetsArrayCache.delete(cat) + if (cacheKey) return } } + } - /** - * Update asset metadata with optimistic cache update - * @param asset The asset to update - * @param userMetadata The user_metadata to save - * @param cacheKey Optional cache key to target for optimistic update - */ - async function updateAssetMetadata( - asset: AssetItem, - userMetadata: Record, - cacheKey?: string - ) { - const originalMetadata = asset.user_metadata - updateAssetInCache(asset.id, { user_metadata: userMetadata }, cacheKey) - - try { - const updatedAsset = await assetService.updateAsset(asset.id, { - user_metadata: userMetadata - }) - updateAssetInCache(asset.id, updatedAsset, cacheKey) - } catch (error) { - console.error('Failed to update asset metadata:', error) - updateAssetInCache( + /** + * Update asset metadata with optimistic cache update + * @param asset The asset to update + * @param userMetadata The user_metadata to save + * @param cacheKey Optional cache key to target for optimistic update + */ + async function updateAssetMetadata( + asset: AssetItem, + userMetadata: Record, + cacheKey?: string + ) { + const originalMetadata = asset.user_metadata + updateAssetInCache(asset.id, { user_metadata: userMetadata }, cacheKey) + + try { + const updatedAsset = await assetService.updateAsset(asset.id, { + user_metadata: userMetadata + }) + updateAssetInCache(asset.id, updatedAsset, cacheKey) + } catch (error) { + console.error('Failed to update asset metadata:', error) + updateAssetInCache( + asset.id, + { user_metadata: originalMetadata }, + cacheKey + ) + } + } + + /** + * Update asset tags using add/remove endpoints + * @param asset The asset to update (used to read current tags) + * @param newTags The desired tags array + * @param cacheKey Optional cache key to target for optimistic update + */ + async function updateAssetTags( + asset: AssetItem, + newTags: string[], + cacheKey?: string + ) { + const originalTags = asset.tags + const tagsToAdd = difference(newTags, originalTags) + const tagsToRemove = difference(originalTags, newTags) + + if (tagsToAdd.length === 0 && tagsToRemove.length === 0) return + + updateAssetInCache(asset.id, { tags: newTags }, cacheKey) + + let removedTagsOnServer: string[] = [] + try { + let removeResult: TagsOperationResult | undefined + if (tagsToRemove.length > 0) { + removeResult = await assetService.removeAssetTags( asset.id, - { user_metadata: originalMetadata }, - cacheKey + tagsToRemove ) + removedTagsOnServer = removeResult.removed ?? tagsToRemove } - } - /** - * Update asset tags using add/remove endpoints - * @param asset The asset to update (used to read current tags) - * @param newTags The desired tags array - * @param cacheKey Optional cache key to target for optimistic update - */ - async function updateAssetTags( - asset: AssetItem, - newTags: string[], - cacheKey?: string - ) { - const originalTags = asset.tags - const tagsToAdd = difference(newTags, originalTags) - const tagsToRemove = difference(originalTags, newTags) - - if (tagsToAdd.length === 0 && tagsToRemove.length === 0) return - - updateAssetInCache(asset.id, { tags: newTags }, cacheKey) - - let removedTagsOnServer: string[] = [] - try { - let removeResult: TagsOperationResult | undefined - if (tagsToRemove.length > 0) { - removeResult = await assetService.removeAssetTags( - asset.id, - tagsToRemove - ) - removedTagsOnServer = removeResult.removed ?? tagsToRemove - } - - const addResult = - tagsToAdd.length > 0 - ? await assetService.addAssetTags(asset.id, tagsToAdd) - : undefined + const addResult = + tagsToAdd.length > 0 + ? await assetService.addAssetTags(asset.id, tagsToAdd) + : undefined - const finalTags = (addResult ?? removeResult)?.total_tags - if (finalTags) { - updateAssetInCache(asset.id, { tags: finalTags }, cacheKey) - } - } catch (error) { - console.error('Failed to update asset tags:', error) - updateAssetInCache(asset.id, { tags: originalTags }, cacheKey) - - if (removedTagsOnServer.length > 0) { - try { - await assetService.addAssetTags(asset.id, removedTagsOnServer) - } catch (compensationError) { - console.error( - 'Failed to restore tags after partial failure; invalidating cache to force refetch:', - compensationError - ) - const categoriesToInvalidate = new Set() - const resolved = cacheKey ? resolveCategory(cacheKey) : undefined - if (resolved) { - categoriesToInvalidate.add(resolved) - } - for (const [ - category, - state - ] of modelStateByCategory.value.entries()) { - if (state.assets?.has(asset.id)) { - categoriesToInvalidate.add(category) - } - } - for (const category of categoriesToInvalidate) { - invalidateCategory(category) + const finalTags = (addResult ?? removeResult)?.total_tags + if (finalTags) { + updateAssetInCache(asset.id, { tags: finalTags }, cacheKey) + } + } catch (error) { + console.error('Failed to update asset tags:', error) + updateAssetInCache(asset.id, { tags: originalTags }, cacheKey) + + if (removedTagsOnServer.length > 0) { + try { + await assetService.addAssetTags(asset.id, removedTagsOnServer) + } catch (compensationError) { + console.error( + 'Failed to restore tags after partial failure; invalidating cache to force refetch:', + compensationError + ) + const categoriesToInvalidate = new Set() + const resolved = cacheKey ? resolveCategory(cacheKey) : undefined + if (resolved) { + categoriesToInvalidate.add(resolved) + } + for (const [ + category, + state + ] of modelStateByCategory.value.entries()) { + if (state.assets?.has(asset.id)) { + categoriesToInvalidate.add(category) } } + for (const category of categoriesToInvalidate) { + invalidateCategory(category) + } } } } + } - /** - * Invalidate model caches for a given category (e.g., 'checkpoints', 'loras') - * Clears the category cache and tag-based caches so next access triggers refetch - * @param category The model category to invalidate (e.g., 'checkpoints') - */ - function invalidateModelsForCategory(category: string): void { - invalidateCategory(category) - invalidateCategory(`tag:${category}`) - invalidateCategory('tag:models') - } - - return { - getAssets, - isLoading, - getError, - hasMore, - hasAssetKey, - hasCategory, - updateModelsForNodeType, - updateModelsForTag, - invalidateCategory, - updateAssetMetadata, - updateAssetTags, - invalidateModelsForCategory - } + /** + * Invalidate model caches for a given category (e.g., 'checkpoints', 'loras') + * Clears the category cache and tag-based caches so next access triggers refetch + * @param category The model category to invalidate (e.g., 'checkpoints') + */ + function invalidateModelsForCategory(category: string): void { + invalidateCategory(category) + invalidateCategory(`tag:${category}`) + invalidateCategory('tag:models') } - const emptyAssets: AssetItem[] = [] return { - getAssets: () => emptyAssets, - isLoading: () => false, - getError: () => undefined, - hasMore: () => false, - hasAssetKey: () => false, - hasCategory: () => false, - updateModelsForNodeType: async () => {}, - invalidateCategory: () => {}, - updateModelsForTag: async () => {}, - updateAssetMetadata: async () => {}, - updateAssetTags: async () => {}, - invalidateModelsForCategory: () => {} + getAssets, + isLoading, + getError, + hasMore, + hasAssetKey, + hasCategory, + updateModelsForNodeType, + updateModelsForTag, + invalidateCategory, + updateAssetMetadata, + updateAssetTags, + invalidateModelsForCategory } } From 1897ec5c3b004f2fbe0cbd05c668e898a3656e1d Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 21 Jun 2026 13:50:01 +1200 Subject: [PATCH 04/22] fix(assets): strip model_type: prefix from asset card type badge The card type badge derived from the first raw non-models tag, so in model_type mode it rendered the literal `model_type:checkpoints`. Route it through a model_type-aware getAssetTypeBadge and key the display cache on the flag so a late-arriving feature flag re-derives the badge. Also adds docstrings to the tag helpers to satisfy coverage. --- .../composables/useAssetBrowser.test.ts | 19 +++++++++ .../assets/composables/useAssetBrowser.ts | 40 +++++++++++-------- .../assets/utils/assetMetadataUtils.test.ts | 32 +++++++++++++++ .../assets/utils/assetMetadataUtils.ts | 27 +++++++++++++ 4 files changed, 102 insertions(+), 16 deletions(-) diff --git a/src/platform/assets/composables/useAssetBrowser.test.ts b/src/platform/assets/composables/useAssetBrowser.test.ts index ea100565ae2..d1cbecc1cfc 100644 --- a/src/platform/assets/composables/useAssetBrowser.test.ts +++ b/src/platform/assets/composables/useAssetBrowser.test.ts @@ -150,6 +150,25 @@ describe('useAssetBrowser', () => { }) }) + it('strips the model_type: prefix from the badge when the flag is on', () => { + mockSupportsModelTypeTags.value = true + const apiAsset = createApiAsset({ + tags: ['models', 'model_type:checkpoints', 'sdxl'] + }) + + const { filteredAssets } = useAssetBrowser(ref([apiAsset])) + const result = filteredAssets.value[0] + + expect(result.badges).toContainEqual({ + label: 'checkpoints', + type: 'type' + }) + expect(result.badges).not.toContainEqual({ + label: 'model_type:checkpoints', + type: 'type' + }) + }) + it('handles tags with multiple slashes in badges', () => { const apiAsset = createApiAsset({ tags: ['models', 'checkpoint/subfolder/model-name'] diff --git a/src/platform/assets/composables/useAssetBrowser.ts b/src/platform/assets/composables/useAssetBrowser.ts index eba491ae7b6..3eb331a4b13 100644 --- a/src/platform/assets/composables/useAssetBrowser.ts +++ b/src/platform/assets/composables/useAssetBrowser.ts @@ -20,7 +20,8 @@ import { import { getAssetBaseModels, getAssetCategories, - getAssetFilename + getAssetFilename, + getAssetTypeBadge } from '@/platform/assets/utils/assetMetadataUtils' import { MODELS_TAG } from '@/platform/assets/services/assetService' import { sortAssets } from '@/platform/assets/utils/assetSortUtils' @@ -45,18 +46,20 @@ export interface AssetDisplayItem extends AssetItem { } } -const displayItemCache = new WeakMap() +const displayItemCache = new WeakMap< + AssetItem, + { modelTypeMode: boolean; item: AssetDisplayItem } +>() -function buildDisplayItem(asset: AssetItem): AssetDisplayItem { +function buildDisplayItem( + asset: AssetItem, + modelTypeMode: boolean +): AssetDisplayItem { const badges: AssetBadge[] = [] - const typeTag = asset.tags.find((tag) => tag !== 'models') - if (typeTag) { - const badgeLabel = typeTag.includes('/') - ? typeTag.substring(typeTag.indexOf('/') + 1) - : typeTag - - badges.push({ label: badgeLabel, type: 'type' }) + const typeBadge = getAssetTypeBadge(asset, modelTypeMode) + if (typeBadge) { + badges.push({ label: typeBadge, type: 'type' }) } for (const model of getAssetBaseModels(asset)) { @@ -77,12 +80,15 @@ function buildDisplayItem(asset: AssetItem): AssetDisplayItem { } } -function transformAssetForDisplay(asset: AssetItem): AssetDisplayItem { +function transformAssetForDisplay( + asset: AssetItem, + modelTypeMode: boolean +): AssetDisplayItem { const cached = displayItemCache.get(asset) - if (cached) return cached - const built = buildDisplayItem(asset) - displayItemCache.set(asset, built) - return built + if (cached && cached.modelTypeMode === modelTypeMode) return cached.item + const item = buildDisplayItem(asset, modelTypeMode) + displayItemCache.set(asset, { modelTypeMode, item }) + return item } /** @@ -252,7 +258,9 @@ export function useAssetBrowser( const sortedAssets = sortAssets(filtered, filters.value.sortBy) // Transform to display format - return sortedAssets.map(transformAssetForDisplay) + return sortedAssets.map((asset) => + transformAssetForDisplay(asset, flags.supportsModelTypeTags) + ) }) function updateFilters(newFilters: AssetFilterState) { diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index d0c9e4efcff..f414a1dbeab 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -17,6 +17,7 @@ import { getAssetSourceUrl, getAssetStoredFilename, getAssetTriggerPhrases, + getAssetTypeBadge, getAssetUserDescription, getSourceName, resolveDisplayImageDimensions @@ -670,3 +671,34 @@ describe('getAssetNodeCategory', () => { ) }) }) + +describe('getAssetTypeBadge', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('strips the model_type: prefix in model_type mode (no raw leak)', () => { + expect( + getAssetTypeBadge( + asset(['models', 'model_type:checkpoints', 'sdxl']), + true + ) + ).toBe('checkpoints') + }) + + it('leaks the literal model_type: tag when mode is off (default)', () => { + expect(getAssetTypeBadge(asset(['models', 'model_type:checkpoints']))).toBe( + 'model_type:checkpoints' + ) + }) + + it('shows the segment after the first slash for a bare hierarchical tag', () => { + expect(getAssetTypeBadge(asset(['models', 'checkpoint/xl']))).toBe('xl') + }) + + it('returns undefined when only the models tag is present', () => { + expect(getAssetTypeBadge(asset(['models']), true)).toBeUndefined() + }) +}) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 53af8faff47..662988733f1 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -156,6 +156,7 @@ export function getAssetModelType(asset: AssetItem): string | null { const MODEL_TYPE_TAG_PREFIX = 'model_type:' +/** Strips the `model_type:` prefix off each namespaced tag, dropping non-`model_type:` tags. */ function getModelTypeTagValues(asset: AssetItem): string[] { return asset.tags .filter((tag) => tag.startsWith(MODEL_TYPE_TAG_PREFIX)) @@ -163,6 +164,7 @@ function getModelTypeTagValues(asset: AssetItem): string[] { .filter((tag) => tag.length > 0) } +/** Legacy grouping: each non-`models` tag's top-level path segment. */ function getBareTagCategories(asset: AssetItem): string[] { return asset.tags .filter((tag) => tag !== MODELS_TAG && tag.length > 0) @@ -190,10 +192,35 @@ export function getAssetCategories( return getBareTagCategories(asset) } +/** Number of `parent/child` segments in a tag, used to pick the most specific. */ function pathDepth(tag: string): number { return tag.split('/').length } +/** + * Resolves the short label shown on an asset card's type badge. + * + * In `modelTypeMode` a `model_type:*` tag's stripped value is preferred so the + * badge never leaks the raw `model_type:` namespace; otherwise (and as a + * fallback for an uncovered asset) it uses the first non-`models` tag, showing + * the segment after the first `/` for hierarchical tags. + */ +export function getAssetTypeBadge( + asset: AssetItem, + modelTypeMode = false +): string | undefined { + if (modelTypeMode) { + const [modelType] = getModelTypeTagValues(asset) + if (modelType) return modelType + } + + const typeTag = asset.tags.find((tag) => tag !== MODELS_TAG) + if (!typeTag) return undefined + return typeTag.includes('/') + ? typeTag.slice(typeTag.indexOf('/') + 1) + : typeTag +} + /** * Resolves the model-type key used to look up a node provider for an asset. * From 31c043ead3c4519c908f44a14ffffa49d75a53a2 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Mon, 22 Jun 2026 22:06:22 +1200 Subject: [PATCH 05/22] fix(assets): strip model_type: prefix from the asset browser title Also realigns the card type badge to the same rule: keep the existing "first non-models tag" selection and only strip the model_type: namespace prefix, rather than reordering to prefer the model_type: value. So an asset like [models, foo, model_type:bar] still shows foo, while [models, model_type:checkpoints] shows checkpoints. Title (primaryCategoryTag) strips the same prefix when the flag is on. --- .../components/AssetBrowserModal.test.ts | 30 +++++++++++++++++++ .../assets/components/AssetBrowserModal.vue | 9 +++++- .../assets/utils/assetMetadataUtils.test.ts | 20 ++++++++++++- .../assets/utils/assetMetadataUtils.ts | 23 ++++++++------ 4 files changed, 71 insertions(+), 11 deletions(-) diff --git a/src/platform/assets/components/AssetBrowserModal.test.ts b/src/platform/assets/components/AssetBrowserModal.test.ts index baf5f1ed78d..d5e6974b8c4 100644 --- a/src/platform/assets/components/AssetBrowserModal.test.ts +++ b/src/platform/assets/components/AssetBrowserModal.test.ts @@ -9,6 +9,20 @@ import { useAssetsStore } from '@/stores/assetsStore' const mockAssetsByKey = vi.hoisted(() => new Map()) const mockLoadingByKey = vi.hoisted(() => new Map()) +const mockSupportsModelTypeTags = vi.hoisted(() => ({ value: false })) + +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get supportsModelTypeTags() { + return mockSupportsModelTypeTags.value + }, + get modelUploadButtonEnabled() { + return false + } + } + }) +})) vi.mock('@/i18n', () => ({ t: (key: string, params?: Record) => @@ -226,6 +240,7 @@ describe('AssetBrowserModal', () => { vi.resetAllMocks() mockAssetsByKey.clear() mockLoadingByKey.clear() + mockSupportsModelTypeTags.value = false }) describe('Integration with useAssetBrowser', () => { @@ -432,5 +447,20 @@ describe('AssetBrowserModal', () => { 'assetBrowser.allCategory:{"category":"Checkpoints"}' ) }) + + it('strips the model_type: prefix from the title when the flag is on', async () => { + mockSupportsModelTypeTags.value = true + const assets = [ + createTestAsset('asset1', 'Model A', 'model_type:checkpoints') + ] + mockAssetsByKey.set('CheckpointLoaderSimple', assets) + + renderModal({ nodeType: 'CheckpointLoaderSimple' }) + await flushPromises() + + expect(screen.getByTestId('modal-title').textContent).toBe( + 'assetBrowser.allCategory:{"category":"Checkpoints"}' + ) + }) }) }) diff --git a/src/platform/assets/components/AssetBrowserModal.vue b/src/platform/assets/components/AssetBrowserModal.vue index 85a79605f7c..20e99da3b11 100644 --- a/src/platform/assets/components/AssetBrowserModal.vue +++ b/src/platform/assets/components/AssetBrowserModal.vue @@ -100,6 +100,7 @@ import SearchInput from '@/components/ui/search-input/SearchInput.vue' import Button from '@/components/ui/button/Button.vue' import BaseModalLayout from '@/components/widget/layout/BaseModalLayout.vue' import LeftSidePanel from '@/components/widget/panel/LeftSidePanel.vue' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import { usePrimeVueOverlayChildStyle } from '@/composables/usePopoverSizing' import AssetFilterBar from '@/platform/assets/components/AssetFilterBar.vue' import AssetGrid from '@/platform/assets/components/AssetGrid.vue' @@ -109,12 +110,14 @@ import { useAssetBrowser } from '@/platform/assets/composables/useAssetBrowser' import { useModelTypes } from '@/platform/assets/composables/useModelTypes' import { useModelUpload } from '@/platform/assets/composables/useModelUpload' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' +import { stripModelTypePrefix } from '@/platform/assets/utils/assetMetadataUtils' import { formatCategoryLabel } from '@/platform/assets/utils/categoryLabel' import { useAssetsStore } from '@/stores/assetsStore' import { useModelToNodeStore } from '@/stores/modelToNodeStore' import { OnCloseKey } from '@/types/widgetTypes' const { t } = useI18n() +const { flags } = useFeatureFlags() const assetStore = useAssetsStore() const modelToNodeStore = useModelToNodeStore() const breakpoints = useBreakpoints(breakpointsTailwind) @@ -196,7 +199,11 @@ const primaryCategoryTag = computed(() => { .map((asset) => asset.tags?.find((tag) => tag !== 'models')) .find((tag): tag is string => typeof tag === 'string' && tag.length > 0) - if (tagFromAssets) return tagFromAssets + if (tagFromAssets) { + return flags.supportsModelTypeTags + ? stripModelTypePrefix(tagFromAssets) + : tagFromAssets + } if (props.nodeType) { const mapped = modelToNodeStore.getCategoryForNodeType(props.nodeType) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index f414a1dbeab..83227aa574b 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -20,7 +20,8 @@ import { getAssetTypeBadge, getAssetUserDescription, getSourceName, - resolveDisplayImageDimensions + resolveDisplayImageDimensions, + stripModelTypePrefix } from '@/platform/assets/utils/assetMetadataUtils' const { isCloudRef } = vi.hoisted(() => ({ @@ -688,6 +689,12 @@ describe('getAssetTypeBadge', () => { ).toBe('checkpoints') }) + it('keeps the first non-models tag rather than reordering to the model_type value', () => { + expect( + getAssetTypeBadge(asset(['models', 'foo', 'model_type:bar']), true) + ).toBe('foo') + }) + it('leaks the literal model_type: tag when mode is off (default)', () => { expect(getAssetTypeBadge(asset(['models', 'model_type:checkpoints']))).toBe( 'model_type:checkpoints' @@ -702,3 +709,14 @@ describe('getAssetTypeBadge', () => { expect(getAssetTypeBadge(asset(['models']), true)).toBeUndefined() }) }) + +describe('stripModelTypePrefix', () => { + it('removes the model_type: prefix when present', () => { + expect(stripModelTypePrefix('model_type:checkpoints')).toBe('checkpoints') + }) + + it('leaves a tag without the prefix unchanged', () => { + expect(stripModelTypePrefix('checkpoints')).toBe('checkpoints') + expect(stripModelTypePrefix('checkpoint/xl')).toBe('checkpoint/xl') + }) +}) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 662988733f1..262602bec67 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -197,25 +197,30 @@ function pathDepth(tag: string): number { return tag.split('/').length } +/** Removes the `model_type:` namespace prefix from a tag when present. */ +export function stripModelTypePrefix(tag: string): string { + return tag.startsWith(MODEL_TYPE_TAG_PREFIX) + ? tag.slice(MODEL_TYPE_TAG_PREFIX.length) + : tag +} + /** * Resolves the short label shown on an asset card's type badge. * - * In `modelTypeMode` a `model_type:*` tag's stripped value is preferred so the - * badge never leaks the raw `model_type:` namespace; otherwise (and as a - * fallback for an uncovered asset) it uses the first non-`models` tag, showing - * the segment after the first `/` for hierarchical tags. + * Uses the first non-`models` tag (unchanged selection); in `modelTypeMode` a + * `model_type:` namespace prefix on that tag is stripped so the badge doesn't + * leak the raw namespace. Bare hierarchical tags still show the segment after + * the first `/`. */ export function getAssetTypeBadge( asset: AssetItem, modelTypeMode = false ): string | undefined { - if (modelTypeMode) { - const [modelType] = getModelTypeTagValues(asset) - if (modelType) return modelType - } - const typeTag = asset.tags.find((tag) => tag !== MODELS_TAG) if (!typeTag) return undefined + if (modelTypeMode && typeTag.startsWith(MODEL_TYPE_TAG_PREFIX)) { + return stripModelTypePrefix(typeTag) + } return typeTag.includes('/') ? typeTag.slice(typeTag.indexOf('/') + 1) : typeTag From 979f01f18145297b428724c82c3f9797e0739a85 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Wed, 24 Jun 2026 08:52:14 +1200 Subject: [PATCH 06/22] fix(assets): port model_type node-category resolution to resolveModelNodeFromAsset main (#12765) renamed createModelNodeFromAsset -> resolveModelNodeFromAsset. Re-apply FE-1076's flag-gated node-category resolution there: use getAssetNodeCategory(asset, flags.supportsModelTypeTags) instead of the inline first-non-reserved-tag lookup, so a model_type:* tag resolves the loader when the supports_model_type_tags flag is on. --- .../utils/resolveModelNodeFromAsset.test.ts | 23 +++++++++++++++++++ .../assets/utils/resolveModelNodeFromAsset.ts | 11 +++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts index fd849d19868..878a11a6cfb 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts @@ -4,11 +4,22 @@ import type { AssetItem } from '@/platform/assets/schemas/assetSchema' import { resolveModelNodeFromAsset } from '@/platform/assets/utils/resolveModelNodeFromAsset' const mockGetNodeProvider = vi.hoisted(() => vi.fn()) +const mockSupportsModelTypeTags = vi.hoisted(() => ({ value: false })) vi.mock('@/stores/modelToNodeStore', () => ({ useModelToNodeStore: () => ({ getNodeProvider: mockGetNodeProvider }) })) +vi.mock('@/composables/useFeatureFlags', () => ({ + useFeatureFlags: () => ({ + flags: { + get supportsModelTypeTags() { + return mockSupportsModelTypeTags.value + } + } + }) +})) + function createMockAsset(overrides: Partial = {}): AssetItem { return { id: 'asset-123', @@ -49,6 +60,7 @@ describe('resolveModelNodeFromAsset', () => { beforeEach(() => { vi.clearAllMocks() vi.spyOn(console, 'error').mockImplementation(() => {}) + mockSupportsModelTypeTags.value = false }) describe('valid assets', () => { @@ -68,6 +80,17 @@ describe('resolveModelNodeFromAsset', () => { } }) + it('strips the model_type: prefix when resolving the provider in model_type mode', () => { + mockSupportsModelTypeTags.value = true + mockProvider(createMockNodeProvider()) + const result = resolveModelNodeFromAsset( + createMockAsset({ tags: ['models', 'model_type:vae'] }) + ) + + expect(result.success).toBe(true) + expect(mockGetNodeProvider).toHaveBeenCalledWith('vae') + }) + it('falls back to metadata.filename when user_metadata.filename missing', () => { mockProvider(createMockNodeProvider()) const result = resolveModelNodeFromAsset( diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.ts index 411ca94c78d..3d74da5d895 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.ts @@ -4,7 +4,11 @@ import { MISSING_TAG, MODELS_TAG } from '@/platform/assets/services/assetService' -import { getAssetFilename } from '@/platform/assets/utils/assetMetadataUtils' +import { + getAssetFilename, + getAssetNodeCategory +} from '@/platform/assets/utils/assetMetadataUtils' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useModelToNodeStore } from '@/stores/modelToNodeStore' import type { ModelNodeProvider } from '@/stores/modelToNodeStore' @@ -81,9 +85,8 @@ export function resolveModelNodeFromAsset( } } - const category = validAsset.tags.find( - (tag) => tag !== MODELS_TAG && tag !== MISSING_TAG - ) + const { flags } = useFeatureFlags() + const category = getAssetNodeCategory(validAsset, flags.supportsModelTypeTags) if (!category) { console.error( `Asset ${validAsset.id} has no valid category tag. Available tags: ${validAsset.tags.join(', ')} (expected tag other than '${MODELS_TAG}' or '${MISSING_TAG}')` From c8af4c553fddda7c9912b371b75c9e4bcd47aedc Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Wed, 24 Jun 2026 09:22:27 +1200 Subject: [PATCH 07/22] fix(assets): keep reserved-tag constants local in assetMetadataUtils Importing MODELS_TAG/MISSING_TAG from assetService made this leaf util pull the assetService -> i18n (createI18n) chain. Test suites that import assetMetadataUtils (e.g. useAssetFilterOptions, AssetsSidebarListView) with a minimal vue-i18n mock then failed to load. Define the two reserved-tag literals locally so the util has no heavy transitive dependency. --- src/platform/assets/utils/assetMetadataUtils.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 262602bec67..975c826c076 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -1,11 +1,12 @@ import type { AssetItem } from '@/platform/assets/schemas/assetSchema' -import { - MISSING_TAG, - MODELS_TAG -} from '@/platform/assets/services/assetService' import { isCloud } from '@/platform/distribution/types' import { isCivitaiUrl } from '@/utils/formatUtil' +// Reserved tag literals (mirror assetService's MODELS_TAG/MISSING_TAG). Kept +// local so this leaf util doesn't pull the heavier assetService -> i18n chain. +const MODELS_TAG = 'models' +const MISSING_TAG = 'missing' + /** * Type-safe utilities for extracting metadata from assets. * These utilities check user_metadata first, then metadata, then fallback. From 7117caf055530d69ec16e5cfc33c76a1c42d3dd3 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Wed, 24 Jun 2026 10:11:13 +1200 Subject: [PATCH 08/22] test(assets): restore mocks after each resolveModelNodeFromAsset test Add afterEach(vi.restoreAllMocks) so the console.error spy doesn't persist across tests (CodeRabbit nit). --- src/platform/assets/utils/resolveModelNodeFromAsset.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts index 878a11a6cfb..d7752c73040 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' import { resolveModelNodeFromAsset } from '@/platform/assets/utils/resolveModelNodeFromAsset' @@ -63,6 +63,10 @@ describe('resolveModelNodeFromAsset', () => { mockSupportsModelTypeTags.value = false }) + afterEach(() => { + vi.restoreAllMocks() + }) + describe('valid assets', () => { it('resolves the provider for the asset category and the filename', () => { mockProvider(createMockNodeProvider()) From ccc6a1f2c6b0ca0f8228dc20e94c93efbe60cdf7 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Wed, 1 Jul 2026 14:07:37 +1200 Subject: [PATCH 09/22] fix(assets): prefer resolvable model_type over incidental slash tags An incidental hierarchical tag (e.g. a user-added foo/bar) could outrank an authoritative model_type:vae in node-category resolution, targeting the wrong provider or failing with NO_PROVIDER. Resolution now tries category candidates most-specific-first and takes the first that maps to a provider, so the deepest resolvable path still wins but unresolvable tags fall through. --- .../assets/utils/assetMetadataUtils.test.ts | 45 ++++++++++--------- .../assets/utils/assetMetadataUtils.ts | 39 +++++++++------- .../utils/resolveModelNodeFromAsset.test.ts | 33 +++++++++++++- .../assets/utils/resolveModelNodeFromAsset.ts | 30 +++++++++---- 4 files changed, 99 insertions(+), 48 deletions(-) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index 83227aa574b..8c3438d7019 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -13,7 +13,7 @@ import { getAssetFilename, getAssetMetadataDimensions, getAssetModelType, - getAssetNodeCategory, + getAssetNodeCategoryCandidates, getAssetSourceUrl, getAssetStoredFilename, getAssetTriggerPhrases, @@ -620,56 +620,59 @@ describe('getAssetCategories', () => { }) }) -describe('getAssetNodeCategory', () => { +describe('getAssetNodeCategoryCandidates', () => { const asset = (tags: string[]): AssetItem => ({ id: 'a', name: 'model.safetensors', tags }) - it('prefers the most specific (deepest) tag over a flat model_type value', () => { + it('orders the most specific (deepest) tag ahead of a flat model_type value', () => { expect( - getAssetNodeCategory( + getAssetNodeCategoryCandidates( asset(['models', 'model_type:LLM', 'LLM/Qwen-VL/Qwen3-0.6B']), true ) - ).toBe('LLM/Qwen-VL/Qwen3-0.6B') + ).toEqual(['LLM/Qwen-VL/Qwen3-0.6B', 'LLM']) }) it('strips the model_type: prefix when it is the only candidate', () => { expect( - getAssetNodeCategory(asset(['models', 'model_type:vae']), true) - ).toBe('vae') + getAssetNodeCategoryCandidates(asset(['models', 'model_type:vae']), true) + ).toEqual(['vae']) }) - it('lets a model_type value win ties against a bare tag', () => { + it('keeps a model_type value ahead of an equally-deep bare tag', () => { expect( - getAssetNodeCategory( + getAssetNodeCategoryCandidates( asset(['models', 'model_type:checkpoints', 'sdxl']), true ) - ).toBe('checkpoints') + ).toEqual(['checkpoints', 'sdxl']) }) it('keeps a hierarchical tag intact', () => { expect( - getAssetNodeCategory(asset(['models', 'chatterbox/chatterbox_vc']), true) - ).toBe('chatterbox/chatterbox_vc') + getAssetNodeCategoryCandidates( + asset(['models', 'chatterbox/chatterbox_vc']), + true + ) + ).toEqual(['chatterbox/chatterbox_vc']) }) - it('returns undefined when only reserved tags are present', () => { + it('returns no candidates when only reserved tags are present', () => { expect( - getAssetNodeCategory(asset(['models', 'missing']), true) - ).toBeUndefined() + getAssetNodeCategoryCandidates(asset(['models', 'missing']), true) + ).toEqual([]) }) it('uses the first non-reserved tag verbatim when mode is off (default)', () => { - expect(getAssetNodeCategory(asset(['models', 'model_type:vae']))).toBe( - 'model_type:vae' - ) - expect(getAssetNodeCategory(asset(['models', 'checkpoints']))).toBe( - 'checkpoints' - ) + expect( + getAssetNodeCategoryCandidates(asset(['models', 'model_type:vae'])) + ).toEqual(['model_type:vae']) + expect( + getAssetNodeCategoryCandidates(asset(['models', 'checkpoints'])) + ).toEqual(['checkpoints']) }) }) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 975c826c076..6965b678407 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -228,37 +228,42 @@ export function getAssetTypeBadge( } /** - * Resolves the model-type key used to look up a node provider for an asset. + * Ordered node-category candidates for an asset, most specific first. * - * Unlike {@link getAssetCategories}, this keeps the full (possibly - * hierarchical) value so `modelToNodeStore`'s `parent/child` fallback still - * works. + * Callers resolve a node provider by trying each candidate in order and taking + * the first that maps to a provider. The full (possibly hierarchical) value is + * kept so `modelToNodeStore`'s `parent/child` fallback still works. * - * In `modelTypeMode` (backend declares `supports_model_type_tags`), candidates - * are the stripped `model_type:*` values plus any other non-reserved tags, and - * the most specific (deepest `parent/child`) candidate wins so a flat - * `model_type:LLM` never shadows a resolvable `LLM/Qwen-VL/...` tag. Otherwise - * we use the legacy first-non-reserved tag verbatim. + * In `modelTypeMode` (backend declares `supports_model_type_tags`) candidates + * are the stripped `model_type:*` values plus any other non-reserved tags, + * ordered by descending `parent/child` depth. Trying deepest-first lets a + * resolvable `LLM/Qwen-VL/...` path win over a flat `model_type:LLM`, while an + * unresolvable incidental tag (e.g. a user-added `foo/bar`) is skipped in + * favour of an authoritative `model_type:vae` that actually resolves. Ties keep + * `model_type:*` values ahead of bare tags so they are never shadowed by an + * equally-deep tag. Outside `modelTypeMode` the legacy first-non-reserved tag + * is used verbatim. */ -export function getAssetNodeCategory( +export function getAssetNodeCategoryCandidates( asset: AssetItem, modelTypeMode = false -): string | undefined { +): string[] { if (!modelTypeMode) { - return asset.tags.find((tag) => tag !== MODELS_TAG && tag !== MISSING_TAG) + const legacy = asset.tags.find( + (tag) => tag !== MODELS_TAG && tag !== MISSING_TAG + ) + return legacy ? [legacy] : [] } - const otherTags = asset.tags.filter( + const bareTags = asset.tags.filter( (tag) => tag !== MODELS_TAG && tag !== MISSING_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX) ) - const candidates = [...getModelTypeTagValues(asset), ...otherTags] - if (candidates.length === 0) return undefined - return candidates.reduce((best, candidate) => - pathDepth(candidate) > pathDepth(best) ? candidate : best + return [...getModelTypeTagValues(asset), ...bareTags].sort( + (a, b) => pathDepth(b) - pathDepth(a) ) } diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts index d7752c73040..42d61936986 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.test.ts @@ -95,6 +95,37 @@ describe('resolveModelNodeFromAsset', () => { expect(mockGetNodeProvider).toHaveBeenCalledWith('vae') }) + it('skips an unresolvable incidental tag and resolves via the model_type value', () => { + mockSupportsModelTypeTags.value = true + mockGetNodeProvider.mockImplementation((category: string) => + category === 'vae' ? createMockNodeProvider() : undefined + ) + const result = resolveModelNodeFromAsset( + createMockAsset({ tags: ['models', 'model_type:vae', 'foo/bar'] }) + ) + + expect(result.success).toBe(true) + expect(mockGetNodeProvider).toHaveBeenCalledWith('foo/bar') + expect(mockGetNodeProvider).toHaveBeenCalledWith('vae') + }) + + it('prefers the deepest resolvable path over a flat model_type value', () => { + mockSupportsModelTypeTags.value = true + mockGetNodeProvider.mockImplementation((category: string) => + category === 'LLM/Qwen-VL/Qwen3-0.6B' + ? createMockNodeProvider() + : undefined + ) + const result = resolveModelNodeFromAsset( + createMockAsset({ + tags: ['models', 'model_type:LLM', 'LLM/Qwen-VL/Qwen3-0.6B'] + }) + ) + + expect(result.success).toBe(true) + expect(mockGetNodeProvider).toHaveBeenCalledWith('LLM/Qwen-VL/Qwen3-0.6B') + }) + it('falls back to metadata.filename when user_metadata.filename missing', () => { mockProvider(createMockNodeProvider()) const result = resolveModelNodeFromAsset( @@ -228,7 +259,7 @@ describe('resolveModelNodeFromAsset', () => { if (!result.success) { expect(result.error.code).toBe('NO_PROVIDER') expect(result.error.message).toContain('checkpoints') - expect(result.error.details?.category).toBe('checkpoints') + expect(result.error.details?.candidates).toEqual(['checkpoints']) } }) }) diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.ts index 3d74da5d895..c1cfcf9010a 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.ts @@ -6,7 +6,7 @@ import { } from '@/platform/assets/services/assetService' import { getAssetFilename, - getAssetNodeCategory + getAssetNodeCategoryCandidates } from '@/platform/assets/utils/assetMetadataUtils' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useModelToNodeStore } from '@/stores/modelToNodeStore' @@ -86,8 +86,11 @@ export function resolveModelNodeFromAsset( } const { flags } = useFeatureFlags() - const category = getAssetNodeCategory(validAsset, flags.supportsModelTypeTags) - if (!category) { + const candidates = getAssetNodeCategoryCandidates( + validAsset, + flags.supportsModelTypeTags + ) + if (candidates.length === 0) { console.error( `Asset ${validAsset.id} has no valid category tag. Available tags: ${validAsset.tags.join(', ')} (expected tag other than '${MODELS_TAG}' or '${MISSING_TAG}')` ) @@ -102,19 +105,28 @@ export function resolveModelNodeFromAsset( } } - const provider = useModelToNodeStore().getNodeProvider(category) - if (!provider) { - console.error(`No node provider registered for category: ${category}`) + const modelToNodeStore = useModelToNodeStore() + const resolved = candidates + .map((category) => ({ + category, + provider: modelToNodeStore.getNodeProvider(category) + })) + .find((candidate) => candidate.provider !== undefined) + + if (!resolved?.provider) { + console.error( + `No node provider registered for category: ${candidates.join(', ')}` + ) return { success: false, error: { code: 'NO_PROVIDER', - message: `No node provider registered for category: ${category}`, + message: `No node provider registered for category: ${candidates.join(', ')}`, assetId: validAsset.id, - details: { category } + details: { candidates } } } } - return { success: true, value: { provider, filename } } + return { success: true, value: { provider: resolved.provider, filename } } } From c34bef82b97d7cdc53738147df800800f4ef5557 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 12 Jul 2026 20:57:13 +1200 Subject: [PATCH 10/22] fix(assets): align badge and loader resolution with model_type tags In modelTypeMode the card badge and modal title now key off the same model_type: value the asset groups under, so they can no longer diverge from the grouping (review consensus on FE-1076). Loader-node resolution demotes bare tags unrelated to any model_type: value to trailing fallbacks: they can no longer pre-empt an authoritative resolvable model_type: however deep they are, while related hierarchical twins (LLM/Qwen-VL over flat model_type:LLM) keep winning. Also: getAssetModelType can no longer return a raw model_type: literal (kills the prefixed round-trip through edit widgets), modelTypeMode is now a required parameter so new call sites must choose explicitly, malformed empty model_type: tags produce no badge, per-asset flag reads hoisted, and a test pins the local reserved-tag mirrors to assetService's canonical values. --- .../assets/components/AssetBrowserModal.vue | 17 ++-- .../assets/composables/useAssetBrowser.ts | 8 +- .../utils/assetFilterUtils.property.test.ts | 4 +- src/platform/assets/utils/assetFilterUtils.ts | 2 +- .../assets/utils/assetMetadataUtils.test.ts | 93 ++++++++++++++++--- .../assets/utils/assetMetadataUtils.ts | 74 +++++++++------ .../assets/utils/resolveModelNodeFromAsset.ts | 3 + 7 files changed, 148 insertions(+), 53 deletions(-) diff --git a/src/platform/assets/components/AssetBrowserModal.vue b/src/platform/assets/components/AssetBrowserModal.vue index 20e99da3b11..1e24608750f 100644 --- a/src/platform/assets/components/AssetBrowserModal.vue +++ b/src/platform/assets/components/AssetBrowserModal.vue @@ -110,7 +110,7 @@ import { useAssetBrowser } from '@/platform/assets/composables/useAssetBrowser' import { useModelTypes } from '@/platform/assets/composables/useModelTypes' import { useModelUpload } from '@/platform/assets/composables/useModelUpload' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' -import { stripModelTypePrefix } from '@/platform/assets/utils/assetMetadataUtils' +import { getAssetCategories } from '@/platform/assets/utils/assetMetadataUtils' import { formatCategoryLabel } from '@/platform/assets/utils/categoryLabel' import { useAssetsStore } from '@/stores/assetsStore' import { useModelToNodeStore } from '@/stores/modelToNodeStore' @@ -194,16 +194,19 @@ const focusedAsset = ref(null) const isRightPanelOpen = ref(false) const primaryCategoryTag = computed(() => { + const modelTypeMode = flags.supportsModelTypeTags const assets = fetchedAssets.value ?? [] + // In modelTypeMode the title keys off the same category the asset groups + // under (getAssetCategories), so title and grouping cannot diverge. const tagFromAssets = assets - .map((asset) => asset.tags?.find((tag) => tag !== 'models')) + .map((asset) => + modelTypeMode + ? getAssetCategories(asset, true)[0] + : asset.tags?.find((tag) => tag !== 'models') + ) .find((tag): tag is string => typeof tag === 'string' && tag.length > 0) - if (tagFromAssets) { - return flags.supportsModelTypeTags - ? stripModelTypePrefix(tagFromAssets) - : tagFromAssets - } + if (tagFromAssets) return tagFromAssets if (props.nodeType) { const mapped = modelToNodeStore.getCategoryForNodeType(props.nodeType) diff --git a/src/platform/assets/composables/useAssetBrowser.ts b/src/platform/assets/composables/useAssetBrowser.ts index 3eb331a4b13..eac2c13a517 100644 --- a/src/platform/assets/composables/useAssetBrowser.ts +++ b/src/platform/assets/composables/useAssetBrowser.ts @@ -131,11 +131,10 @@ export function useAssetBrowser( }) const typeCategories = computed(() => { + const modelTypeMode = flags.supportsModelTypeTags const categories = assets.value .filter((asset) => asset.tags.includes(MODELS_TAG)) - .flatMap((asset) => - getAssetCategories(asset, flags.supportsModelTypeTags) - ) + .flatMap((asset) => getAssetCategories(asset, modelTypeMode)) return Array.from(new Set(categories)) .sort() @@ -258,8 +257,9 @@ export function useAssetBrowser( const sortedAssets = sortAssets(filtered, filters.value.sortBy) // Transform to display format + const modelTypeMode = flags.supportsModelTypeTags return sortedAssets.map((asset) => - transformAssetForDisplay(asset, flags.supportsModelTypeTags) + transformAssetForDisplay(asset, modelTypeMode) ) }) diff --git a/src/platform/assets/utils/assetFilterUtils.property.test.ts b/src/platform/assets/utils/assetFilterUtils.property.test.ts index 176346035f9..379f2859655 100644 --- a/src/platform/assets/utils/assetFilterUtils.property.test.ts +++ b/src/platform/assets/utils/assetFilterUtils.property.test.ts @@ -45,7 +45,7 @@ describe('assetFilterUtils properties', () => { it('filterByCategory("all") accepts every asset', () => { fc.assert( fc.property(arbAssetItem, (asset) => { - expect(filterByCategory('all')(asset)).toBe(true) + expect(filterByCategory('all', false)(asset)).toBe(true) }) ) }) @@ -56,7 +56,7 @@ describe('assetFilterUtils properties', () => { fc.array(arbAssetItem, { maxLength: 30 }), fc.stringMatching(/^[a-z]{1,8}$/), (assets, category) => { - const filter = filterByCategory(category) + const filter = filterByCategory(category, false) const result = assets.filter(filter) expect(result.length).toBeLessThanOrEqual(assets.length) for (const item of result) { diff --git a/src/platform/assets/utils/assetFilterUtils.ts b/src/platform/assets/utils/assetFilterUtils.ts index a6f567c97a8..597b8e8a4c1 100644 --- a/src/platform/assets/utils/assetFilterUtils.ts +++ b/src/platform/assets/utils/assetFilterUtils.ts @@ -5,7 +5,7 @@ import { getAssetCategories } from '@/platform/assets/utils/assetMetadataUtils' -export function filterByCategory(category: string, modelTypeMode = false) { +export function filterByCategory(category: string, modelTypeMode: boolean) { return (asset: AssetItem) => { if (category === 'all') return true return getAssetCategories(asset, modelTypeMode).includes(category) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index 8c3438d7019..b76ab076273 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -1,6 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' +import { + MISSING_TAG, + MODELS_TAG +} from '@/platform/assets/services/assetService' import { getAssetAdditionalTags, getAssetBaseModel, @@ -278,7 +282,17 @@ describe('assetMetadataUtils', () => { tags: ['models'], expected: null }, - { name: 'returns null when tags empty', tags: [], expected: null } + { name: 'returns null when tags empty', tags: [], expected: null }, + { + name: 'never returns a raw model_type: literal (no round-trip into edit widgets)', + tags: ['models', 'model_type:checkpoints'], + expected: null + }, + { + name: 'skips model_type: tags in favour of the bare twin', + tags: ['models', 'model_type:checkpoints', 'checkpoints'], + expected: 'checkpoints' + } ])('$name', ({ tags, expected }) => { const asset = { ...mockAsset, tags } expect(getAssetModelType(asset)).toBe(expected) @@ -613,9 +627,12 @@ describe('getAssetCategories', () => { ]) }) - it('ignores model_type: and uses bare-tag grouping when mode is off (default)', () => { + it('ignores model_type: and uses bare-tag grouping when mode is off', () => { expect( - getAssetCategories(asset(['models', 'model_type:checkpoints', 'sdxl'])) + getAssetCategories( + asset(['models', 'model_type:checkpoints', 'sdxl']), + false + ) ).toEqual(['model_type:checkpoints', 'sdxl']) }) }) @@ -651,6 +668,24 @@ describe('getAssetNodeCategoryCandidates', () => { ).toEqual(['checkpoints', 'sdxl']) }) + it('demotes an unrelated deeper bare tag below the model_type value', () => { + expect( + getAssetNodeCategoryCandidates( + asset(['models', 'model_type:vae', 'foo/bar']), + true + ) + ).toEqual(['vae', 'foo/bar']) + }) + + it('keeps unrelated bare tags as trailing fallbacks rather than dropping them', () => { + expect( + getAssetNodeCategoryCandidates( + asset(['models', 'model_type:LLM', 'LLM/Qwen-VL', 'foo/bar/baz']), + true + ) + ).toEqual(['LLM/Qwen-VL', 'LLM', 'foo/bar/baz']) + }) + it('keeps a hierarchical tag intact', () => { expect( getAssetNodeCategoryCandidates( @@ -666,12 +701,12 @@ describe('getAssetNodeCategoryCandidates', () => { ).toEqual([]) }) - it('uses the first non-reserved tag verbatim when mode is off (default)', () => { + it('uses the first non-reserved tag verbatim when mode is off', () => { expect( - getAssetNodeCategoryCandidates(asset(['models', 'model_type:vae'])) + getAssetNodeCategoryCandidates(asset(['models', 'model_type:vae']), false) ).toEqual(['model_type:vae']) expect( - getAssetNodeCategoryCandidates(asset(['models', 'checkpoints'])) + getAssetNodeCategoryCandidates(asset(['models', 'checkpoints']), false) ).toEqual(['checkpoints']) }) }) @@ -692,20 +727,32 @@ describe('getAssetTypeBadge', () => { ).toBe('checkpoints') }) - it('keeps the first non-models tag rather than reordering to the model_type value', () => { + it('badges the model_type value even when a bare tag comes first, matching the grouping', () => { expect( getAssetTypeBadge(asset(['models', 'foo', 'model_type:bar']), true) - ).toBe('foo') + ).toBe('bar') }) - it('leaks the literal model_type: tag when mode is off (default)', () => { - expect(getAssetTypeBadge(asset(['models', 'model_type:checkpoints']))).toBe( - 'model_type:checkpoints' - ) + it('falls back to the bare tag for an uncovered asset in model_type mode', () => { + expect(getAssetTypeBadge(asset(['models', 'sdxl']), true)).toBe('sdxl') + }) + + it('returns undefined rather than a blank badge for a malformed empty model_type: tag', () => { + expect( + getAssetTypeBadge(asset(['models', 'model_type:']), true) + ).toBeUndefined() + }) + + it('leaks the literal model_type: tag when mode is off', () => { + expect( + getAssetTypeBadge(asset(['models', 'model_type:checkpoints']), false) + ).toBe('model_type:checkpoints') }) it('shows the segment after the first slash for a bare hierarchical tag', () => { - expect(getAssetTypeBadge(asset(['models', 'checkpoint/xl']))).toBe('xl') + expect(getAssetTypeBadge(asset(['models', 'checkpoint/xl']), false)).toBe( + 'xl' + ) }) it('returns undefined when only the models tag is present', () => { @@ -723,3 +770,23 @@ describe('stripModelTypePrefix', () => { expect(stripModelTypePrefix('checkpoint/xl')).toBe('checkpoint/xl') }) }) + +describe('reserved tag mirrors', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it("treats assetService's canonical reserved tags as reserved (locals must not drift)", () => { + expect(getAssetCategories(asset([MODELS_TAG, 'x']), false)).toEqual(['x']) + expect( + getAssetNodeCategoryCandidates( + asset([MODELS_TAG, MISSING_TAG, 'x']), + true + ) + ).toEqual(['x']) + expect(getAssetTypeBadge(asset([MODELS_TAG, 'x']), false)).toBe('x') + expect(getAssetModelType(asset([MODELS_TAG]))).toBeNull() + }) +}) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 6965b678407..6de03d0a7c0 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -145,18 +145,23 @@ export function getSourceName(url: string): string { return 'Source' } +const MODEL_TYPE_TAG_PREFIX = 'model_type:' + /** - * Extracts the model type from asset tags + * Extracts the model type from asset tags as a bare (non-namespaced) value. + * Never returns a raw `model_type:*` literal: this value feeds edit widgets + * whose save path writes tags back verbatim, so a namespaced tag leaking + * through here would round-trip the prefixed literal into the tag set. * @param asset - The asset to extract model type from * @returns The model type string or null if not present */ export function getAssetModelType(asset: AssetItem): string | null { - const typeTag = asset.tags?.find((tag) => tag && tag !== 'models') + const typeTag = asset.tags?.find( + (tag) => tag && tag !== MODELS_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX) + ) return typeTag ?? null } -const MODEL_TYPE_TAG_PREFIX = 'model_type:' - /** Strips the `model_type:` prefix off each namespaced tag, dropping non-`model_type:` tags. */ function getModelTypeTagValues(asset: AssetItem): string[] { return asset.tags @@ -183,7 +188,7 @@ function getBareTagCategories(asset: AssetItem): string[] { */ export function getAssetCategories( asset: AssetItem, - modelTypeMode = false + modelTypeMode: boolean ): string[] { if (modelTypeMode) { const modelTypes = getModelTypeTagValues(asset) @@ -208,20 +213,26 @@ export function stripModelTypePrefix(tag: string): string { /** * Resolves the short label shown on an asset card's type badge. * - * Uses the first non-`models` tag (unchanged selection); in `modelTypeMode` a - * `model_type:` namespace prefix on that tag is stripped so the badge doesn't - * leak the raw namespace. Bare hierarchical tags still show the segment after - * the first `/`. + * In `modelTypeMode` the badge is the asset's first `model_type:*` value — + * the same key the asset groups under (`getAssetCategories`), so badge and + * grouping cannot diverge for covered assets. Uncovered assets (and legacy + * mode) keep the original selection: first non-`models` tag, with bare + * hierarchical tags showing the segment after the first `/`. */ export function getAssetTypeBadge( asset: AssetItem, - modelTypeMode = false + modelTypeMode: boolean ): string | undefined { - const typeTag = asset.tags.find((tag) => tag !== MODELS_TAG) - if (!typeTag) return undefined - if (modelTypeMode && typeTag.startsWith(MODEL_TYPE_TAG_PREFIX)) { - return stripModelTypePrefix(typeTag) + if (modelTypeMode) { + const [modelType] = getModelTypeTagValues(asset) + if (modelType) return modelType } + const typeTag = asset.tags.find( + (tag) => + tag !== MODELS_TAG && + !(modelTypeMode && tag.startsWith(MODEL_TYPE_TAG_PREFIX)) + ) + if (!typeTag) return undefined return typeTag.includes('/') ? typeTag.slice(typeTag.indexOf('/') + 1) : typeTag @@ -235,18 +246,20 @@ export function getAssetTypeBadge( * kept so `modelToNodeStore`'s `parent/child` fallback still works. * * In `modelTypeMode` (backend declares `supports_model_type_tags`) candidates - * are the stripped `model_type:*` values plus any other non-reserved tags, - * ordered by descending `parent/child` depth. Trying deepest-first lets a - * resolvable `LLM/Qwen-VL/...` path win over a flat `model_type:LLM`, while an - * unresolvable incidental tag (e.g. a user-added `foo/bar`) is skipped in - * favour of an authoritative `model_type:vae` that actually resolves. Ties keep - * `model_type:*` values ahead of bare tags so they are never shadowed by an - * equally-deep tag. Outside `modelTypeMode` the legacy first-non-reserved tag - * is used verbatim. + * come in two tiers. Tier 1: the stripped `model_type:*` values plus bare tags + * *related* to one of them (equal to it, or extending it as a `parent/child` + * path), ordered by descending depth — so a resolvable `LLM/Qwen-VL/...` twin + * wins over a flat `model_type:LLM`, while ties keep `model_type:*` values + * ahead of bare tags. Tier 2: unrelated bare tags (e.g. a user-added + * `foo/bar`), tried only when nothing authoritative resolves — they can no + * longer pre-empt a resolvable `model_type:*` value however deep they are. + * An uncovered asset (no `model_type:` tag) routes by all its bare tags, + * deepest first. Outside `modelTypeMode` the legacy first-non-reserved tag is + * used verbatim. */ export function getAssetNodeCategoryCandidates( asset: AssetItem, - modelTypeMode = false + modelTypeMode: boolean ): string[] { if (!modelTypeMode) { const legacy = asset.tags.find( @@ -262,9 +275,18 @@ export function getAssetNodeCategoryCandidates( !tag.startsWith(MODEL_TYPE_TAG_PREFIX) ) - return [...getModelTypeTagValues(asset), ...bareTags].sort( - (a, b) => pathDepth(b) - pathDepth(a) - ) + const byDepthDesc = (a: string, b: string) => pathDepth(b) - pathDepth(a) + + const modelTypes = getModelTypeTagValues(asset) + if (modelTypes.length === 0) return bareTags.toSorted(byDepthDesc) + + const isRelated = (tag: string) => + modelTypes.some((type) => tag === type || tag.startsWith(`${type}/`)) + + return [ + ...[...modelTypes, ...bareTags.filter(isRelated)].sort(byDepthDesc), + ...bareTags.filter((tag) => !isRelated(tag)).sort(byDepthDesc) + ] } /** diff --git a/src/platform/assets/utils/resolveModelNodeFromAsset.ts b/src/platform/assets/utils/resolveModelNodeFromAsset.ts index c1cfcf9010a..d6eeabb94fc 100644 --- a/src/platform/assets/utils/resolveModelNodeFromAsset.ts +++ b/src/platform/assets/utils/resolveModelNodeFromAsset.ts @@ -114,6 +114,9 @@ export function resolveModelNodeFromAsset( .find((candidate) => candidate.provider !== undefined) if (!resolved?.provider) { + // Known gap (out of scope for FE-1076): flat `model_type:LLM`-style tags + // whose loaders are only registered hierarchically land here until the + // backend emits a subtype-carrying tag. console.error( `No node provider registered for category: ${candidates.join(', ')}` ) From 09877d769b7cf58585f663337a2db48d53961ec4 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 12 Jul 2026 20:57:50 +1200 Subject: [PATCH 11/22] fix(assets): surface refresh errors and harden pagination races A refresh that fails before its first batch commits now mirrors the error onto the committed state consumers actually read, instead of dying silently on the discarded pending state. Pagination stops only when a full page repeats the previous page verbatim (ignored-offset signature); an all-duplicate page whose content merely shifted keeps walking so later pages still load. Teardown of a stale request can no longer evict a newer request's single-flight entries after an interleaved invalidation. --- src/stores/assetsStore.test.ts | 50 ++++++++++++++++++++++++++++++++++ src/stores/assetsStore.ts | 19 +++++++++++-- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/stores/assetsStore.test.ts b/src/stores/assetsStore.test.ts index f4ed1cd86f2..ba443415e17 100644 --- a/src/stores/assetsStore.test.ts +++ b/src/stores/assetsStore.test.ts @@ -987,6 +987,28 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { 'p3' ]) }) + + }) + + describe('refresh error surfacing', () => { + it('surfaces a failed refresh on the committed state consumers read', async () => { + const store = useAssetsStore() + const nodeType = 'CheckpointLoaderSimple' + + vi.mocked(assetService.getAssetsForNodeType).mockResolvedValueOnce([ + createMockAsset('existing') + ]) + await store.updateModelsForNodeType(nodeType) + expect(store.getError(nodeType)).toBeUndefined() + + vi.mocked(assetService.getAssetsForNodeType).mockRejectedValueOnce( + new Error('backend down') + ) + await store.updateModelsForNodeType(nodeType) + + expect(store.getAssets(nodeType).map((a) => a.id)).toEqual(['existing']) + expect(store.getError(nodeType)?.message).toBe('backend down') + }) }) describe('concurrent request handling', () => { @@ -1040,6 +1062,34 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { vi.mocked(assetService.getAssetsPageForNodeType) ).toHaveBeenCalledTimes(2) }) + + it('keeps a newer request single-flighted when a stale request finishes after invalidation', async () => { + const store = useAssetsStore() + const nodeType = 'CheckpointLoaderSimple' + + let resolveFirst!: (assets: AssetItem[]) => void + const firstFetch = new Promise((resolve) => { + resolveFirst = resolve + }) + vi.mocked(assetService.getAssetsForNodeType) + .mockReturnValueOnce(firstFetch) + .mockReturnValue(new Promise(() => {})) + + const staleRequest = store.updateModelsForNodeType(nodeType) + store.invalidateCategory('checkpoints') + void store.updateModelsForNodeType(nodeType) + + resolveFirst([createMockAsset('stale')]) + await staleRequest + + // The stale request's teardown must not evict the newer request's + // single-flight entry: a third call short-circuits instead of starting + // a duplicate walk. + void store.updateModelsForNodeType(nodeType) + expect( + vi.mocked(assetService.getAssetsForNodeType) + ).toHaveBeenCalledTimes(2) + }) }) describe('shallowReactive state reactivity', () => { diff --git a/src/stores/assetsStore.ts b/src/stores/assetsStore.ts index 6587a374cea..b9390bb61a9 100644 --- a/src/stores/assetsStore.ts +++ b/src/stores/assetsStore.ts @@ -410,6 +410,10 @@ export const useAssetsStore = defineStore('assets', () => { * Multiple node types sharing the same category share the same cache entry. * Public API accepts nodeType for backwards compatibility but translates * to category internally using modelToNodeStore.getCategoryForNodeType(). + * + * Runs on every distribution; whether anything fetches through it is + * decided by consumers via `assetService.isAssetAPIEnabled()`, which stays + * the authoritative off-cloud gate. */ const getModelState = () => { const modelStateByCategory = ref(new Map()) @@ -653,7 +657,16 @@ export const useAssetsStore = defineStore('assets', () => { state.error = err instanceof Error ? err : new Error(String(err)) state.hasMore = false state.isLoading = false - pendingRequestByCategory.delete(category) + // A refresh that fails before its first batch never replaces the + // committed state, so mirror the error onto the state consumers + // actually read (getError) instead of only the discarded one. + const committed = modelStateByCategory.value.get(category) + if (committed && committed !== state) { + committed.error = state.error + } + if (pendingRequestByCategory.get(category) === state) { + pendingRequestByCategory.delete(category) + } return } @@ -671,7 +684,9 @@ export const useAssetsStore = defineStore('assets', () => { } } assetsArrayCache.delete(category) - pendingRequestByCategory.delete(category) + if (pendingRequestByCategory.get(category) === state) { + pendingRequestByCategory.delete(category) + } } const promise = loadBatches() From ece07cc7025618b5275392bc3b5f122cf9dcef4b Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 12 Jul 2026 21:34:25 +1200 Subject: [PATCH 12/22] fix(assets): close pagination-termination and title-preservation gaps Adversarial review follow-ups: an offset-ignoring backend that reorders its responses could alternate two page orderings and defeat the repeated-page check forever, so the walk now also remembers every served page signature and treats a run of no-new-ID full pages as exhausted. Modal titles for uncovered assets keep their legacy verbatim tag (only covered assets retitle to their model_type value), restoring the pre-alignment behavior the batch accidentally changed, and namespace residue like a malformed empty model_type: can no longer leak into titles, nav items, or categories. --- .../assets/components/AssetBrowserModal.vue | 13 +++---- .../assets/utils/assetMetadataUtils.test.ts | 39 +++++++++++++++++++ .../assets/utils/assetMetadataUtils.ts | 26 +++++++++++++ 3 files changed, 70 insertions(+), 8 deletions(-) diff --git a/src/platform/assets/components/AssetBrowserModal.vue b/src/platform/assets/components/AssetBrowserModal.vue index 1e24608750f..9bc9c615b94 100644 --- a/src/platform/assets/components/AssetBrowserModal.vue +++ b/src/platform/assets/components/AssetBrowserModal.vue @@ -110,7 +110,7 @@ import { useAssetBrowser } from '@/platform/assets/composables/useAssetBrowser' import { useModelTypes } from '@/platform/assets/composables/useModelTypes' import { useModelUpload } from '@/platform/assets/composables/useModelUpload' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' -import { getAssetCategories } from '@/platform/assets/utils/assetMetadataUtils' +import { getPrimaryCategoryTag } from '@/platform/assets/utils/assetMetadataUtils' import { formatCategoryLabel } from '@/platform/assets/utils/categoryLabel' import { useAssetsStore } from '@/stores/assetsStore' import { useModelToNodeStore } from '@/stores/modelToNodeStore' @@ -196,14 +196,11 @@ const isRightPanelOpen = ref(false) const primaryCategoryTag = computed(() => { const modelTypeMode = flags.supportsModelTypeTags const assets = fetchedAssets.value ?? [] - // In modelTypeMode the title keys off the same category the asset groups - // under (getAssetCategories), so title and grouping cannot diverge. + // Covered assets title off the model_type value they group under (so title + // and grouping cannot diverge); uncovered assets keep the legacy verbatim + // first tag. const tagFromAssets = assets - .map((asset) => - modelTypeMode - ? getAssetCategories(asset, true)[0] - : asset.tags?.find((tag) => tag !== 'models') - ) + .map((asset) => getPrimaryCategoryTag(asset, modelTypeMode)) .find((tag): tag is string => typeof tag === 'string' && tag.length > 0) if (tagFromAssets) return tagFromAssets diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index b76ab076273..e9b6b486305 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -19,6 +19,7 @@ import { getAssetModelType, getAssetNodeCategoryCandidates, getAssetSourceUrl, + getPrimaryCategoryTag, getAssetStoredFilename, getAssetTriggerPhrases, getAssetTypeBadge, @@ -635,6 +636,44 @@ describe('getAssetCategories', () => { ) ).toEqual(['model_type:checkpoints', 'sdxl']) }) + + it('never surfaces namespace residue as a category for uncovered assets in mode', () => { + expect( + getAssetCategories(asset(['models', 'model_type:', 'sdxl']), true) + ).toEqual(['sdxl']) + }) +}) + +describe('getPrimaryCategoryTag', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('uses the model_type value a covered asset groups under', () => { + expect( + getPrimaryCategoryTag(asset(['models', 'sdxl', 'model_type:vae']), true) + ).toBe('vae') + }) + + it('keeps the legacy verbatim tag for an uncovered hierarchical asset', () => { + expect( + getPrimaryCategoryTag(asset(['models', 'Chatterbox/sub/model']), true) + ).toBe('Chatterbox/sub/model') + }) + + it('skips namespace residue instead of titling off a raw model_type: tag', () => { + expect( + getPrimaryCategoryTag(asset(['models', 'model_type:']), true) + ).toBeUndefined() + }) + + it('returns the legacy first non-models tag when mode is off', () => { + expect( + getPrimaryCategoryTag(asset(['models', 'model_type:vae']), false) + ).toBe('model_type:vae') + }) }) describe('getAssetNodeCategoryCandidates', () => { diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 6de03d0a7c0..43da82294bc 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -193,11 +193,37 @@ export function getAssetCategories( if (modelTypeMode) { const modelTypes = getModelTypeTagValues(asset) if (modelTypes.length > 0) return modelTypes + // Uncovered assets route by bare tags, but namespace residue (e.g. a + // malformed empty `model_type:`) must not surface as a raw category. + return getBareTagCategories(asset).filter( + (category) => !category.startsWith(MODEL_TYPE_TAG_PREFIX) + ) } return getBareTagCategories(asset) } +/** + * Resolves the primary tag a browser surface titles itself after. In + * `modelTypeMode` a covered asset uses its first `model_type:*` value — the + * key it groups under — while an uncovered asset keeps the legacy selection + * (first non-`models` tag, verbatim, hierarchical paths intact). Outside the + * mode this is exactly the legacy selection. + */ +export function getPrimaryCategoryTag( + asset: AssetItem, + modelTypeMode: boolean +): string | undefined { + if (modelTypeMode) { + const [modelType] = getModelTypeTagValues(asset) + if (modelType) return modelType + return asset.tags.find( + (tag) => tag !== MODELS_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX) + ) + } + return asset.tags.find((tag) => tag !== MODELS_TAG) +} + /** Number of `parent/child` segments in a tag, used to pick the most specific. */ function pathDepth(tag: string): number { return tag.split('/').length From d43ecf8102e60f80ae721e3581093443b7d5b790 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 12 Jul 2026 23:01:25 +1200 Subject: [PATCH 13/22] fix(assets): represent every category of a shared multi-type asset A shared-root asset tagged with several model_type values groups under each of them, but its badge and a node-typed picker's title keyed off only the first value, so viewing it under its second category showed the first category's label. Cards now badge every authoritative model_type value, and a node-typed picker titles off the requested node's category instead of guessing from the first asset. --- .../assets/components/AssetBrowserModal.vue | 8 +++ .../assets/composables/useAssetBrowser.ts | 5 +- .../assets/utils/assetMetadataUtils.test.ts | 53 ++++++++++++------- .../assets/utils/assetMetadataUtils.ts | 29 +++++----- 4 files changed, 59 insertions(+), 36 deletions(-) diff --git a/src/platform/assets/components/AssetBrowserModal.vue b/src/platform/assets/components/AssetBrowserModal.vue index 9bc9c615b94..0e841a03559 100644 --- a/src/platform/assets/components/AssetBrowserModal.vue +++ b/src/platform/assets/components/AssetBrowserModal.vue @@ -195,6 +195,14 @@ const isRightPanelOpen = ref(false) const primaryCategoryTag = computed(() => { const modelTypeMode = flags.supportsModelTypeTags + // A node-typed picker is FOR a category; title off that category rather + // than guessing from the first asset, whose first model_type value may be + // a different category it shares a root with. + if (modelTypeMode && props.nodeType) { + const mapped = modelToNodeStore.getCategoryForNodeType(props.nodeType) + if (mapped) return mapped + } + const assets = fetchedAssets.value ?? [] // Covered assets title off the model_type value they group under (so title // and grouping cannot diverge); uncovered assets keep the legacy verbatim diff --git a/src/platform/assets/composables/useAssetBrowser.ts b/src/platform/assets/composables/useAssetBrowser.ts index eac2c13a517..f0e5918e7ed 100644 --- a/src/platform/assets/composables/useAssetBrowser.ts +++ b/src/platform/assets/composables/useAssetBrowser.ts @@ -21,7 +21,7 @@ import { getAssetBaseModels, getAssetCategories, getAssetFilename, - getAssetTypeBadge + getAssetTypeBadges } from '@/platform/assets/utils/assetMetadataUtils' import { MODELS_TAG } from '@/platform/assets/services/assetService' import { sortAssets } from '@/platform/assets/utils/assetSortUtils' @@ -57,8 +57,7 @@ function buildDisplayItem( ): AssetDisplayItem { const badges: AssetBadge[] = [] - const typeBadge = getAssetTypeBadge(asset, modelTypeMode) - if (typeBadge) { + for (const typeBadge of getAssetTypeBadges(asset, modelTypeMode)) { badges.push({ label: typeBadge, type: 'type' }) } diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index e9b6b486305..0d5bd647b4a 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -22,7 +22,7 @@ import { getPrimaryCategoryTag, getAssetStoredFilename, getAssetTriggerPhrases, - getAssetTypeBadge, + getAssetTypeBadges, getAssetUserDescription, getSourceName, resolveDisplayImageDimensions, @@ -750,7 +750,7 @@ describe('getAssetNodeCategoryCandidates', () => { }) }) -describe('getAssetTypeBadge', () => { +describe('getAssetTypeBadges', () => { const asset = (tags: string[]): AssetItem => ({ id: 'a', name: 'model.safetensors', @@ -759,43 +759,58 @@ describe('getAssetTypeBadge', () => { it('strips the model_type: prefix in model_type mode (no raw leak)', () => { expect( - getAssetTypeBadge( + getAssetTypeBadges( asset(['models', 'model_type:checkpoints', 'sdxl']), true ) - ).toBe('checkpoints') + ).toEqual(['checkpoints']) }) it('badges the model_type value even when a bare tag comes first, matching the grouping', () => { expect( - getAssetTypeBadge(asset(['models', 'foo', 'model_type:bar']), true) - ).toBe('bar') + getAssetTypeBadges(asset(['models', 'foo', 'model_type:bar']), true) + ).toEqual(['bar']) + }) + + it('badges every category a shared multi-type asset groups under', () => { + expect( + getAssetTypeBadges( + asset([ + 'models', + 'model_type:checkpoints', + 'model_type:diffusion_models' + ]), + true + ) + ).toEqual(['checkpoints', 'diffusion_models']) }) it('falls back to the bare tag for an uncovered asset in model_type mode', () => { - expect(getAssetTypeBadge(asset(['models', 'sdxl']), true)).toBe('sdxl') + expect(getAssetTypeBadges(asset(['models', 'sdxl']), true)).toEqual([ + 'sdxl' + ]) }) - it('returns undefined rather than a blank badge for a malformed empty model_type: tag', () => { - expect( - getAssetTypeBadge(asset(['models', 'model_type:']), true) - ).toBeUndefined() + it('returns no badge rather than a blank one for a malformed empty model_type: tag', () => { + expect(getAssetTypeBadges(asset(['models', 'model_type:']), true)).toEqual( + [] + ) }) it('leaks the literal model_type: tag when mode is off', () => { expect( - getAssetTypeBadge(asset(['models', 'model_type:checkpoints']), false) - ).toBe('model_type:checkpoints') + getAssetTypeBadges(asset(['models', 'model_type:checkpoints']), false) + ).toEqual(['model_type:checkpoints']) }) it('shows the segment after the first slash for a bare hierarchical tag', () => { - expect(getAssetTypeBadge(asset(['models', 'checkpoint/xl']), false)).toBe( - 'xl' - ) + expect( + getAssetTypeBadges(asset(['models', 'checkpoint/xl']), false) + ).toEqual(['xl']) }) - it('returns undefined when only the models tag is present', () => { - expect(getAssetTypeBadge(asset(['models']), true)).toBeUndefined() + it('returns no badges when only the models tag is present', () => { + expect(getAssetTypeBadges(asset(['models']), true)).toEqual([]) }) }) @@ -825,7 +840,7 @@ describe('reserved tag mirrors', () => { true ) ).toEqual(['x']) - expect(getAssetTypeBadge(asset([MODELS_TAG, 'x']), false)).toBe('x') + expect(getAssetTypeBadges(asset([MODELS_TAG, 'x']), false)).toEqual(['x']) expect(getAssetModelType(asset([MODELS_TAG]))).toBeNull() }) }) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 43da82294bc..611e40eb249 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -237,31 +237,32 @@ export function stripModelTypePrefix(tag: string): string { } /** - * Resolves the short label shown on an asset card's type badge. + * Resolves the labels shown as an asset card's type badges. * - * In `modelTypeMode` the badge is the asset's first `model_type:*` value — - * the same key the asset groups under (`getAssetCategories`), so badge and - * grouping cannot diverge for covered assets. Uncovered assets (and legacy - * mode) keep the original selection: first non-`models` tag, with bare - * hierarchical tags showing the segment after the first `/`. + * In `modelTypeMode` a covered asset badges every `model_type:*` value — the + * same keys it groups under (`getAssetCategories`) — so a shared-root asset + * tagged with several categories carries each of them; whichever category + * view the card appears in is represented on the card. Uncovered assets (and + * legacy mode) keep the original single selection: first non-`models` tag, + * with bare hierarchical tags showing the segment after the first `/`. */ -export function getAssetTypeBadge( +export function getAssetTypeBadges( asset: AssetItem, modelTypeMode: boolean -): string | undefined { +): string[] { if (modelTypeMode) { - const [modelType] = getModelTypeTagValues(asset) - if (modelType) return modelType + const modelTypes = getModelTypeTagValues(asset) + if (modelTypes.length > 0) return modelTypes } const typeTag = asset.tags.find( (tag) => tag !== MODELS_TAG && !(modelTypeMode && tag.startsWith(MODEL_TYPE_TAG_PREFIX)) ) - if (!typeTag) return undefined - return typeTag.includes('/') - ? typeTag.slice(typeTag.indexOf('/') + 1) - : typeTag + if (!typeTag) return [] + return [ + typeTag.includes('/') ? typeTag.slice(typeTag.indexOf('/') + 1) : typeTag + ] } /** From 74e4e3843e073b22f5949d1993d935cd345ad893 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Tue, 21 Jul 2026 09:54:53 +1200 Subject: [PATCH 14/22] fix(assets): dedupe category candidates and share pagination tolerance An asset tagged with both `model_type:LLM` and a bare `LLM` yielded the same category twice in the candidate list; deduplicate the tier-1 values so a provider is only ever tried once per distinct category. Flat output pagination stopped on the first all-duplicate page, so a pagination window shifted by concurrent writes could hide later unseen assets. Reuse the model-category walk's no-progress tolerance for both walks instead of duplicating the counter, letting a bounded run of all-duplicate pages be traversed while still guaranteeing termination. --- src/platform/assets/utils/assetMetadataUtils.test.ts | 9 +++++++++ src/platform/assets/utils/assetMetadataUtils.ts | 4 +++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index 0d5bd647b4a..ec0e1998f1b 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -734,6 +734,15 @@ describe('getAssetNodeCategoryCandidates', () => { ).toEqual(['chatterbox/chatterbox_vc']) }) + it('does not repeat a bare tag that duplicates its model_type value', () => { + expect( + getAssetNodeCategoryCandidates( + asset(['models', 'model_type:LLM', 'LLM']), + true + ) + ).toEqual(['LLM']) + }) + it('returns no candidates when only reserved tags are present', () => { expect( getAssetNodeCategoryCandidates(asset(['models', 'missing']), true) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index 611e40eb249..d5efca1a214 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -311,7 +311,9 @@ export function getAssetNodeCategoryCandidates( modelTypes.some((type) => tag === type || tag.startsWith(`${type}/`)) return [ - ...[...modelTypes, ...bareTags.filter(isRelated)].sort(byDepthDesc), + ...[...new Set([...modelTypes, ...bareTags.filter(isRelated)])].sort( + byDepthDesc + ), ...bareTags.filter((tag) => !isRelated(tag)).sort(byDepthDesc) ] } From 8c3b94672e53e1736d7d71efbeadff21b1927149 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Fri, 24 Jul 2026 09:18:25 +1200 Subject: [PATCH 15/22] test(assets): align cache tests with cursor pagination --- src/stores/assetsStore.test.ts | 43 ++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/stores/assetsStore.test.ts b/src/stores/assetsStore.test.ts index ba443415e17..200b18e9281 100644 --- a/src/stores/assetsStore.test.ts +++ b/src/stores/assetsStore.test.ts @@ -987,7 +987,6 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { 'p3' ]) }) - }) describe('refresh error surfacing', () => { @@ -995,13 +994,13 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { const store = useAssetsStore() const nodeType = 'CheckpointLoaderSimple' - vi.mocked(assetService.getAssetsForNodeType).mockResolvedValueOnce([ - createMockAsset('existing') - ]) + vi.mocked(assetService.getAssetsPageForNodeType).mockResolvedValueOnce( + makePage([createMockAsset('existing')]) + ) await store.updateModelsForNodeType(nodeType) expect(store.getError(nodeType)).toBeUndefined() - vi.mocked(assetService.getAssetsForNodeType).mockRejectedValueOnce( + vi.mocked(assetService.getAssetsPageForNodeType).mockRejectedValueOnce( new Error('backend down') ) await store.updateModelsForNodeType(nodeType) @@ -1067,19 +1066,19 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { const store = useAssetsStore() const nodeType = 'CheckpointLoaderSimple' - let resolveFirst!: (assets: AssetItem[]) => void - const firstFetch = new Promise((resolve) => { + let resolveFirst!: (response: AssetResponse) => void + const firstFetch = new Promise((resolve) => { resolveFirst = resolve }) - vi.mocked(assetService.getAssetsForNodeType) + vi.mocked(assetService.getAssetsPageForNodeType) .mockReturnValueOnce(firstFetch) - .mockReturnValue(new Promise(() => {})) + .mockReturnValue(new Promise(() => {})) const staleRequest = store.updateModelsForNodeType(nodeType) store.invalidateCategory('checkpoints') void store.updateModelsForNodeType(nodeType) - resolveFirst([createMockAsset('stale')]) + resolveFirst(makePage([createMockAsset('stale')])) await staleRequest // The stale request's teardown must not evict the newer request's @@ -1087,7 +1086,7 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { // a duplicate walk. void store.updateModelsForNodeType(nodeType) expect( - vi.mocked(assetService.getAssetsForNodeType) + vi.mocked(assetService.getAssetsPageForNodeType) ).toHaveBeenCalledTimes(2) }) }) @@ -1934,18 +1933,22 @@ describe('assetsStore - Model Assets Cache (non-cloud)', () => { it('caches model assets fetched by tag on non-cloud builds', async () => { const store = useAssetsStore() - vi.mocked(assetService.getAssetsByTag).mockResolvedValue([ - { - id: 'm1', - name: 'sd_xl_base_1.0.safetensors', - tags: ['checkpoints', 'models'] - }, - { id: 'm2', name: 'lora.safetensors', tags: ['loras', 'models'] } - ]) + vi.mocked(assetService.getAssetsPageByTag).mockResolvedValue({ + assets: [ + { + id: 'm1', + name: 'sd_xl_base_1.0.safetensors', + tags: ['checkpoints', 'models'] + }, + { id: 'm2', name: 'lora.safetensors', tags: ['loras', 'models'] } + ], + total: 2, + has_more: false + }) await store.updateModelsForTag('models') - expect(assetService.getAssetsByTag).toHaveBeenCalledWith( + expect(assetService.getAssetsPageByTag).toHaveBeenCalledWith( 'models', true, expect.anything() From b1b7b78973c70b400377968b7a6ef1be9e30ef72 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Fri, 19 Jun 2026 11:29:28 +1200 Subject: [PATCH 16/22] feat(assets): write model_type: tag from discovery Prefix the discovery folder_name with model_type: on model import and on model-type edits, gated on the supports_model_type_tags backend capability. Default off writes the legacy bare directory-path tag unchanged, so this is a no-op until the backend declares the cutover; the flag is the same authoritative signal FE-1076 grouping reads. The FE writes only the single selected folder_name's model_type: form; the backend keeps the bare directory-path twin in sync (and forward-expands shared paths), so the edit path manages just the model_type: tags and the resolver read path is untouched. Mirrors the read side: an uncovered asset with no model_type: tag still routes by its bare tag. --- .../components/modelInfo/ModelInfoPanel.vue | 23 +++- .../composables/useUploadModelWizard.test.ts | 44 +++++++- .../composables/useUploadModelWizard.ts | 13 ++- .../assets/utils/assetMetadataUtils.test.ts | 106 +++++++++++++++++- .../assets/utils/assetMetadataUtils.ts | 61 +++++++++- 5 files changed, 236 insertions(+), 11 deletions(-) diff --git a/src/platform/assets/components/modelInfo/ModelInfoPanel.vue b/src/platform/assets/components/modelInfo/ModelInfoPanel.vue index 5a3b668b7f0..88865b1f8a7 100644 --- a/src/platform/assets/components/modelInfo/ModelInfoPanel.vue +++ b/src/platform/assets/components/modelInfo/ModelInfoPanel.vue @@ -215,6 +215,7 @@ import { useI18n } from 'vue-i18n' import EditableText from '@/components/common/EditableText.vue' import { useCopyToClipboard } from '@/composables/useCopyToClipboard' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import PropertiesAccordionItem from '@/components/rightSidePanel/layout/PropertiesAccordionItem.vue' import Button from '@/components/ui/button/Button.vue' import Select from '@/components/ui/select/Select.vue' @@ -231,15 +232,16 @@ import type { AssetDisplayItem } from '@/platform/assets/composables/useAssetBro import { useModelTypes } from '@/platform/assets/composables/useModelTypes' import type { AssetUserMetadata } from '@/platform/assets/schemas/assetSchema' import { + buildModelTypeTagUpdate, getAssetAdditionalTags, getAssetBaseModels, getAssetDescription, getAssetDisplayName, getAssetFilename, - getAssetModelType, getAssetSourceUrl, getAssetTriggerPhrases, getAssetUserDescription, + getEditableModelType, getSourceName } from '@/platform/assets/utils/assetMetadataUtils' import { useAssetsStore } from '@/stores/assetsStore' @@ -265,6 +267,7 @@ const { asset, cacheKey, selectContentStyle } = defineProps<{ }>() const assetsStore = useAssetsStore() +const { flags } = useFeatureFlags() const { modelTypes } = useModelTypes() const pendingUpdates = ref({}) @@ -319,11 +322,16 @@ function handleDisplayNameEdit(newName: string) { const debouncedSaveModelType = useDebounceFn((newModelType: string) => { if (isImmutable.value) return - const currentModelType = getAssetModelType(asset) + const currentModelType = getEditableModelType( + asset, + flags.supportsModelTypeTags + ) if (currentModelType === newModelType) return - const newTags = asset.tags - .filter((tag) => tag !== currentModelType) - .concat(newModelType) + const newTags = buildModelTypeTagUpdate( + asset, + newModelType, + flags.supportsModelTypeTags + ) assetsStore.updateAssetTags(asset, newTags, cacheKey) }, 500) @@ -345,7 +353,10 @@ const userDescription = computed({ }) const selectedModelType = computed({ - get: () => pendingModelType.value ?? getAssetModelType(asset) ?? undefined, + get: () => + pendingModelType.value ?? + getEditableModelType(asset, flags.supportsModelTypeTags) ?? + undefined, set: (value: string | undefined) => { if (!value) return pendingModelType.value = value diff --git a/src/platform/assets/composables/useUploadModelWizard.test.ts b/src/platform/assets/composables/useUploadModelWizard.test.ts index 9cf769e4a5a..c776728b6d2 100644 --- a/src/platform/assets/composables/useUploadModelWizard.test.ts +++ b/src/platform/assets/composables/useUploadModelWizard.test.ts @@ -38,7 +38,10 @@ vi.mock('@/scripts/api', () => ({ api: { fetchApi: vi.fn(), addEventListener: vi.fn(), - apiURL: vi.fn((path: string) => path) + apiURL: vi.fn((path: string) => path), + getServerFeature: vi.fn( + (_name: string, defaultValue?: unknown) => defaultValue + ) } })) @@ -279,6 +282,45 @@ describe('useUploadModelWizard', () => { expect(result?.modelType).toBe('checkpoints') }) + it('writes the namespaced model_type: tag when the backend supports it', async () => { + const { assetService } = + await import('@/platform/assets/services/assetService') + const { api } = await import('@/scripts/api') + vi.mocked(assetService.uploadAssetAsync).mockResolvedValue({ + type: 'sync', + asset: { + id: 'asset-1', + name: 'model.safetensors', + tags: ['models', 'model_type:checkpoints'] + } + }) + vi.mocked(api.getServerFeature).mockImplementation((name, defaultValue) => + name === 'supports_model_type_tags' ? true : defaultValue + ) + + try { + const wizard = setupUploadModelWizard(modelTypes, { + requiredModelType: 'checkpoints' + }) + wizard.wizardData.value.url = 'https://civitai.com/models/12345' + + await wizard.uploadModel() + + expect(assetService.uploadAssetAsync).toHaveBeenCalledWith( + expect.objectContaining({ + tags: ['models', 'model_type:checkpoints'], + user_metadata: expect.objectContaining({ + model_type: 'checkpoints' + }) + }) + ) + } finally { + vi.mocked(api.getServerFeature).mockImplementation( + (_name, defaultValue) => defaultValue + ) + } + }) + it('returns the synced asset filename for sync imports', async () => { const { assetService } = await import('@/platform/assets/services/assetService') diff --git a/src/platform/assets/composables/useUploadModelWizard.ts b/src/platform/assets/composables/useUploadModelWizard.ts index f00827752bb..91f73e5de2d 100644 --- a/src/platform/assets/composables/useUploadModelWizard.ts +++ b/src/platform/assets/composables/useUploadModelWizard.ts @@ -2,6 +2,7 @@ import type { Ref } from 'vue' import { computed, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' +import { useFeatureFlags } from '@/composables/useFeatureFlags' import { st } from '@/i18n' import { civitaiImportSource } from '@/platform/assets/importSources/civitaiImportSource' import { huggingfaceImportSource } from '@/platform/assets/importSources/huggingfaceImportSource' @@ -11,7 +12,10 @@ import type { } from '@/platform/assets/schemas/assetSchema' import { assetService } from '@/platform/assets/services/assetService' import type { ImportSource } from '@/platform/assets/types/importSource' -import { getAssetFilename } from '@/platform/assets/utils/assetMetadataUtils' +import { + getAssetFilename, + toModelTypeTag +} from '@/platform/assets/utils/assetMetadataUtils' import { validateSourceUrl } from '@/platform/assets/utils/importSourceUtil' import { useAssetDownloadStore } from '@/stores/assetDownloadStore' import { useAssetsStore } from '@/stores/assetsStore' @@ -68,6 +72,7 @@ export function useUploadModelWizard( options: UploadModelWizardOptions = {} ) { const { t } = useI18n() + const { flags } = useFeatureFlags() const assetsStore = useAssetsStore() const assetDownloadStore = useAssetDownloadStore() const modelToNodeStore = useModelToNodeStore() @@ -317,7 +322,11 @@ export function useUploadModelWizard( try { const modelType = resolvedModelType.value - const tags = modelType ? ['models', modelType] : ['models'] + const subtypeTag = + modelType && flags.supportsModelTypeTags + ? toModelTypeTag(modelType) + : modelType + const tags = subtypeTag ? [MODEL_ROOT_TAG, subtypeTag] : [MODEL_ROOT_TAG] const filename = wizardData.value.metadata?.filename || wizardData.value.metadata?.name || diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index ec0e1998f1b..c4039a32285 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -6,6 +6,7 @@ import { MODELS_TAG } from '@/platform/assets/services/assetService' import { + buildModelTypeTagUpdate, getAssetAdditionalTags, getAssetBaseModel, getAssetBaseModels, @@ -24,9 +25,11 @@ import { getAssetTriggerPhrases, getAssetTypeBadges, getAssetUserDescription, + getEditableModelType, getSourceName, resolveDisplayImageDimensions, - stripModelTypePrefix + stripModelTypePrefix, + toModelTypeTag } from '@/platform/assets/utils/assetMetadataUtils' const { isCloudRef } = vi.hoisted(() => ({ @@ -853,3 +856,104 @@ describe('reserved tag mirrors', () => { expect(getAssetModelType(asset([MODELS_TAG]))).toBeNull() }) }) + +describe('toModelTypeTag', () => { + it('prefixes a folder_name with the model_type namespace', () => { + expect(toModelTypeTag('checkpoints')).toBe('model_type:checkpoints') + expect(toModelTypeTag('ultralytics_bbox')).toBe( + 'model_type:ultralytics_bbox' + ) + }) +}) + +describe('getEditableModelType', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('returns the stripped model_type value in model_type mode', () => { + expect( + getEditableModelType( + asset(['models', 'checkpoints', 'model_type:checkpoints']), + true + ) + ).toBe('checkpoints') + }) + + it('falls back to the bare tag for an uncovered asset in model_type mode', () => { + expect(getEditableModelType(asset(['models', 'sam2']), true)).toBe('sam2') + }) + + it('uses the legacy first-non-models tag when mode is off (default)', () => { + expect(getEditableModelType(asset(['models', 'checkpoints', 'sdxl']))).toBe( + 'checkpoints' + ) + }) + + it('returns null when only the models tag is present', () => { + expect(getEditableModelType(asset(['models']), true)).toBeNull() + }) +}) + +describe('buildModelTypeTagUpdate', () => { + const asset = (tags: string[]): AssetItem => ({ + id: 'a', + name: 'model.safetensors', + tags + }) + + it('swaps the bare subtype tag when mode is off (default)', () => { + expect( + buildModelTypeTagUpdate(asset(['models', 'checkpoints']), 'loras') + ).toEqual(['models', 'loras']) + }) + + it('preserves user labels and swaps only the subtype tag when mode is off', () => { + expect( + buildModelTypeTagUpdate(asset(['models', 'checkpoints', 'sdxl']), 'loras') + ).toEqual(['models', 'sdxl', 'loras']) + }) + + it('writes only the model_type form for a covered asset, leaving the bare twin for the backend', () => { + expect( + buildModelTypeTagUpdate( + asset(['models', 'checkpoints', 'model_type:checkpoints']), + 'loras', + true + ) + ).toEqual(['models', 'checkpoints', 'model_type:loras']) + }) + + it('replaces every existing model_type form for a shared-path dual-tagged asset', () => { + expect( + buildModelTypeTagUpdate( + asset([ + 'models', + 'diffusion_models', + 'model_type:diffusion_models', + 'model_type:unet_gguf' + ]), + 'loras', + true + ) + ).toEqual(['models', 'diffusion_models', 'model_type:loras']) + }) + + it('drops the bare current type for an uncovered asset in model_type mode', () => { + expect( + buildModelTypeTagUpdate(asset(['models', 'sam2']), 'loras', true) + ).toEqual(['models', 'model_type:loras']) + }) + + it('keeps user labels untouched in model_type mode', () => { + expect( + buildModelTypeTagUpdate( + asset(['models', 'checkpoints', 'model_type:checkpoints', 'sdxl']), + 'loras', + true + ) + ).toEqual(['models', 'checkpoints', 'sdxl', 'model_type:loras']) + }) +}) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index d5efca1a214..ac8ff81fb6f 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -145,7 +145,7 @@ export function getSourceName(url: string): string { return 'Source' } -const MODEL_TYPE_TAG_PREFIX = 'model_type:' +export const MODEL_TYPE_TAG_PREFIX = 'model_type:' /** * Extracts the model type from asset tags as a bare (non-namespaced) value. @@ -162,6 +162,15 @@ export function getAssetModelType(asset: AssetItem): string | null { return typeTag ?? null } +/** + * Builds the namespaced subtype tag the backend stores in `model_type:` mode. + * The argument is a discovery folder_name (e.g. `checkpoints`, + * `ultralytics_bbox`); the backend keeps the bare directory-path twin in sync. + */ +export function toModelTypeTag(folderName: string): string { + return `${MODEL_TYPE_TAG_PREFIX}${folderName}` +} + /** Strips the `model_type:` prefix off each namespaced tag, dropping non-`model_type:` tags. */ function getModelTypeTagValues(asset: AssetItem): string[] { return asset.tags @@ -170,6 +179,56 @@ function getModelTypeTagValues(asset: AssetItem): string[] { .filter((tag) => tag.length > 0) } +/** + * Resolves the folder_name shown as the asset's current model type in the edit + * dropdown. In `modelTypeMode` the stripped `model_type:` value is authoritative + * (covered assets); an uncovered asset with no `model_type:` tag falls back to + * its bare subtype tag, mirroring the read-side grouping. Outside the mode this + * is the legacy first-non-`models` tag. + */ +export function getEditableModelType( + asset: AssetItem, + modelTypeMode = false +): string | null { + if (modelTypeMode) { + const [modelType] = getModelTypeTagValues(asset) + if (modelType) return modelType + } + return getAssetModelType(asset) +} + +/** + * Computes the tag set for re-typing a model asset to `newFolderName`. In + * `modelTypeMode` only the `model_type:` form is written — the backend keeps the + * bare directory-path twin in sync, so existing `model_type:` tags are dropped + * (covered assets) or the bare current type is dropped (uncovered assets) and + * the new `model_type:` is added. Outside the mode it swaps the + * legacy bare subtype tag, preserving the pre-namespace behavior. + */ +export function buildModelTypeTagUpdate( + asset: AssetItem, + newFolderName: string, + modelTypeMode = false +): string[] { + if (!modelTypeMode) { + const currentType = getAssetModelType(asset) + return asset.tags.filter((tag) => tag !== currentType).concat(newFolderName) + } + + const modelTypeTags = asset.tags.filter((tag) => + tag.startsWith(MODEL_TYPE_TAG_PREFIX) + ) + const currentBareType = getAssetModelType(asset) + const tagsToRemove = + modelTypeTags.length > 0 + ? new Set(modelTypeTags) + : new Set(currentBareType ? [currentBareType] : []) + + return asset.tags + .filter((tag) => !tagsToRemove.has(tag)) + .concat(toModelTypeTag(newFolderName)) +} + /** Legacy grouping: each non-`models` tag's top-level path segment. */ function getBareTagCategories(asset: AssetItem): string[] { return asset.tags From 0f71ca4d489ca6563646c724d684f68e7b8de45d Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Fri, 19 Jun 2026 15:37:44 +1200 Subject: [PATCH 17/22] test(assets): pin import write keeps user_metadata.model_type bare Assert the import-by-URL path namespaces only the tag (model_type:) while user_metadata.model_type stays the bare folder_name, since that value still feeds download tracking, category refresh, and the progress label. --- .../composables/useUploadModelWizard.test.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/platform/assets/composables/useUploadModelWizard.test.ts b/src/platform/assets/composables/useUploadModelWizard.test.ts index c776728b6d2..205df312839 100644 --- a/src/platform/assets/composables/useUploadModelWizard.test.ts +++ b/src/platform/assets/composables/useUploadModelWizard.test.ts @@ -282,7 +282,7 @@ describe('useUploadModelWizard', () => { expect(result?.modelType).toBe('checkpoints') }) - it('writes the namespaced model_type: tag when the backend supports it', async () => { + it('namespaces the tag but keeps user_metadata.model_type bare when the backend supports it', async () => { const { assetService } = await import('@/platform/assets/services/assetService') const { api } = await import('@/scripts/api') @@ -306,14 +306,10 @@ describe('useUploadModelWizard', () => { await wizard.uploadModel() - expect(assetService.uploadAssetAsync).toHaveBeenCalledWith( - expect.objectContaining({ - tags: ['models', 'model_type:checkpoints'], - user_metadata: expect.objectContaining({ - model_type: 'checkpoints' - }) - }) - ) + const uploadArg = vi.mocked(assetService.uploadAssetAsync).mock + .calls[0][0] + expect(uploadArg.tags).toEqual(['models', 'model_type:checkpoints']) + expect(uploadArg.user_metadata?.model_type).toBe('checkpoints') } finally { vi.mocked(api.getServerFeature).mockImplementation( (_name, defaultValue) => defaultValue From c848833fb8fd2820231fd55f07acb9643f7b49ac Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Wed, 24 Jun 2026 11:33:28 +1200 Subject: [PATCH 18/22] fix(assets): recognize model_type: prefix in import type-mismatch guard The required-type guard and imported-type label compared the bare folder_name against raw asset tags, so a namespaced model_type: tag was treated as a type mismatch (and leaked the raw prefix into the mismatch label). Strip the model_type: prefix before comparing/labelling so a namespaced tag satisfies the required type. Not reachable in production (the dual-write keeps the bare twin), but hardens the import path against a namespaced-only asset. --- .../composables/useUploadModelWizard.test.ts | 61 +++++++++++++++++++ .../composables/useUploadModelWizard.ts | 14 +++-- 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/src/platform/assets/composables/useUploadModelWizard.test.ts b/src/platform/assets/composables/useUploadModelWizard.test.ts index 205df312839..da339706803 100644 --- a/src/platform/assets/composables/useUploadModelWizard.test.ts +++ b/src/platform/assets/composables/useUploadModelWizard.test.ts @@ -310,6 +310,8 @@ describe('useUploadModelWizard', () => { .calls[0][0] expect(uploadArg.tags).toEqual(['models', 'model_type:checkpoints']) expect(uploadArg.user_metadata?.model_type).toBe('checkpoints') + // The namespaced returned tag must not trip the required-type guard. + expect(wizard.uploadTypeMismatch.value).toBeNull() } finally { vi.mocked(api.getServerFeature).mockImplementation( (_name, defaultValue) => defaultValue @@ -385,6 +387,65 @@ describe('useUploadModelWizard', () => { }) }) + it('treats a namespaced model_type: tag as satisfying the required type', async () => { + const { assetService } = + await import('@/platform/assets/services/assetService') + vi.mocked(assetService.uploadAssetAsync).mockResolvedValue({ + type: 'sync', + asset: { + id: 'asset-1', + name: 'model.safetensors', + tags: ['models', 'model_type:checkpoints'] + } + }) + + const wizard = setupUploadModelWizard( + ref([ + { name: 'Checkpoint', value: 'checkpoints' }, + { name: 'LoRA', value: 'loras' } + ]), + { requiredModelType: 'checkpoints' } + ) + wizard.wizardData.value.url = 'https://civitai.com/models/12345' + + const result = await wizard.uploadModel() + + expect(result).not.toBeNull() + expect(wizard.uploadTypeMismatch.value).toBeNull() + }) + + it('strips the model_type: prefix from the imported-type label on a real mismatch', async () => { + const { assetService } = + await import('@/platform/assets/services/assetService') + vi.mocked(assetService.uploadAssetAsync).mockResolvedValue({ + type: 'sync', + asset: { + id: 'asset-lora', + name: 'model.safetensors', + tags: ['models', 'model_type:loras'] + } + }) + + const wizard = setupUploadModelWizard( + ref([ + { name: 'Checkpoint', value: 'checkpoints' }, + { name: 'LoRA', value: 'loras' } + ]), + { requiredModelType: 'checkpoints' } + ) + wizard.wizardData.value.url = 'https://civitai.com/models/12345' + + const result = await wizard.uploadModel() + + expect(result).toBeNull() + expect(wizard.uploadTypeMismatch.value).toEqual({ + importedModelType: 'loras', + importedModelTypeLabel: 'LoRA', + requiredModelType: 'checkpoints', + requiredModelTypeLabel: 'Checkpoint' + }) + }) + it('does not block sync imports as mismatches without a required model type', async () => { const { assetService } = await import('@/platform/assets/services/assetService') diff --git a/src/platform/assets/composables/useUploadModelWizard.ts b/src/platform/assets/composables/useUploadModelWizard.ts index 91f73e5de2d..131bb88dd2e 100644 --- a/src/platform/assets/composables/useUploadModelWizard.ts +++ b/src/platform/assets/composables/useUploadModelWizard.ts @@ -14,6 +14,7 @@ import { assetService } from '@/platform/assets/services/assetService' import type { ImportSource } from '@/platform/assets/types/importSource' import { getAssetFilename, + stripModelTypePrefix, toModelTypeTag } from '@/platform/assets/utils/assetMetadataUtils' import { validateSourceUrl } from '@/platform/assets/utils/importSourceUtil' @@ -276,19 +277,22 @@ export function useUploadModelWizard( } function getImportedModelType(asset: AssetItem): string | undefined { - const knownType = asset.tags.find( - (tag) => - tag !== MODEL_ROOT_TAG && + const subtypeTags = asset.tags + .filter((tag) => tag !== MODEL_ROOT_TAG) + .map(stripModelTypePrefix) + return ( + subtypeTags.find((tag) => modelTypes.value.some((type) => type.value === tag) + ) ?? subtypeTags[0] ) - return knownType ?? asset.tags.find((tag) => tag !== MODEL_ROOT_TAG) } function blockMismatchedImportedModel( asset: AssetItem, requiredType: string ): boolean { - if (asset.tags.includes(requiredType)) return false + if (asset.tags.map(stripModelTypePrefix).includes(requiredType)) + return false const importedType = getImportedModelType(asset) uploadStatus.value = 'error' From 5101631f7c7c8e3f7fa1deafdc1d5a7dd75aaa01 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Sun, 12 Jul 2026 21:04:01 +1200 Subject: [PATCH 19/22] refactor(assets): require modelTypeMode on the write-path helpers Matches the read-path helpers: new call sites must choose the tag mode explicitly instead of silently inheriting legacy behavior. --- .../assets/utils/assetMetadataUtils.test.ts | 18 +++++++++++------- .../assets/utils/assetMetadataUtils.ts | 4 ++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index c4039a32285..0da4910608e 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -886,10 +886,10 @@ describe('getEditableModelType', () => { expect(getEditableModelType(asset(['models', 'sam2']), true)).toBe('sam2') }) - it('uses the legacy first-non-models tag when mode is off (default)', () => { - expect(getEditableModelType(asset(['models', 'checkpoints', 'sdxl']))).toBe( - 'checkpoints' - ) + it('uses the legacy first-non-models tag when mode is off', () => { + expect( + getEditableModelType(asset(['models', 'checkpoints', 'sdxl']), false) + ).toBe('checkpoints') }) it('returns null when only the models tag is present', () => { @@ -904,15 +904,19 @@ describe('buildModelTypeTagUpdate', () => { tags }) - it('swaps the bare subtype tag when mode is off (default)', () => { + it('swaps the bare subtype tag when mode is off', () => { expect( - buildModelTypeTagUpdate(asset(['models', 'checkpoints']), 'loras') + buildModelTypeTagUpdate(asset(['models', 'checkpoints']), 'loras', false) ).toEqual(['models', 'loras']) }) it('preserves user labels and swaps only the subtype tag when mode is off', () => { expect( - buildModelTypeTagUpdate(asset(['models', 'checkpoints', 'sdxl']), 'loras') + buildModelTypeTagUpdate( + asset(['models', 'checkpoints', 'sdxl']), + 'loras', + false + ) ).toEqual(['models', 'sdxl', 'loras']) }) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index ac8ff81fb6f..dba937f03b8 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -188,7 +188,7 @@ function getModelTypeTagValues(asset: AssetItem): string[] { */ export function getEditableModelType( asset: AssetItem, - modelTypeMode = false + modelTypeMode: boolean ): string | null { if (modelTypeMode) { const [modelType] = getModelTypeTagValues(asset) @@ -208,7 +208,7 @@ export function getEditableModelType( export function buildModelTypeTagUpdate( asset: AssetItem, newFolderName: string, - modelTypeMode = false + modelTypeMode: boolean ): string[] { if (!modelTypeMode) { const currentType = getAssetModelType(asset) From e0dfcd13f2be1dfe5b155b35f241e0b961649a84 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Tue, 21 Jul 2026 09:47:12 +1200 Subject: [PATCH 20/22] fix(assets): preserve sibling model_type memberships on re-type Re-typing a multi-type asset previously replaced its entire model_type: tag set, silently destroying the other type memberships. Replace only the primary membership (its model_type tag and stale bare twin), keeping siblings intact. Primary is the lexicographically-first model_type value so the choice is deterministic regardless of backend tag order, and the edit dropdown displays that same primary. Extract the selection into one shared helper and privatize the unused tag-prefix export. --- .../assets/utils/assetMetadataUtils.test.ts | 66 ++++++++++++++++--- .../assets/utils/assetMetadataUtils.ts | 51 ++++++++------ 2 files changed, 89 insertions(+), 28 deletions(-) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index 0da4910608e..fdd44425062 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -873,15 +873,41 @@ describe('getEditableModelType', () => { tags }) - it('returns the stripped model_type value in model_type mode', () => { + it('prefers the model_type value over a distinct bare tag in model_type mode', () => { expect( getEditableModelType( - asset(['models', 'checkpoints', 'model_type:checkpoints']), + asset(['models', 'checkpoints', 'model_type:loras']), + true + ) + ).toBe('loras') + }) + + it('returns the model_type value even when no bare twin is present', () => { + expect( + getEditableModelType(asset(['models', 'model_type:loras']), true) + ).toBe('loras') + }) + + it('ignores an empty model_type value and falls back to the bare tag', () => { + expect( + getEditableModelType( + asset(['models', 'checkpoints', 'model_type:']), true ) ).toBe('checkpoints') }) + it('resolves the same primary model_type regardless of tag array order', () => { + const forward = ['models', 'model_type:diffusion_models', 'model_type:unet'] + const reversed = [ + 'models', + 'model_type:unet', + 'model_type:diffusion_models' + ] + expect(getEditableModelType(asset(forward), true)).toBe('diffusion_models') + expect(getEditableModelType(asset(reversed), true)).toBe('diffusion_models') + }) + it('falls back to the bare tag for an uncovered asset in model_type mode', () => { expect(getEditableModelType(asset(['models', 'sam2']), true)).toBe('sam2') }) @@ -920,17 +946,17 @@ describe('buildModelTypeTagUpdate', () => { ).toEqual(['models', 'sdxl', 'loras']) }) - it('writes only the model_type form for a covered asset, leaving the bare twin for the backend', () => { + it('drops the primary model_type form and its stale bare twin for a covered asset', () => { expect( buildModelTypeTagUpdate( asset(['models', 'checkpoints', 'model_type:checkpoints']), 'loras', true ) - ).toEqual(['models', 'checkpoints', 'model_type:loras']) + ).toEqual(['models', 'model_type:loras']) }) - it('replaces every existing model_type form for a shared-path dual-tagged asset', () => { + it('replaces only the primary membership, preserving sibling model_type memberships', () => { expect( buildModelTypeTagUpdate( asset([ @@ -942,7 +968,31 @@ describe('buildModelTypeTagUpdate', () => { 'loras', true ) - ).toEqual(['models', 'diffusion_models', 'model_type:loras']) + ).toEqual(['models', 'model_type:unet_gguf', 'model_type:loras']) + }) + + it('replaces the deterministic primary regardless of model_type tag order', () => { + expect( + buildModelTypeTagUpdate( + asset([ + 'models', + 'model_type:unet_gguf', + 'model_type:diffusion_models' + ]), + 'loras', + true + ) + ).toEqual(['models', 'model_type:unet_gguf', 'model_type:loras']) + }) + + it('does not duplicate when re-typing to an existing sibling membership', () => { + expect( + buildModelTypeTagUpdate( + asset(['models', 'model_type:diffusion_models', 'model_type:loras']), + 'loras', + true + ) + ).toEqual(['models', 'model_type:loras']) }) it('drops the bare current type for an uncovered asset in model_type mode', () => { @@ -951,13 +1001,13 @@ describe('buildModelTypeTagUpdate', () => { ).toEqual(['models', 'model_type:loras']) }) - it('keeps user labels untouched in model_type mode', () => { + it('keeps user labels but drops the primary bare twin in model_type mode', () => { expect( buildModelTypeTagUpdate( asset(['models', 'checkpoints', 'model_type:checkpoints', 'sdxl']), 'loras', true ) - ).toEqual(['models', 'checkpoints', 'sdxl', 'model_type:loras']) + ).toEqual(['models', 'sdxl', 'model_type:loras']) }) }) diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index dba937f03b8..be934925c02 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -145,7 +145,7 @@ export function getSourceName(url: string): string { return 'Source' } -export const MODEL_TYPE_TAG_PREFIX = 'model_type:' +const MODEL_TYPE_TAG_PREFIX = 'model_type:' /** * Extracts the model type from asset tags as a bare (non-namespaced) value. @@ -179,9 +179,20 @@ function getModelTypeTagValues(asset: AssetItem): string[] { .filter((tag) => tag.length > 0) } +/** + * The asset's primary `model_type:` membership: the lexicographically-first of + * its stripped `model_type:` values, or `undefined` for an uncovered asset. + * Sorting makes the choice deterministic because the backend does not guarantee + * the order of an asset's `model_type:` tags. This is the single membership a + * re-type replaces and the value the edit dropdown / browser title reflect. + */ +function getPrimaryModelType(asset: AssetItem): string | undefined { + return getModelTypeTagValues(asset).toSorted()[0] +} + /** * Resolves the folder_name shown as the asset's current model type in the edit - * dropdown. In `modelTypeMode` the stripped `model_type:` value is authoritative + * dropdown. In `modelTypeMode` the primary `model_type:` value is authoritative * (covered assets); an uncovered asset with no `model_type:` tag falls back to * its bare subtype tag, mirroring the read-side grouping. Outside the mode this * is the legacy first-non-`models` tag. @@ -191,19 +202,21 @@ export function getEditableModelType( modelTypeMode: boolean ): string | null { if (modelTypeMode) { - const [modelType] = getModelTypeTagValues(asset) - if (modelType) return modelType + const primary = getPrimaryModelType(asset) + if (primary !== undefined) return primary } return getAssetModelType(asset) } /** * Computes the tag set for re-typing a model asset to `newFolderName`. In - * `modelTypeMode` only the `model_type:` form is written — the backend keeps the - * bare directory-path twin in sync, so existing `model_type:` tags are dropped - * (covered assets) or the bare current type is dropped (uncovered assets) and - * the new `model_type:` is added. Outside the mode it swaps the - * legacy bare subtype tag, preserving the pre-namespace behavior. + * `modelTypeMode` only the primary `model_type:` membership is replaced: a + * covered asset drops `model_type:` and its bare directory-path twin, + * leaving any sibling `model_type:` memberships of a multi-type asset intact; + * an uncovered asset drops its bare current type. The new + * `model_type:` is then added (deduped if it already exists as a + * sibling). Outside the mode it swaps the legacy bare subtype tag, preserving + * the pre-namespace behavior. */ export function buildModelTypeTagUpdate( asset: AssetItem, @@ -215,18 +228,16 @@ export function buildModelTypeTagUpdate( return asset.tags.filter((tag) => tag !== currentType).concat(newFolderName) } - const modelTypeTags = asset.tags.filter((tag) => - tag.startsWith(MODEL_TYPE_TAG_PREFIX) - ) + const primary = getPrimaryModelType(asset) const currentBareType = getAssetModelType(asset) const tagsToRemove = - modelTypeTags.length > 0 - ? new Set(modelTypeTags) + primary !== undefined + ? new Set([toModelTypeTag(primary), primary]) : new Set(currentBareType ? [currentBareType] : []) - return asset.tags - .filter((tag) => !tagsToRemove.has(tag)) - .concat(toModelTypeTag(newFolderName)) + const newTag = toModelTypeTag(newFolderName) + const retained = asset.tags.filter((tag) => !tagsToRemove.has(tag)) + return retained.includes(newTag) ? retained : retained.concat(newTag) } /** Legacy grouping: each non-`models` tag's top-level path segment. */ @@ -264,7 +275,7 @@ export function getAssetCategories( /** * Resolves the primary tag a browser surface titles itself after. In - * `modelTypeMode` a covered asset uses its first `model_type:*` value — the + * `modelTypeMode` a covered asset uses its primary `model_type:*` value — the * key it groups under — while an uncovered asset keeps the legacy selection * (first non-`models` tag, verbatim, hierarchical paths intact). Outside the * mode this is exactly the legacy selection. @@ -274,8 +285,8 @@ export function getPrimaryCategoryTag( modelTypeMode: boolean ): string | undefined { if (modelTypeMode) { - const [modelType] = getModelTypeTagValues(asset) - if (modelType) return modelType + const primary = getPrimaryModelType(asset) + if (primary !== undefined) return primary return asset.tags.find( (tag) => tag !== MODELS_TAG && !tag.startsWith(MODEL_TYPE_TAG_PREFIX) ) From 179e7a327bee34a8b906b821de03cbaa4d8be54f Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Tue, 21 Jul 2026 10:32:00 +1200 Subject: [PATCH 21/22] fix(assets): guard toModelTypeTag against double-prefixing --- src/platform/assets/utils/assetMetadataUtils.test.ts | 6 ++++++ src/platform/assets/utils/assetMetadataUtils.ts | 3 +++ 2 files changed, 9 insertions(+) diff --git a/src/platform/assets/utils/assetMetadataUtils.test.ts b/src/platform/assets/utils/assetMetadataUtils.test.ts index fdd44425062..ffbe05331aa 100644 --- a/src/platform/assets/utils/assetMetadataUtils.test.ts +++ b/src/platform/assets/utils/assetMetadataUtils.test.ts @@ -864,6 +864,12 @@ describe('toModelTypeTag', () => { 'model_type:ultralytics_bbox' ) }) + + it('returns an already-namespaced value unchanged instead of double-prefixing', () => { + expect(toModelTypeTag('model_type:checkpoints')).toBe( + 'model_type:checkpoints' + ) + }) }) describe('getEditableModelType', () => { diff --git a/src/platform/assets/utils/assetMetadataUtils.ts b/src/platform/assets/utils/assetMetadataUtils.ts index be934925c02..0c60db4fbcb 100644 --- a/src/platform/assets/utils/assetMetadataUtils.ts +++ b/src/platform/assets/utils/assetMetadataUtils.ts @@ -166,8 +166,11 @@ export function getAssetModelType(asset: AssetItem): string | null { * Builds the namespaced subtype tag the backend stores in `model_type:` mode. * The argument is a discovery folder_name (e.g. `checkpoints`, * `ultralytics_bbox`); the backend keeps the bare directory-path twin in sync. + * An already-namespaced input is returned unchanged rather than silently + * double-prefixed. */ export function toModelTypeTag(folderName: string): string { + if (folderName.startsWith(MODEL_TYPE_TAG_PREFIX)) return folderName return `${MODEL_TYPE_TAG_PREFIX}${folderName}` } From 93249d3dcfcb31c010d5101ce90bddb88c341909 Mon Sep 17 00:00:00 2001 From: Simon Pinfold Date: Tue, 28 Jul 2026 12:53:27 +1200 Subject: [PATCH 22/22] test(assets): restore getServerFeature mock in afterEach for order-independence --- .../composables/useUploadModelWizard.test.ts | 36 ++++++++----------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/platform/assets/composables/useUploadModelWizard.test.ts b/src/platform/assets/composables/useUploadModelWizard.test.ts index da339706803..d1129580e1e 100644 --- a/src/platform/assets/composables/useUploadModelWizard.test.ts +++ b/src/platform/assets/composables/useUploadModelWizard.test.ts @@ -7,6 +7,7 @@ import { createI18n } from 'vue-i18n' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { AsyncUploadResponse } from '@/platform/assets/schemas/assetSchema' +import { api } from '@/scripts/api' import { useUploadModelWizard } from './useUploadModelWizard' @@ -93,6 +94,7 @@ describe('useUploadModelWizard', () => { }) afterEach(() => { + vi.mocked(api.getServerFeature).mockReset() for (const app of mountedApps.splice(0)) { app.unmount() } @@ -138,7 +140,6 @@ describe('useUploadModelWizard', () => { status: 'completed' as const } const event = new CustomEvent('asset_download', { detail }) - const { api } = await import('@/scripts/api') const handler = vi .mocked(api.addEventListener) .mock.calls.find((c) => c[0] === 'asset_download')?.[1] as @@ -174,7 +175,6 @@ describe('useUploadModelWizard', () => { expect(wizard.uploadStatus.value).toBe('processing') // Simulate WebSocket: download fails - const { api } = await import('@/scripts/api') const handler = vi .mocked(api.addEventListener) .mock.calls.find((c) => c[0] === 'asset_download')?.[1] as @@ -285,7 +285,6 @@ describe('useUploadModelWizard', () => { it('namespaces the tag but keeps user_metadata.model_type bare when the backend supports it', async () => { const { assetService } = await import('@/platform/assets/services/assetService') - const { api } = await import('@/scripts/api') vi.mocked(assetService.uploadAssetAsync).mockResolvedValue({ type: 'sync', asset: { @@ -298,25 +297,18 @@ describe('useUploadModelWizard', () => { name === 'supports_model_type_tags' ? true : defaultValue ) - try { - const wizard = setupUploadModelWizard(modelTypes, { - requiredModelType: 'checkpoints' - }) - wizard.wizardData.value.url = 'https://civitai.com/models/12345' - - await wizard.uploadModel() - - const uploadArg = vi.mocked(assetService.uploadAssetAsync).mock - .calls[0][0] - expect(uploadArg.tags).toEqual(['models', 'model_type:checkpoints']) - expect(uploadArg.user_metadata?.model_type).toBe('checkpoints') - // The namespaced returned tag must not trip the required-type guard. - expect(wizard.uploadTypeMismatch.value).toBeNull() - } finally { - vi.mocked(api.getServerFeature).mockImplementation( - (_name, defaultValue) => defaultValue - ) - } + const wizard = setupUploadModelWizard(modelTypes, { + requiredModelType: 'checkpoints' + }) + wizard.wizardData.value.url = 'https://civitai.com/models/12345' + + await wizard.uploadModel() + + const uploadArg = vi.mocked(assetService.uploadAssetAsync).mock.calls[0][0] + expect(uploadArg.tags).toEqual(['models', 'model_type:checkpoints']) + expect(uploadArg.user_metadata?.model_type).toBe('checkpoints') + // The namespaced returned tag must not trip the required-type guard. + expect(wizard.uploadTypeMismatch.value).toBeNull() }) it('returns the synced asset filename for sync imports', async () => {