Compare commits

..

5 Commits

Author SHA1 Message Date
Will Miao
d3bf0a164b fix(gitignore): add .reasonix/ to ignore list 2026-06-23 07:06:15 +08:00
Will Miao
afb6ca1b8d refactor(settings): rename update_flag_strategy to version_grouping with migration 2026-06-22 16:59:32 +08:00
Will Miao
94f43426d7 feat(ui): show version count in group-by-model cards, add versions_count sort, no-reload VLM
- group_by_model dedup now counts versions per group and attaches
  version_count; respects update_flag_strategy (same_base) by
  sub-grouping on base_model
- Card footer shows clickable 'x versions' link instead of version
  name when grouped (hides HIGH/LOW badges); clicking triggers
  View Local Versions without page reload
- Added 'Local Versions' sort option (versions_count), auto-hidden
  when group_by_model is off
- Sort preference is saved/restored separately for normal and
  grouped modes
- VLM flow (triggerVlmView, clearCustomFilter) uses resetAndReload()
  via API instead of window.location.reload()
- Fixed cache mutation bug: version_count is now set on a shallow
  copy, not the cached dict, preventing stale version_count leaking
  into VLM responses
- i18n: all 9 locale files translated
2026-06-22 16:02:12 +08:00
Will Miao
2b361f4f5d feat(ui): add group-by-model toggle to global context menu
Adds a 'Group by Model' toggle entry to the right-click global context
menu for quick access, complementing the existing setting in
Settings → Layout Settings. The menu item shows a checkmark indicator
reflecting the current state and immediately reloads the view on toggle.

Also fixes he.json translation that was mojibake (garbled characters).

Includes:
- Context menu HTML item with check-indicator
- JS toggle logic via settingsManager
- i18n for all 10 locales
- Hebrew translation fix
2026-06-22 11:31:15 +08:00
Will Miao
7438072f8c feat(save-image): add %batch_num% support in batch loop 2026-06-22 09:11:38 +08:00
33 changed files with 458 additions and 80 deletions

1
.gitignore vendored
View File

@@ -19,6 +19,7 @@ model_cache/
.codex
.omo
reasonix.toml
.reasonix/
.codegraph/
# Vue widgets development cache (but keep build output)

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "Verwendungsanzahl"
},
"footer": {
"versionCount": "{count} Versionen",
"viewAllVersions": "Alle lokalen Versionen anzeigen"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "Ausgeschlossene Modelle verwalten"
},
"groupByModel": {
"label": "Nach Modell gruppieren"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "Zusätzliche Ordnerpfade",
"downloadPathTemplates": "Download-Pfad-Vorlagen",
"priorityTags": "Prioritäts-Tags",
"updateFlags": "Update-Markierungen",
"versionScope": "Update-Markierungen",
"exampleImages": "Beispielbilder",
"autoOrganize": "Auto-Organisierung",
"metadata": "Metadaten",
@@ -588,7 +595,7 @@
"download": "Herunterladen",
"restartRequired": "Neustart erforderlich"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "Strategie für Update-Markierungen",
"help": "Entscheide, ob Update-Badges nur dann erscheinen, wenn eine neue Version dasselbe Basismodell wie deine lokalen Dateien verwendet, oder sobald es irgendein neueres Release für dieses Modell gibt.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "Kleinste",
"usage": "Anzahl Nutzung",
"usageDesc": "Meiste",
"usageAsc": "Wenigste"
"usageAsc": "Wenigste",
"versionsCount": "Lokale Versionen",
"versionsCountDesc": "Meiste Versionen zuerst",
"versionsCountAsc": "Wenigste Versionen zuerst"
},
"refresh": {
"title": "Modelliste aktualisieren",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "Times used"
},
"footer": {
"versionCount": "{count} versions",
"viewAllVersions": "View all local versions"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "Manage Excluded Models"
},
"groupByModel": {
"label": "Group by Model"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "Extra Folder Paths",
"downloadPathTemplates": "Download Path Templates",
"priorityTags": "Priority Tags",
"updateFlags": "Update Flags",
"versionScope": "Version Scope",
"exampleImages": "Example Images",
"autoOrganize": "Auto-organize",
"metadata": "Metadata",
@@ -588,12 +595,12 @@
"download": "Download",
"restartRequired": "Requires restart"
},
"updateFlagStrategy": {
"label": "Update Flag Strategy",
"help": "Decide whether update badges should only appear when a new release shares the same base model as your local files or whenever any newer version exists for that model.",
"versionGrouping": {
"label": "Version Grouping",
"help": "Decide how versions are grouped for display: by base model or all together. Also controls update badge logic and the VLM version list filtering.",
"options": {
"sameBase": "Match updates by base model",
"any": "Flag any available update"
"sameBase": "Group by base model (same_base)",
"any": "Show all versions (any)"
}
},
"hideEarlyAccessUpdates": {
@@ -672,7 +679,10 @@
"sizeAsc": "Smallest",
"usage": "Use Count",
"usageDesc": "Most",
"usageAsc": "Least"
"usageAsc": "Least",
"versionsCount": "Local Versions",
"versionsCountDesc": "Most versions first",
"versionsCountAsc": "Fewest versions first"
},
"refresh": {
"title": "Refresh model list",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "Veces usado"
},
"footer": {
"versionCount": "{count} versiones",
"viewAllVersions": "Ver todas las versiones locales"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "Gestionar modelos excluidos"
},
"groupByModel": {
"label": "Agrupar por modelo"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "Rutas de carpetas adicionales",
"downloadPathTemplates": "Plantillas de rutas de descarga",
"priorityTags": "Etiquetas prioritarias",
"updateFlags": "Indicadores de actualización",
"versionScope": "Indicadores de actualización",
"exampleImages": "Imágenes de ejemplo",
"autoOrganize": "Organización automática",
"metadata": "Metadatos",
@@ -588,7 +595,7 @@
"download": "Descargar",
"restartRequired": "Requiere reinicio"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "Estrategia de indicadores de actualización",
"help": "Decide si las insignias de actualización deben mostrarse solo cuando una nueva versión comparte el mismo modelo base que tus archivos locales o siempre que exista cualquier versión más reciente de ese modelo.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "Menor",
"usage": "Número de usos",
"usageDesc": "Más",
"usageAsc": "Menos"
"usageAsc": "Menos",
"versionsCount": "Versiones locales",
"versionsCountDesc": "Más versiones primero",
"versionsCountAsc": "Menos versiones primero"
},
"refresh": {
"title": "Actualizar lista de modelos",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "Nombre d'utilisations"
},
"footer": {
"versionCount": "{count} versions",
"viewAllVersions": "Voir toutes les versions locales"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "Gérer les modèles exclus"
},
"groupByModel": {
"label": "Grouper par modèle"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "Chemins de dossiers supplémentaires",
"downloadPathTemplates": "Modèles de chemin de téléchargement",
"priorityTags": "Étiquettes prioritaires",
"updateFlags": "Indicateurs de mise à jour",
"versionScope": "Indicateurs de mise à jour",
"exampleImages": "Images d'exemple",
"autoOrganize": "Organisation automatique",
"metadata": "Métadonnées",
@@ -588,7 +595,7 @@
"download": "Télécharger",
"restartRequired": "Redémarrage requis"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "Stratégie des indicateurs de mise à jour",
"help": "Choisissez si les badges de mise à jour doivent apparaître uniquement lorsquune nouvelle version partage le même modèle de base que vos fichiers locaux, ou dès quil existe une version plus récente pour ce modèle.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "Plus petit",
"usage": "Nombre d'utilisations",
"usageDesc": "Plus",
"usageAsc": "Moins"
"usageAsc": "Moins",
"versionsCount": "Versions locales",
"versionsCountDesc": "Plus de versions d'abord",
"versionsCountAsc": "Moins de versions d'abord"
},
"refresh": {
"title": "Actualiser la liste des modèles",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "מספר שימושים"
},
"footer": {
"versionCount": "{count} גרסאות",
"viewAllVersions": "הצג את כל הגרסאות המקומיות"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "ניהול מודלים מוחרגים"
},
"groupByModel": {
"label": "קיבוץ לפי דגם"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "נתיבי תיקיות נוספים",
"downloadPathTemplates": "תבניות נתיב הורדה",
"priorityTags": "תגיות עדיפות",
"updateFlags": "תגי עדכון",
"versionScope": "תגי עדכון",
"exampleImages": "תמונות דוגמה",
"autoOrganize": "ארגון אוטומטי",
"metadata": "מטא-נתונים",
@@ -588,7 +595,7 @@
"download": "הורד",
"restartRequired": "דורש הפעלה מחדש"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "אסטרטגיית תגי עדכון",
"help": "בחרו אם תוויות העדכון יוצגו רק כאשר גרסה חדשה חולקת את אותו דגם בסיס כמו הקבצים המקומיים שלכם או בכל מקרה שבו קיימת גרסה חדשה עבור אותו דגם.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "הקטן ביותר",
"usage": "מספר שימושים",
"usageDesc": "הכי הרבה",
"usageAsc": "הכי פחות"
"usageAsc": "הכי פחות",
"versionsCount": "גרסאות מקומיות",
"versionsCountDesc": "הכי הרבה גרסאות ראשונות",
"versionsCountAsc": "הכי מעט גרסאות ראשונות"
},
"refresh": {
"title": "רענן רשימת מודלים",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "使用回数"
},
"footer": {
"versionCount": "{count} バージョン",
"viewAllVersions": "ローカルの全バージョンを表示"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "除外モデルを管理"
},
"groupByModel": {
"label": "モデルでグループ化"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "追加フォルダーパス",
"downloadPathTemplates": "ダウンロードパステンプレート",
"priorityTags": "優先タグ",
"updateFlags": "アップデートフラグ",
"versionScope": "アップデートフラグ",
"exampleImages": "例画像",
"autoOrganize": "自動整理",
"metadata": "メタデータ",
@@ -588,7 +595,7 @@
"download": "ダウンロード",
"restartRequired": "再起動が必要"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "アップデートフラグの表示戦略",
"help": "新リリースがローカルファイルと同じベースモデルを共有する場合にのみ更新バッジを表示するか、そのモデルに新しいバージョンがあれば常に表示するかを決めます。",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "小さい順",
"usage": "使用回数",
"usageDesc": "多い",
"usageAsc": "少ない"
"usageAsc": "少ない",
"versionsCount": "ローカルバージョン数",
"versionsCountDesc": "バージョン数の多い順",
"versionsCountAsc": "バージョン数の少ない順"
},
"refresh": {
"title": "モデルリストを更新",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "사용 횟수"
},
"footer": {
"versionCount": "{count}개 버전",
"viewAllVersions": "모든 로컬 버전 보기"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "제외된 모델 관리"
},
"groupByModel": {
"label": "모델별 그룹화"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "추가 폴다 경로",
"downloadPathTemplates": "다운로드 경로 템플릿",
"priorityTags": "우선순위 태그",
"updateFlags": "업데이트 표시",
"versionScope": "업데이트 표시",
"exampleImages": "예시 이미지",
"autoOrganize": "자동 정리",
"metadata": "메타데이터",
@@ -588,7 +595,7 @@
"download": "다운로드",
"restartRequired": "재시작 필요"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "업데이트 표시 전략",
"help": "새 릴리스가 로컬 파일과 동일한 베이스 모델을 공유할 때만 업데이트 배지를 표시할지, 또는 해당 모델에 사용 가능한 새 버전이 있으면 항상 표시할지 결정합니다.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "작은 순서",
"usage": "사용 횟수",
"usageDesc": "많은 순",
"usageAsc": "적은 순"
"usageAsc": "적은 순",
"versionsCount": "로컬 버전 수",
"versionsCountDesc": "버전 수 많은 순",
"versionsCountAsc": "버전 수 적은 순"
},
"refresh": {
"title": "모델 목록 새로고침",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "Количество использований"
},
"footer": {
"versionCount": "{count} версий",
"viewAllVersions": "Показать все локальные версии"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "Управление исключёнными моделями"
},
"groupByModel": {
"label": "Группировать по модели"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "Дополнительные пути к папкам",
"downloadPathTemplates": "Шаблоны путей загрузки",
"priorityTags": "Приоритетные теги",
"updateFlags": "Метки обновлений",
"versionScope": "Метки обновлений",
"exampleImages": "Примеры изображений",
"autoOrganize": "Автоорганизация",
"metadata": "Метаданные",
@@ -588,7 +595,7 @@
"download": "Загрузить",
"restartRequired": "Требует перезапуска"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "Стратегия меток обновлений",
"help": "Выберите, отображать ли значки обновления только когда новая версия имеет тот же базовый модель, что и локальные файлы, или всегда при наличии любого нового релиза для этой модели.",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "Наименьшим",
"usage": "Число использований",
"usageDesc": "Больше",
"usageAsc": "Меньше"
"usageAsc": "Меньше",
"versionsCount": "Локальные версии",
"versionsCountDesc": "Сначала больше версий",
"versionsCountAsc": "Сначала меньше версий"
},
"refresh": {
"title": "Обновить список моделей",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "使用次数"
},
"footer": {
"versionCount": "{count} 个版本",
"viewAllVersions": "查看所有本地版本"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "管理已排除的模型"
},
"groupByModel": {
"label": "按模型分组"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "额外文件夹路径",
"downloadPathTemplates": "下载路径模板",
"priorityTags": "优先标签",
"updateFlags": "更新标记",
"versionScope": "版本范围",
"exampleImages": "示例图片",
"autoOrganize": "自动整理",
"metadata": "元数据",
@@ -588,12 +595,12 @@
"download": "下载",
"restartRequired": "需要重启"
},
"updateFlagStrategy": {
"label": "更新标记策略",
"help": "决定更新徽章是否仅在新版本与本地文件共享相同基础模型时显示,或只要该模型有任何更新版本就显示。",
"versionGrouping": {
"label": "版本分组",
"help": "控制版本在 UI 中的分组方式:按基础模型分组或合并显示。同时影响更新徽章逻辑和版本列表的筛选行为。",
"options": {
"sameBase": "按基础模型匹配更新",
"any": "显示任何可用更新"
"sameBase": "按基础模型分组",
"any": "显示所有版本"
}
},
"hideEarlyAccessUpdates": {
@@ -672,7 +679,10 @@
"sizeAsc": "最小",
"usage": "使用次数",
"usageDesc": "最多",
"usageAsc": "最少"
"usageAsc": "最少",
"versionsCount": "本地版本数",
"versionsCountDesc": "版本数从多到少",
"versionsCountAsc": "版本数从少到多"
},
"refresh": {
"title": "刷新模型列表",

View File

@@ -145,6 +145,10 @@
},
"usage": {
"timesUsed": "使用次數"
},
"footer": {
"versionCount": "{count} 個版本",
"viewAllVersions": "檢視所有本地版本"
}
},
"globalContextMenu": {
@@ -183,6 +187,9 @@
},
"manageExcludedModels": {
"label": "管理已排除的模型"
},
"groupByModel": {
"label": "按模型分組"
}
},
"header": {
@@ -325,7 +332,7 @@
"extraFolderPaths": "額外資料夾路徑",
"downloadPathTemplates": "下載路徑範本",
"priorityTags": "優先標籤",
"updateFlags": "更新標記",
"versionScope": "版本範圍",
"exampleImages": "範例圖片",
"autoOrganize": "自動整理",
"metadata": "中繼資料",
@@ -588,7 +595,7 @@
"download": "下載",
"restartRequired": "需要重新啟動"
},
"updateFlagStrategy": {
"versionGrouping": {
"label": "更新標記策略",
"help": "決定更新徽章是否僅在新版本與本地檔案共享相同基礎模型時顯示,或只要該模型有任何更新版本就顯示。",
"options": {
@@ -672,7 +679,10 @@
"sizeAsc": "最小",
"usage": "使用次數",
"usageDesc": "最多",
"usageAsc": "最少"
"usageAsc": "最少",
"versionsCount": "本地版本數",
"versionsCountDesc": "版本數從多到少",
"versionsCountAsc": "版本數從少到多"
},
"refresh": {
"title": "重新整理模型列表",

View File

@@ -608,7 +608,7 @@ class SaveImageLM:
img = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8))
# Generate filename with counter if needed
base_filename = filename
base_filename = filename.replace("%batch_num%", str(i))
if add_counter_to_filename:
# Use counter + i to ensure unique filenames for all images in batch
current_counter = counter + i

View File

@@ -115,19 +115,50 @@ class BaseModelService(ABC):
# Optionally group by civitai modelId, showing only the latest version per model
dedup_lost = 0
if kwargs.get("group_by_model") and civitai_model_id is None:
dedup_map = {} # modelId -> (item, version_id)
# Determine whether to further sub-group by base model
# When version_grouping is "same_base", versions with different
# base models are effectively different groups — the dedup key
# needs to include base_model so the version count and VLM flow
# stay consistent (card shows correct count for its base model).
ufs = self.settings.get("version_grouping", "same_base")
group_by_base = ufs == "same_base"
dedup_map = {} # (modelId [,base_model]) -> (item, version_id)
version_counter = {} # same-key -> count
standalone = []
for item in sorted_data:
mid = self._extract_model_id(item)
if mid is None:
standalone.append(item)
continue
key = (mid, item.get("base_model") or "") if group_by_base else mid
# Count all versions per key
version_counter[key] = version_counter.get(key, 0) + 1
vid = self._extract_version_id(item) or 0
if mid not in dedup_map or vid > dedup_map[mid][1]:
dedup_map[mid] = (item, vid)
if key not in dedup_map or vid > dedup_map[key][1]:
dedup_map[key] = (item, vid)
# Attach version_count to each surviving grouped item (shallow copy
# to avoid mutating cached dicts — the cache is shared across requests)
for key, (item, vid) in dedup_map.items():
item = dict(item)
item["version_count"] = version_counter[key]
dedup_map[key] = (item, vid)
dedup_lost = len(sorted_data) - (len(dedup_map) + len(standalone))
sorted_data = [entry[0] for entry in dedup_map.values()] + standalone
# Re-sort by version_count after dedup (only makes sense in group_by_model mode)
is_group_by_active = kwargs.get("group_by_model") and civitai_model_id is None
if sort_params.key == "versions_count" and is_group_by_active:
reverse = sort_params.order == "desc"
sorted_data.sort(
key=lambda x: (
x.get("version_count", 0),
(x.get("model_name") or x.get("file_name") or "").lower(),
x.get("file_path", "").lower(),
),
reverse=reverse,
)
t1 = time.perf_counter()
if hash_filters:
filtered_data = await self._apply_hash_filters(sorted_data, hash_filters)
@@ -520,7 +551,7 @@ class BaseModelService(ABC):
if not ordered_ids:
return annotated
strategy_value = self.settings.get("update_flag_strategy")
strategy_value = self.settings.get("version_grouping")
if isinstance(strategy_value, str) and strategy_value.strip():
strategy = strategy_value.strip().lower()
else:

View File

@@ -48,6 +48,7 @@ class CheckpointService(BaseModelService):
"skip_metadata_refresh": bool(checkpoint_data.get("skip_metadata_refresh", False)),
"civitai": self.filter_civitai_data(checkpoint_data.get("civitai", {}), minimal=True),
"auto_tags": checkpoint_data.get("auto_tags") or extract_auto_tags(checkpoint_data),
"version_count": checkpoint_data.get("version_count"),
}
def find_duplicate_hashes(self) -> Dict:

View File

@@ -48,6 +48,7 @@ class EmbeddingService(BaseModelService):
"skip_metadata_refresh": bool(embedding_data.get("skip_metadata_refresh", False)),
"civitai": self.filter_civitai_data(embedding_data.get("civitai", {}), minimal=True),
"auto_tags": embedding_data.get("auto_tags") or extract_auto_tags(embedding_data),
"version_count": embedding_data.get("version_count"),
}
def find_duplicate_hashes(self) -> Dict:

View File

@@ -59,6 +59,7 @@ class LoraService(BaseModelService):
lora_data.get("civitai", {}), minimal=True
),
"auto_tags": lora_data.get("auto_tags") or extract_auto_tags(lora_data),
"version_count": lora_data.get("version_count"),
}
async def _apply_specific_filters(self, data: List[Dict], **kwargs) -> List[Dict]:

View File

@@ -18,6 +18,8 @@ SUPPORTED_SORT_MODES = [
('size', 'desc'),
('usage', 'asc'),
('usage', 'desc'),
('versions_count', 'asc'),
('versions_count', 'desc'),
]
# Is this in use?
@@ -263,6 +265,17 @@ class ModelCache:
),
reverse=reverse
)
elif sort_key == 'versions_count':
# Pre-dedup sort: fall back to name sort.
# Actual re-sort by version_count happens in get_paginated_data after dedup.
result = natsorted(
data,
key=lambda x: (
self._get_display_name(x).lower(),
x.get('file_path', '').lower()
),
reverse=reverse
)
else:
# Fallback: no sort
result = list(data)

View File

@@ -98,7 +98,7 @@ DEFAULT_SETTINGS: Dict[str, Any] = {
"lora_syntax_format": "legacy",
"model_card_footer_action": "replace_preview",
"show_version_on_card": True,
"update_flag_strategy": "same_base",
"version_grouping": "same_base",
"auto_organize_exclusions": [],
"metadata_refresh_skip_paths": [],
"skip_previously_downloaded_model_versions": False,
@@ -745,6 +745,7 @@ class SettingsManager:
"includeTriggerWords": "include_trigger_words",
"compactMode": "compact_mode",
"modelCardFooterAction": "model_card_footer_action",
"update_flag_strategy": "version_grouping",
}
updated = False

View File

@@ -509,6 +509,50 @@
background: rgba(0,0,0,0.18); /* Optional: subtle background for contrast */
}
/* Clickable version count link (shown in group-by-model mode) */
.version-count-link {
display: inline-block;
color: var(--color-accent);
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
font-size: 0.85em;
line-height: 1.4;
margin-top: 2px;
border: 1px solid var(--color-accent-border);
border-radius: var(--border-radius-xs);
padding: 1px 6px;
background: var(--color-accent-subtle);
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease;
}
.version-count-link:hover {
background: var(--color-accent-border);
border-color: var(--color-accent-transparent);
}
/* Medium density adjustments for version count link */
.medium-density .version-count-link {
font-size: 0.8em;
}
.medium-density .badge-version-unit .version-count-link {
max-width: 90px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Compact density adjustments for version count link */
.compact-density .version-count-link {
font-size: 0.75em;
}
.compact-density .badge-version-unit .version-count-link {
max-width: 70px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Version row — flex container for badges + version names */
.version-row {
display: flex;

View File

@@ -59,3 +59,8 @@
.initialization-notice .loading-spinner {
margin-bottom: var(--space-2);
}
/* Hide versions_count sort option when group-by-model is off */
body:not(.group-by-model) .sort-option-versions-count {
display: none;
}

View File

@@ -24,6 +24,14 @@ export class GlobalContextMenu extends BaseContextMenu {
const cleanupExamplesItem = this.menu.querySelector('[data-action="cleanup-example-images-folders"]');
const excludedModelsItem = this.menu.querySelector('[data-action="manage-excluded-models"]');
const repairRecipesItem = this.menu.querySelector('[data-action="repair-recipes"]');
const groupByModelItem = this.menu.querySelector('[data-action="toggle-group-by-model"]');
const groupByModelCheck = groupByModelItem?.querySelector('.check-indicator');
// Update check indicator for group-by-model
if (groupByModelCheck) {
const isEnabled = !!state.global.settings.group_by_model;
groupByModelCheck.style.display = isEnabled ? 'block' : 'none';
}
if (isRecipesPage) {
modelUpdateItem?.classList.add('hidden');
@@ -31,6 +39,7 @@ export class GlobalContextMenu extends BaseContextMenu {
downloadExamplesItem?.classList.add('hidden');
cleanupExamplesItem?.classList.add('hidden');
excludedModelsItem?.classList.add('hidden');
groupByModelItem?.classList.add('hidden');
repairRecipesItem?.classList.remove('hidden');
} else {
modelUpdateItem?.classList.remove('hidden');
@@ -38,6 +47,7 @@ export class GlobalContextMenu extends BaseContextMenu {
downloadExamplesItem?.classList.remove('hidden');
cleanupExamplesItem?.classList.remove('hidden');
excludedModelsItem?.classList.remove('hidden');
groupByModelItem?.classList.remove('hidden');
repairRecipesItem?.classList.add('hidden');
}
@@ -74,6 +84,9 @@ export class GlobalContextMenu extends BaseContextMenu {
case 'manage-excluded-models':
this.manageExcludedModels();
break;
case 'toggle-group-by-model':
this.toggleGroupByModel();
break;
default:
console.warn(`Unhandled global context menu action: ${action}`);
break;
@@ -86,6 +99,30 @@ export class GlobalContextMenu extends BaseContextMenu {
});
}
toggleGroupByModel() {
const sm = window.settingsManager;
if (!sm) {
console.error('settingsManager not available on window');
return;
}
const newValue = !state.global.settings.group_by_model;
state.global.settings.group_by_model = newValue;
// Save/restore sort preference when toggling group_by_model
if (window.pageControls?.onGroupByModelToggled) {
window.pageControls.onGroupByModelToggled(newValue);
}
sm.saveSetting('group_by_model', newValue).catch((error) => {
console.error('Failed to save group_by_model setting:', error);
// Revert state on failure
state.global.settings.group_by_model = !newValue;
});
sm.applyFrontendSettings();
sm.reloadContent();
}
async downloadExampleImages(menuItem) {
const downloadPath = state?.global?.settings?.example_images_path;
if (!downloadPath) {

View File

@@ -102,7 +102,12 @@ export class CheckpointsControls extends PageControls {
removeSessionItem('vlm_model_name');
removeSessionItem('vlm_base_model');
removeSessionItem('vlm_page_type');
window.location.reload();
// Hide the indicator
const indicator = document.getElementById('customFilterIndicator');
if (indicator) {
indicator.classList.add('hidden');
}
await resetAndReload();
return;
}

View File

@@ -119,7 +119,11 @@ export class LorasControls extends PageControls {
removeSessionItem('vlm_model_name');
removeSessionItem('vlm_base_model');
removeSessionItem('vlm_page_type');
window.location.reload();
const indicator = document.getElementById('customFilterIndicator');
if (indicator) {
indicator.classList.add('hidden');
}
await resetAndReload();
return;
}

View File

@@ -1,6 +1,6 @@
// PageControls.js - Manages controls for both LoRAs and Checkpoints pages
import { state, getCurrentPageState, setCurrentPageType } from '../../state/index.js';
import { getStorageItem, setStorageItem, getSessionItem, setSessionItem, removeSessionItem } from '../../utils/storageHelpers.js';
import { getStorageItem, setStorageItem, removeStorageItem, getSessionItem, setSessionItem, removeSessionItem } from '../../utils/storageHelpers.js';
import { showToast, openCivitaiByMetadata } from '../../utils/uiHelpers.js';
import { performModelUpdateCheck } from '../../utils/updateCheckHelpers.js';
import { sidebarManager } from '../SidebarManager.js';
@@ -465,6 +465,68 @@ export class PageControls {
/**
* Clear custom filter
*/
/**
* Trigger View Local Versions without page reload
* Sets sessionStorage and reloads data via the API.
*/
triggerVlmView(modelId, modelName, baseModel, pageType) {
const targetPageType = pageType || this.pageType;
setSessionItem('vlm_model_id', String(modelId));
setSessionItem('vlm_model_name', modelName || String(modelId));
setSessionItem('vlm_page_type', targetPageType);
if (baseModel) {
setSessionItem('vlm_base_model', baseModel);
} else {
removeSessionItem('vlm_base_model');
}
// Reload data via API (no page reload)
this.resetAndReload(true).then(() => {
// Show the VLM indicator after data loads
this.checkVlmFilter();
});
}
/**
* Called when group_by_model is toggled.
* Saves current sort when entering grouped mode, restores normal sort
* when leaving — prevents "Most versions first" persisting after exit.
*/
onGroupByModelToggled(isEnabled) {
const normalKey = `${this.pageType}_sort_normal`;
const groupedKey = `${this.pageType}_sort_grouped`;
if (isEnabled) {
// Entering group mode: save current sort for later restoration
setStorageItem(normalKey, this.pageState.sortBy);
// Restore previously saved grouped sort, if any
const savedGroupedSort = getStorageItem(groupedKey);
if (savedGroupedSort) {
this.pageState.sortBy = savedGroupedSort;
this.saveSortPreference(savedGroupedSort);
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortSelect.value = savedGroupedSort;
}
}
} else {
// Leaving group mode: save current grouped sort aside, restore normal
const currentSort = this.pageState.sortBy;
if (currentSort && currentSort.startsWith('versions_count')) {
setStorageItem(groupedKey, currentSort);
}
const savedNormalSort = getStorageItem(normalKey);
if (savedNormalSort) {
removeStorageItem(normalKey);
this.pageState.sortBy = savedNormalSort;
this.saveSortPreference(savedNormalSort);
const sortSelect = document.getElementById('sortSelect');
if (sortSelect) {
sortSelect.value = savedNormalSort;
}
}
}
}
/**
* Check for View Local Versions filter in sessionStorage (page-type-scoped)
*/
@@ -515,8 +577,14 @@ export class PageControls {
removeSessionItem('vlm_base_model');
removeSessionItem('vlm_page_type');
// Full page reload to restore initial state (mirrors the "set" action)
window.location.reload();
// Hide the indicator
const indicator = document.getElementById('customFilterIndicator');
if (indicator) {
indicator.classList.add('hidden');
}
// Reload data via API (no page reload)
await this.resetAndReload(true);
return;
}

View File

@@ -100,6 +100,12 @@ function handleModelCardEvent_internal(event, modelType) {
return true; // Stop propagation
}
if (event.target.closest('.version-count-link')) {
event.stopPropagation();
handleViewLocalVersionsFromCard(card, modelType);
return true;
}
// If no specific element was clicked, handle the card click (show modal or toggle selection)
handleCardClick(card, modelType);
return false; // Continue with other handlers (e.g., bulk selection)
@@ -265,6 +271,22 @@ async function handleExampleImagesAccess(card, modelType) {
}
}
function handleViewLocalVersionsFromCard(card, modelType) {
const modelId = card.dataset.modelId;
const modelName = card.dataset.name;
if (!modelId) return;
// Respect version_grouping: only filter by base model when the strategy says so
const strategy = state.global?.settings?.version_grouping;
const shouldFilterByBase = strategy === 'same_base';
const baseModel = shouldFilterByBase && card.dataset.base_model !== 'Unknown'
? card.dataset.base_model
: undefined;
// Use the no-reload VLM flow via PageControls
if (window.pageControls && typeof window.pageControls.triggerVlmView === 'function') {
window.pageControls.triggerVlmView(modelId, modelName, baseModel, modelType);
}
}
function handleCardClick(card, modelType) {
const pageState = getCurrentPageState();
@@ -448,6 +470,10 @@ export function createModelCard(model, modelType) {
const hasUpdateAvailable = Boolean(model.update_available);
card.dataset.update_available = hasUpdateAvailable ? 'true' : 'false';
card.dataset.skip_metadata_refresh = model.skip_metadata_refresh ? 'true' : 'false';
// Store version_count for group-by-model display
if (model.version_count !== undefined) {
card.dataset.version_count = model.version_count;
}
// To only show usage_count when sorting by usage.
const pageState = getCurrentPageState();
@@ -659,16 +685,28 @@ export function createModelCard(model, modelType) {
const autoTags = model.auto_tags || [];
const hlTags = autoTags.filter(t => t === 'HIGH' || t === 'LOW');
const hasVersionName = model.civitai?.name;
if (!hlTags.length && !hasVersionName) return '';
// When group_by_model is active and model has multiple versions,
// show clickable version count instead of version name (and hide badges)
const isGroupByModel = state.global.settings.group_by_model;
const versionCount = model.version_count;
const showVersionCount = isGroupByModel && versionCount > 1;
if (!hlTags.length && !hasVersionName && !showVersionCount) return '';
const density = state.global.settings.display_density || 'default';
const shortLabels = density === 'medium' || density === 'compact';
const badges = hlTags.map(t => {
// Don't show HIGH/LOW badges when showing version count (confusing in grouped mode)
const badges = !showVersionCount ? hlTags.map(t => {
const cls = t === 'HIGH' ? 'hl-badge hl-badge--high' : 'hl-badge hl-badge--low';
const label = shortLabels ? (t === 'HIGH' ? 'H' : 'L') : t;
const titleAttr = shortLabels ? ` title="${t}"` : '';
return `<span class="${cls}"${titleAttr}>${label}</span>`;
}).join('');
const versionHtml = hasVersionName ? `<span class="version-name civitai-version">${model.civitai.name}</span>` : '';
}).join('') : '';
let versionHtml = '';
if (showVersionCount) {
const countLabel = translate('modelCard.footer.versionCount', { count: versionCount }, `${versionCount} versions`);
versionHtml = `<span class="version-count-link" title="${translate('modelCard.footer.viewAllVersions', {}, 'View all local versions')}">${countLabel}</span>`;
} else if (hasVersionName) {
versionHtml = `<span class="version-name civitai-version">${model.civitai.name}</span>`;
}
return `<span class="badge-version-unit">${badges}${versionHtml}</span>`;
})()}
${hasUsageCount ? `<span class="version-name" title="${translate('modelCard.usage.timesUsed', {}, 'Times used')}">${model.usage_count}×</span>` : ''}

View File

@@ -307,7 +307,7 @@ function getToggleTooltipText(mode) {
}
function getDefaultDisplayMode() {
const strategy = state?.global?.settings?.update_flag_strategy;
const strategy = state?.global?.settings?.version_grouping;
return strategy === DISPLAY_FILTER_MODES.SAME_BASE
? DISPLAY_FILTER_MODES.SAME_BASE
: DISPLAY_FILTER_MODES.ANY;
@@ -339,7 +339,7 @@ function resolveUpdateAvailability(record, baseModel, currentVersionId) {
return false;
}
const strategy = state?.global?.settings?.update_flag_strategy;
const strategy = state?.global?.settings?.version_grouping;
const sameBaseMode = strategy === DISPLAY_FILTER_MODES.SAME_BASE;
const hideEarlyAccess = state?.global?.settings?.hide_early_access_updates;
@@ -1042,9 +1042,16 @@ export function initVersionsTab({
removeSessionItem('vlm_base_model');
}
// Close the modal and reload the page to show filtered cards
// Close the modal and navigate via no-reload VLM flow
modalManager.closeModal(modalId);
window.location.reload();
if (window.pageControls && typeof window.pageControls.triggerVlmView === 'function') {
window.pageControls.triggerVlmView(
modelId,
modelName || String(modelId),
isFilteringActive ? baseModelInfo.raw : undefined,
modelType
);
}
}
async function handleToggleVersionIgnore(button, versionId) {

View File

@@ -917,9 +917,9 @@ export class SettingsManager {
modelNameDisplaySelect.value = state.global.settings.model_name_display || 'model_name';
}
const updateFlagStrategySelect = document.getElementById('updateFlagStrategy');
if (updateFlagStrategySelect) {
updateFlagStrategySelect.value = state.global.settings.update_flag_strategy || 'same_base';
const versionGroupingSelect = document.getElementById('versionGrouping');
if (versionGroupingSelect) {
versionGroupingSelect.value = state.global.settings.version_grouping || 'same_base';
}
// Set hide early access updates setting
@@ -2018,6 +2018,10 @@ export class SettingsManager {
}
if (settingKey === 'show_only_sfw' || settingKey === 'blur_mature_content' || settingKey === 'group_by_model') {
// Save/restore sort preference when toggling group_by_model
if (settingKey === 'group_by_model' && window.pageControls?.onGroupByModelToggled) {
window.pageControls.onGroupByModelToggled(value);
}
this.reloadContent();
}
@@ -2066,7 +2070,7 @@ export class SettingsManager {
if (
settingKey === 'model_name_display'
|| settingKey === 'model_card_footer_action'
|| settingKey === 'update_flag_strategy'
|| settingKey === 'version_grouping'
|| settingKey === 'mature_blur_level'
) {
this.reloadContent();

View File

@@ -44,7 +44,7 @@ const DEFAULT_SETTINGS_BASE = Object.freeze({
include_trigger_words: false,
compact_mode: false,
priority_tags: { ...DEFAULT_PRIORITY_TAG_CONFIG },
update_flag_strategy: 'same_base',
version_grouping: 'same_base',
hide_early_access_updates: false,
auto_organize_exclusions: [],
metadata_refresh_skip_paths: [],

View File

@@ -158,6 +158,11 @@
<div class="context-menu-item" data-action="manage-excluded-models">
<i class="fas fa-eye-slash"></i> <span>{{ t('globalContextMenu.manageExcludedModels.label', default='Manage Excluded Models') }}</span>
</div>
<div class="context-menu-separator"></div>
<div class="context-menu-item" data-action="toggle-group-by-model">
<i class="fas fa-layer-group"></i> <span>{{ t('globalContextMenu.groupByModel.label') }}</span>
<i class="fas fa-check check-indicator" style="margin-left:auto;display:none"></i>
</div>
<div class="context-menu-item" data-action="repair-recipes">
<i class="fas fa-tools"></i> <span>{{ t('globalContextMenu.repairRecipes.label') }}</span>
</div>

View File

@@ -37,6 +37,12 @@
<option value="usage:asc">{{ t('loras.controls.sort.usageAsc', default='Times used (low to high)') }}</option>
</optgroup>
{% endif %}
{% if page_id != 'recipes' %}
<optgroup class="sort-option-versions-count" label="{{ t('loras.controls.sort.versionsCount', default='Local Versions') }}">
<option value="versions_count:desc">{{ t('loras.controls.sort.versionsCountDesc', default='Most versions first') }}</option>
<option value="versions_count:asc">{{ t('loras.controls.sort.versionsCountAsc', default='Fewest versions first') }}</option>
</optgroup>
{% endif %}
{% if page_id == 'recipes' %}
<optgroup label="{{ t('recipes.controls.sort.lorasCount') }}">
<option value="loras_count:desc">{{ t('recipes.controls.sort.lorasCountDesc') }}</option>

View File

@@ -1100,23 +1100,23 @@
</div>
</div>
<!-- Update Flags -->
<!-- Version Scope -->
<div class="settings-subsection">
<div class="settings-subsection-header">
<h4>{{ t('settings.sections.updateFlags') }}</h4>
<h4>{{ t('settings.sections.versionScope') }}</h4>
</div>
<div class="setting-item">
<div class="setting-row">
<div class="setting-info">
<label for="updateFlagStrategy">
{{ t('settings.updateFlagStrategy.label') }}
<i class="fas fa-info-circle info-icon" data-tooltip="{{ t('settings.updateFlagStrategy.help') }}"></i>
<label for="versionGrouping">
{{ t('settings.versionGrouping.label') }}
<i class="fas fa-info-circle info-icon" data-tooltip="{{ t('settings.versionGrouping.help') }}"></i>
</label>
</div>
<div class="setting-control select-control">
<select id="updateFlagStrategy" onchange="settingsManager.saveSelectSetting('updateFlagStrategy', 'update_flag_strategy')">
<option value="same_base">{{ t('settings.updateFlagStrategy.options.sameBase') }}</option>
<option value="any">{{ t('settings.updateFlagStrategy.options.any') }}</option>
<select id="versionGrouping" onchange="settingsManager.saveSelectSetting('versionGrouping', 'version_grouping')">
<option value="same_base">{{ t('settings.versionGrouping.options.sameBase') }}</option>
<option value="any">{{ t('settings.versionGrouping.options.any') }}</option>
</select>
</div>
</div>

View File

@@ -33,7 +33,7 @@ const stateMock = {
global: {
settings: {
autoplay_on_hover: false,
update_flag_strategy: 'any',
version_grouping: 'any',
},
},
};
@@ -67,7 +67,7 @@ describe('ModelVersionsTab media rendering', () => {
</div>
`;
stateMock.global.settings.autoplay_on_hover = false;
stateMock.global.settings.update_flag_strategy = 'any';
stateMock.global.settings.version_grouping = 'any';
({ getModelApiClient } = await import(API_FACTORY_MODULE));
fetchModelUpdateVersions = vi.fn();
getModelApiClient.mockReturnValue({
@@ -157,7 +157,7 @@ describe('ModelVersionsTab media rendering', () => {
});
it('shows a stable label with a short state indicator', async () => {
stateMock.global.settings.update_flag_strategy = 'any';
stateMock.global.settings.version_grouping = 'any';
fetchModelUpdateVersions.mockResolvedValue({
success: true,
record: {
@@ -192,7 +192,7 @@ describe('ModelVersionsTab media rendering', () => {
});
it('filters versions to the current base model when strategy is same_base', async () => {
stateMock.global.settings.update_flag_strategy = 'same_base';
stateMock.global.settings.version_grouping = 'same_base';
fetchModelUpdateVersions.mockResolvedValue({
success: true,
record: {
@@ -235,7 +235,7 @@ describe('ModelVersionsTab media rendering', () => {
});
it('toggle button can switch to display all versions', async () => {
stateMock.global.settings.update_flag_strategy = 'same_base';
stateMock.global.settings.version_grouping = 'same_base';
fetchModelUpdateVersions.mockResolvedValue({
success: true,
record: {
@@ -286,7 +286,7 @@ describe('ModelVersionsTab media rendering', () => {
});
it('shows a newer version badge when viewing same-base results', async () => {
stateMock.global.settings.update_flag_strategy = 'same_base';
stateMock.global.settings.version_grouping = 'same_base';
fetchModelUpdateVersions.mockResolvedValue({
success: true,
record: {

View File

@@ -482,7 +482,7 @@ async def test_get_paginated_data_annotates_update_flags_with_bulk_dedup():
@pytest.mark.asyncio
async def test_update_flag_strategy_same_base_prefers_matching_base():
async def test_version_grouping_same_base_prefers_matching_base():
items = [
{
"model_name": "Pony Version",
@@ -551,7 +551,7 @@ async def test_update_flag_strategy_same_base_prefers_matching_base():
should_ignore_model=False,
)
update_service = StubUpdateServiceWithRecords({1: record})
settings = StubSettings({"update_flag_strategy": "same_base"})
settings = StubSettings({"version_grouping": "same_base"})
service = DummyService(
model_type="stub",
@@ -579,7 +579,7 @@ async def test_update_flag_strategy_same_base_prefers_matching_base():
@pytest.mark.asyncio
async def test_update_flag_strategy_same_base_honors_latest_local_version():
async def test_version_grouping_same_base_honors_latest_local_version():
items = [
{
"model_name": "Pony v0.1",
@@ -648,7 +648,7 @@ async def test_update_flag_strategy_same_base_honors_latest_local_version():
should_ignore_model=False,
)
update_service = StubUpdateServiceWithRecords({1: record})
settings = StubSettings({"update_flag_strategy": "same_base"})
settings = StubSettings({"version_grouping": "same_base"})
service = DummyService(
model_type="stub",
@@ -790,8 +790,14 @@ async def test_get_paginated_data_group_by_model_dedup():
for item in response["items"]:
if item.get("civitai", {}).get("modelId") == 1:
assert item["civitai"]["id"] == 200
# version_count should reflect total versions for this model
assert item.get("version_count") == 2, f"Expected version_count=2, got {item.get('version_count')}"
elif item.get("civitai", {}).get("modelId") == 2:
assert item["civitai"]["id"] == 99
assert item.get("version_count") == 2, f"Expected version_count=2, got {item.get('version_count')}"
else:
# Standalone item should NOT have version_count
assert "version_count" not in item, f"Standalone should not have version_count"
# With group_by_model=False (default) — all 5 items pass through
response_all = await service.get_paginated_data(