Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(models): details for ComfyUI files and LoRAs, with the source page (D1)

purplec5de273f7913
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.ts
index 742e29e2..b639a7ef 100644
--- a/dev-server/remote-stubs.ts
+++ b/dev-server/remote-stubs.ts
@@ -97,6 +97,7 @@ export function registerRemoteStubs(routes: RouteMount): void {
'/local-api/local-api-usage', '/local-api/set-download-limit', '/local-api/character-photos', '/local-api/pick-gguf-file',
'/local-api/list-custom-nodes', '/local-api/remove-custom-node', '/local-api/custom-node-log',
'/local-api/verify-model-files', '/local-api/verify-model-files-status', '/local-api/verify-model-files-cancel',
+ '/local-api/comfy-model-info',
'/local-api/trash-model-file', '/local-api/set-engine-idle-unload', '/local-api/transcribe-external',
'/local-api/set-gpu-roles', '/local-api/describe-gpu-roles',
'/local-api/abliterate-plan', '/local-api/abliterate-start', '/local-api/abliterate-status',
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rs
index 090c01ea..f32531cf 100644
--- a/src-tauri/src/commands/download.rs
+++ b/src-tauri/src/commands/download.rs
@@ -679,6 +679,54 @@ pub(crate) fn not_ours_to_delete(filename: &str, base: &str, extra_dirs: &[Strin
format!("{} was not found in the ComfyUI models folders", filename)
}
+/// Every copy of one ComfyUI model file in the folders LU downloads into and
+/// ComfyUI enumerates from. Delete and Details look a file up the same way,
+/// so the two buttons beside a row can never disagree about which file it is.
+async fn comfy_model_hits(
+ state: &State<'_, AppState>,
+ comfy_path: &str,
+ sub: &str,
+ base: &str,
+) -> Vec<PathBuf> {
+ let models_root = PathBuf::from(comfy_path).join("models");
+ // Both trees, because the download may have written into either: the
+ // engine's own folders when it was running and could be asked, the classic
+ // guess when it could not (see models_dir_in). A file the app put there is
+ // a file the app has to be able to take away again.
+ //
+ // R1-4: asked fresh via engine_folders (a running ComfyUI's own answer),
+ // not the stale process-wide cache from before this ComfyUI ever
+ // started, a model the running engine had just remapped to a custom
+ // folder looked like a foreign file and refused to delete.
+ let mut roots: Vec<PathBuf> = MODEL_SUBDIRS.iter().map(|d| models_root.join(d)).collect();
+ if let Some(folders) = engine_folders(state).await {
+ for dir in folders.all_dirs() {
+ if !roots.contains(&dir) {
+ roots.push(dir);
+ }
+ }
+ }
+ // GH #183: the folders the user configured for ComfyUI, where a download
+ // writes now even while ComfyUI is shut down.
+ for dir in comfy_user_paths::for_comfy(&Some(comfy_path.to_string())).all_dirs() {
+ if !roots.contains(&dir) {
+ roots.push(dir);
+ }
+ }
+ let mut hits: Vec<PathBuf> = Vec::new();
+ for root in &roots {
+ let cand = if sub.is_empty() {
+ root.join(base)
+ } else {
+ root.join(sub).join(base)
+ };
+ if cand.is_file() && !hits.contains(&cand) {
+ hits.push(cand);
+ }
+ }
+ hits
+}
+
/// Delete one installed model file from the ComfyUI models tree (the Model
/// Hub's trash action — Discord 2026-07-19: a 27 GB video
/// model his PC couldn't run had no in-app way back out). The name is the
@@ -716,42 +764,7 @@ pub async fn delete_comfy_model(
safe_subfolder(&sub)?;
}
let base = sanitize_filename(&base);
- let models_root = PathBuf::from(&comfy_path).join("models");
- // Both trees, because the download may have written into either: the
- // engine's own folders when it was running and could be asked, the classic
- // guess when it could not (see models_dir_in). A file the app put there is
- // a file the app has to be able to take away again.
- //
- // R1-4: asked fresh via engine_folders (a running ComfyUI's own answer),
- // not the stale process-wide cache from before this ComfyUI ever
- // started, a model the running engine had just remapped to a custom
- // folder looked like a foreign file and refused to delete.
- let mut roots: Vec<PathBuf> = MODEL_SUBDIRS.iter().map(|d| models_root.join(d)).collect();
- if let Some(folders) = engine_folders(&state).await {
- for dir in folders.all_dirs() {
- if !roots.contains(&dir) {
- roots.push(dir);
- }
- }
- }
- // GH #183: the folders the user configured for ComfyUI, where a download
- // writes now even while ComfyUI is shut down.
- for dir in comfy_user_paths::for_comfy(&Some(comfy_path.clone())).all_dirs() {
- if !roots.contains(&dir) {
- roots.push(dir);
- }
- }
- let mut hits: Vec<PathBuf> = Vec::new();
- for root in &roots {
- let cand = if sub.is_empty() {
- root.join(&base)
- } else {
- root.join(&sub).join(&base)
- };
- if cand.is_file() && !hits.contains(&cand) {
- hits.push(cand);
- }
- }
+ let hits = comfy_model_hits(&state, &comfy_path, &sub, &base).await;
match hits.len() {
0 => Err(not_ours_to_delete(
&filename,
@@ -784,6 +797,84 @@ pub async fn delete_comfy_model(
}
}
+/// Details for one ComfyUI model file (D1, a user on Discord,
+/// 01.11.2026: the ⓘ beside the bin did nothing for an image model or a
+/// LoRA, because it asked Ollama, which knows no ComfyUI file). Found the
+/// way Delete finds it; a file in the user's own Storage folder is shown
+/// too, since reading is not deleting. Never a path outside those folders.
+#[allow(non_snake_case)]
+#[tauri::command]
+pub async fn comfy_model_info(
+ filename: String,
+ extraDirs: Option<Vec<String>>,
+ state: State<'_, AppState>,
+) -> Result<serde_json::Value, String> {
+ if let Some(remote) = remote_comfy(&state) {
+ return Err(format!(
+ "{} is on the ComfyUI machine ({}). LU cannot read files there.",
+ filename, remote.host
+ ));
+ }
+ let comfy_path = state
+ .comfy_path
+ .lock()
+ .unwrap()
+ .clone()
+ .ok_or("ComfyUI path not set. Please set it in settings or install ComfyUI first.")?;
+ let (sub, base) = split_model_ref(&filename);
+ if !sub.is_empty() {
+ safe_subfolder(&sub)?;
+ }
+ let base = sanitize_filename(&base);
+ let mut hits = comfy_model_hits(&state, &comfy_path, &sub, &base).await;
+ let mut own_folder = false;
+ if hits.is_empty() {
+ hits = own_folder_hits(&base, &extraDirs.unwrap_or_default());
+ own_folder = !hits.is_empty();
+ }
+ let file = hits
+ .first()
+ .ok_or_else(|| format!("{} was not found in the ComfyUI models folders", filename))?;
+ Ok(file_facts(file, own_folder, hits.len()))
+}
+
+/// A file of that name in the user's own model folder (Storage), the place
+/// `not_ours_to_delete` names.
+fn own_folder_hits(base: &str, extra_dirs: &[String]) -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ for raw in extra_dirs {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ for (_, folder) in crate::commands::custom_models::comfy_shaped_subdirs(Path::new(trimmed)) {
+ let cand = folder.join(base);
+ if cand.is_file() && !out.contains(&cand) {
+ out.push(cand);
+ }
+ }
+ }
+ out
+}
+
+/// What the Details dialog shows about a file on disk.
+fn file_facts(file: &Path, own_folder: bool, copies: usize) -> serde_json::Value {
+ let meta = fs::metadata(file).ok();
+ let modified = meta
+ .as_ref()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs());
+ serde_json::json!({
+ "path": file.to_string_lossy(),
+ "folder": file.parent().map(|p| p.to_string_lossy().to_string()).unwrap_or_default(),
+ "bytes": meta.map(|m| m.len()).unwrap_or(0),
+ "modified": modified,
+ "ownFolder": own_folder,
+ "copies": copies,
+ })
+}
+
/// The delete with `trash`: the file goes to the system's Trash and can be
/// put back from there. A trained character is the user's own work and hours
/// of training, so its delete on the Create page takes this way, the same one
@@ -3315,6 +3406,35 @@ mod tests {
assert!(file.exists(), "the file stays where the bin refused it");
}
+ #[test]
+ fn d1_details_read_a_file_in_the_users_own_folder_and_nothing_outside() {
+ let dir = std::env::temp_dir().join(format!("lu-d1-own-{}", std::process::id()));
+ let loras = dir.join("loras");
+ fs::create_dir_all(&loras).unwrap();
+ fs::write(loras.join("style.safetensors"), b"12345").unwrap();
+ fs::write(dir.join("outside.safetensors"), b"x").unwrap();
+ let extra = vec![dir.to_string_lossy().to_string()];
+ let hits = own_folder_hits("style.safetensors", &extra);
+ assert_eq!(hits, vec![loras.join("style.safetensors")]);
+ // A file beside the model folders is not a model of that folder.
+ assert!(own_folder_hits("outside.safetensors", &extra).is_empty());
+ let facts = file_facts(&hits[0], true, 1);
+ assert_eq!(facts["bytes"], 5);
+ assert_eq!(facts["ownFolder"], true);
+ assert_eq!(facts["folder"], loras.to_string_lossy().to_string());
+ assert!(facts["modified"].as_u64().is_some());
+ let _ = fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn d1_details_and_delete_find_a_file_the_same_way() {
+ let src = include_str!("download.rs");
+ let info = fn_body(src, "pub async fn comfy_model_info(");
+ assert!(info.contains("comfy_model_hits(&state"), "{info}");
+ assert!(info.contains("safe_subfolder(&sub)"), "{info}");
+ assert!(info.contains("sanitize_filename(&base)"), "{info}");
+ }
+
#[test]
fn the_trash_delete_never_removes_for_good() {
// Quelltextwaechter: der Zweig mit `trash` geht an den System-Papierkorb
@@ -3346,7 +3466,11 @@ mod tests {
!space_body.contains("comfy_folders::cached()"),
"check_download_space still reads the stale cache instead of asking the engine"
);
- assert!(delete_body.contains("engine_folders(&state).await"), "{delete_body}");
+ // Delete and Details share one lookup (D1), which asks the engine.
+ assert!(delete_body.contains("comfy_model_hits(&state"), "{delete_body}");
+ let hits_body = fn_body(src, "async fn comfy_model_hits(");
+ assert!(!hits_body.contains("comfy_folders::cached()"), "{hits_body}");
+ assert!(hits_body.contains("engine_folders(state).await"), "{hits_body}");
// The space check goes through comfy_models_dir since GH #143 (a
// remote ComfyUI measures the Storage folder), and that one asks
// the engine fresh for everything else.
diff --git a/src-tauri/src/commands/mobile_guard.rs b/src-tauri/src/commands/mobile_guard.rs
index 39c253d1..eecf4cb8 100644
--- a/src-tauri/src/commands/mobile_guard.rs
+++ b/src-tauri/src/commands/mobile_guard.rs
@@ -229,6 +229,7 @@ pub const ALLOWED: &[&str] = &[
"lmstudio_model_dir",
"check_model_sizes",
"delete_comfy_model",
+ "comfy_model_info",
"set_hf_token",
"hf_token_present",
"start_bundled_engine",
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0a8254ad..cb75199e 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -950,6 +950,7 @@ pub fn run() {
commands::download::lmstudio_model_dir,
commands::download::check_model_sizes,
commands::download::delete_comfy_model,
+ commands::download::comfy_model_info,
// Check files and Repair (GH #113)
commands::model_verify::verify_model_files,
commands::model_verify::verify_model_files_status,
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 0f82dadb..5b728695 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -656,6 +656,8 @@ export async function backendCall<T = unknown>(
detect_model_path: { path: "/local-api/detect-model-path", method: "POST" },
check_model_sizes: { path: "/local-api/check-model-sizes", method: "POST" },
delete_comfy_model: { path: "/local-api/delete-comfy-model", method: "POST" },
+ // D1: Details for a ComfyUI file. Rust only, the dev server answers 501.
+ comfy_model_info: { path: "/local-api/comfy-model-info", method: "POST" },
// Check files and Repair (GH #113): Rust only, the dev server answers
// 501 (dev-server/remote-stubs.ts).
verify_model_files: { path: "/local-api/verify-model-files", method: "POST" },
diff --git a/src/api/discover.ts b/src/api/discover.ts
index 28cd3f12..fbfdd243 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -6,6 +6,7 @@ import { restartComfyForNewNodes } from "./comfy-restart"
import type { ProviderId } from "./providers/types"
import { log } from "../lib/logger"
import { useWorkflowStore } from "../stores/workflowStore"
+import { recordSourceFromDownload } from "../stores/modelSourceStore"
import { waitForModelsVisible } from "../lib/bundle-install"
import { bundleBytesToFetch } from "../lib/bundle-state"
import type { DownloadProgress } from "../types/downloads"
@@ -77,6 +78,8 @@ export function civitaiAuthToken(url: string): string | null {
}
export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number, sha256?: string): Promise<{ status: string; id: string; error?: string }> {
+ // D1: the page this file came from, for Details in Models.
+ recordSourceFromDownload(filename, url)
return backendCall("download_model", {
url,
subfolder,
@@ -87,6 +90,24 @@ export async function startModelDownload(url: string, subfolder: string, filenam
})
}
+/** What `comfy_model_info` reads about one ComfyUI model file (D1). */
+export interface ComfyFileFacts {
+ path: string
+ folder: string
+ bytes: number
+ /** Seconds since 1970, or null when the system did not say. */
+ modified: number | null
+ /** The file sits in the user's own Storage folder, not ComfyUI's. */
+ ownFolder: boolean
+ /** How many copies of that name the model folders hold. */
+ copies: number
+}
+
+/** Details for a ComfyUI file of the Installed list. Throws with the reason. */
+export async function comfyModelInfo(filename: string): Promise<ComfyFileFacts> {
+ return backendCall('comfy_model_info', { filename, extraDirs: customModelDirs() })
+}
+
export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {
try {
return await backendCall("download_progress")
@@ -1963,6 +1984,7 @@ export async function startModelDownloadToPath(url: string, destDir: string, fil
// from the CivitAI search into the Mac's LoRA folder). Every other caller
// sends what it sent before.
const authToken = civitaiAuthToken(url)
+ recordSourceFromDownload(filename, url)
return backendCall('download_model_to_path', {
url, destDir, filename, expectedBytes: expectedBytes ?? null, expectedSha256: sha256 ?? null,
...(authToken ? { authToken } : {}),
diff --git a/src/api/lora-link.ts b/src/api/lora-link.ts
index 8c3628e4..708b5ff0 100644
--- a/src/api/lora-link.ts
+++ b/src/api/lora-link.ts
@@ -9,6 +9,7 @@
import { fetchExternal } from './backend'
import { startModelDownload, startModelDownloadToPath } from './discover'
import { useDownloadStore } from '../stores/downloadStore'
+import { useModelSourceStore } from '../stores/modelSourceStore'
import {
civitaiLoraFromModel,
civitaiLoraFromVersionAnswer,
@@ -117,6 +118,8 @@ export async function startLoraLinkDownload(info: LoraLinkInfo, destDir?: string
const store = useDownloadStore.getState()
const extra = { expectedBytes: info.sizeBytes, sha256: info.sha256 }
store.setMeta(info.filename, info.downloadUrl, 'loras', destDir, extra)
+ // D1: the page the link pointed at, for Details in Models.
+ useModelSourceStore.getState().record(info.filename, info.pageUrl)
const answer = destDir
? await startModelDownloadToPath(info.downloadUrl, destDir, info.filename, info.sizeBytes, info.sha256)
: await startModelDownload(info.downloadUrl, 'loras', info.filename, info.sizeBytes, info.sha256)
diff --git a/src/components/models/CivitaiSearchPanel.tsx b/src/components/models/CivitaiSearchPanel.tsx
index d7b76450..504af3e7 100644
--- a/src/components/models/CivitaiSearchPanel.tsx
+++ b/src/components/models/CivitaiSearchPanel.tsx
@@ -9,6 +9,7 @@
*/
import { useEffect, useMemo, useRef, useState } from 'react'
import { Search, Loader2, ExternalLink, Download, CheckCircle } from 'lucide-react'
+import { useModelSourceStore } from '../../stores/modelSourceStore'
import { checkCivitaiInstalled, civitaiInstalledInFolder, searchCivitaiModels, startCivitaiDownload, startModelDownloadToPath, type CivitAIModelResult } from '../../api/discover'
import { openExternal } from '../../api/backend'
import { useDownloadStore } from '../../stores/downloadStore'
@@ -120,6 +121,8 @@ export function CivitaiSearchPanel({ modelType, title, placeholder, search = '',
const download = async (model: CivitAIModelResult) => {
if (!model.downloadUrl || !model.filename || !model.subfolder) return
+ // D1: the CivitAI page of the hit, for Details in Models.
+ useModelSourceStore.getState().record(model.filename, model.sourceUrl)
if (destDir) {
// The folder goes into the record with the file, so Retry and Resume
// write to the same place and never look for a ComfyUI.
diff --git a/src/components/models/LoraManager.tsx b/src/components/models/LoraManager.tsx
index 07a8cd2a..e864f1f5 100644
--- a/src/components/models/LoraManager.tsx
+++ b/src/components/models/LoraManager.tsx
@@ -10,7 +10,7 @@
* the `source: 'lora'` half of it), so there is no second reader and no second
* answer about what is installed.
*/
-import { Layers, Trash2 } from 'lucide-react'
+import { Info, Layers, Trash2 } from 'lucide-react'
import { parseLocalCharacterLora } from '../../api/trainer'
import { formatBytes } from '../../lib/formatters'
import { ModelEmptyState, SectionHead } from './ModelPageParts'
@@ -34,6 +34,8 @@ export interface LoraManagerProps {
searchQuery: string
/** Opens the shared delete confirmation of the Models view. */
onDelete: (name: string) => void
+ /** Opens the Details dialog of that file (D1). */
+ onInfo?: (name: string) => void
/** Sends the user to the Get new segment of this same rail. */
onGetNew: () => void
}
@@ -44,7 +46,7 @@ export interface LoraManagerProps {
* the list "LoRA stack" (ParamGroups.tsx). */
export const LORA_USE_HINT = 'Use them in Create, Advanced settings, Expert, LoRA stack.'
-export function LoraManager({ rows, total, searchQuery, onDelete, onGetNew }: LoraManagerProps) {
+export function LoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNew }: LoraManagerProps) {
if (total === 0) {
return (
<ModelEmptyState
@@ -91,6 +93,16 @@ export function LoraManager({ rows, total, searchQuery, onDelete, onGetNew }: Lo
{character && <span className="font-mono">Trigger word: {character.trigger}</span>}
</div>
</div>
+ {onInfo && (
+ <button
+ onClick={() => onInfo(row.name)}
+ title="Details"
+ aria-label={`Details of ${row.name}`}
+ className="lu-control lu-control--icon lu-control--outline shrink-0"
+ >
+ <Info size={ICON_SM} />
+ </button>
+ )}
<button
onClick={() => onDelete(row.name)}
title="Delete"
diff --git a/src/components/models/ModelFileInfo.tsx b/src/components/models/ModelFileInfo.tsx
new file mode 100644
index 00000000..d0bcb3fb
--- /dev/null
+++ b/src/components/models/ModelFileInfo.tsx
@@ -0,0 +1,86 @@
+// Details for a ComfyUI file of the Installed list: an image or video model,
+// a LoRA, a VAE (D1, a user on Discord, 01.11.2026: the ⓘ beside the bin
+// did nothing, and LoRA rows had none). What the disk says, the page the file
+// came from when LU downloaded it, and the reason when the file cannot be read.
+import { ExternalLink, Loader2 } from 'lucide-react'
+import { Modal } from '../ui/Modal'
+import { ModalActions, ModalButton } from '../ui/ModalActions'
+import { formatBytes } from '../../lib/formatters'
+import { openExternal } from '../../api/backend'
+import type { ComfyFileFacts } from '../../api/discover'
+
+export interface ModelFileInfoState {
+ /** The ComfyUI name, with its subfolder when it has one. */
+ name: string
+ /** "LoRA", "Checkpoint", … or null when the folder is not known. */
+ kind: string | null
+ /** Size from the inventory, for while the disk is still being asked. */
+ size: number
+ facts: ComfyFileFacts | null
+ error: string | null
+ /** Hugging Face or CivitAI page, only when LU wrote it down. */
+ page: string | null
+}
+
+function when(secs: number | null): string | null {
+ if (secs == null) return null
+ return new Date(secs * 1000).toLocaleString()
+}
+
+function Row({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
+ return (
+ <div className="grid grid-cols-[6rem_1fr] gap-2 py-1">
+ <dt className="t-micro text-gray-500 dark:text-gray-400">{label}</dt>
+ <dd className={`t-micro text-gray-900 dark:text-gray-100 break-all ${mono ? 'font-mono' : ''}`}>{value}</dd>
+ </div>
+ )
+}
+
+export function ModelFileInfo({ info, onClose }: { info: ModelFileInfoState | null; onClose: () => void }) {
+ const facts = info?.facts ?? null
+ const file = info ? (info.name.split(/[\\/]/).pop() ?? info.name) : ''
+ const bytes = facts ? facts.bytes : info?.size ?? 0
+ return (
+ <Modal open={!!info} onClose={onClose} title={file || 'Model details'}>
+ {info && (
+ <div data-testid="model-file-info">
+ <dl className="mb-3">
+ <Row label="File" value={file} mono />
+ {info.kind && <Row label="Type" value={info.kind} />}
+ {bytes > 0 && <Row label="Size" value={formatBytes(bytes)} />}
+ {facts && <Row label="Folder" value={facts.folder} mono />}
+ {facts && when(facts.modified) && <Row label="Changed" value={when(facts.modified)!} />}
+ </dl>
+ {facts?.ownFolder && (
+ <p className="t-micro text-gray-600 dark:text-gray-300 mb-3">
+ This file is in your own model folder (Settings, Storage). LU reads it from there and does not delete it.
+ </p>
+ )}
+ {facts && facts.copies > 1 && (
+ <p className="t-micro text-gray-600 dark:text-gray-300 mb-3">
+ There are {facts.copies} files of this name in the model folders. This is the first one.
+ </p>
+ )}
+ {!facts && !info.error && (
+ <p className="t-micro text-gray-500 dark:text-gray-400 mb-3 flex items-center gap-1.5">
+ <Loader2 size={12} className="animate-spin" /> Reading the file…
+ </p>
+ )}
+ {info.error && (
+ <p role="alert" className="t-micro text-red-500 dark:text-red-400 mb-3 break-words">
+ {info.error}
+ </p>
+ )}
+ </div>
+ )}
+ <ModalActions>
+ {info?.page && (
+ <ModalButton variant="quiet" onClick={() => { void openExternal(info.page!) }}>
+ <span className="inline-flex items-center gap-1.5"><ExternalLink size={12} /> Open source page</span>
+ </ModalButton>
+ )}
+ <ModalButton onClick={onClose}>Close</ModalButton>
+ </ModalActions>
+ </Modal>
+ )
+}
diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsx
index 9db338f1..d38e1015 100644
--- a/src/components/models/ModelManager.tsx
+++ b/src/components/models/ModelManager.tsx
@@ -25,6 +25,10 @@ import { LoraAddons } from './LoraAddons'
import { Modal } from '../ui/Modal'
import { ModalActions, ModalButton } from '../ui/ModalActions'
import { showModel } from '../../api/ollama'
+import { comfyModelInfo } from '../../api/discover'
+import { ModelFileInfo, type ModelFileInfoState } from './ModelFileInfo'
+import { useModelSourceStore } from '../../stores/modelSourceStore'
+import { comfyKindLabel } from '../../lib/model-source'
import { checkComfyConnection, refreshComfyModels } from '../../api/comfyui'
import { isMlxImageHost } from '../../api/mlx-image'
import { MacMediaLane } from './MacMediaLane'
@@ -113,6 +117,9 @@ export function ModelManager() {
// das Ganze als JSON.stringify.
const [modelInfo, setModelInfo] = useState<({ name: string } & Record<string, unknown>) | null>(null)
const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
+ // D1: Details for a ComfyUI file (image or video model, LoRA, VAE, …).
+ const [fileInfo, setFileInfo] = useState<ModelFileInfoState | null>(null)
+ const fileInfoFor = useRef<string | null>(null)
// Open on Discover by default — most opens are to find and install
// something new. Installed is one click away in the segment control.
const [tab, setTab] = useState<'installed' | 'discover'>('discover')
@@ -215,12 +222,42 @@ export function ModelManager() {
setInfoOpen(true)
return
}
+ if (model && (model.type === 'image' || model.type === 'video')) {
+ await handleFileInfo(name)
+ return
+ }
try {
const info = await showModel(name)
setModelInfo({ name, ...info })
- setInfoOpen(true)
- } catch {
- // ignore
+ } catch (e) {
+ // D1: the click used to end here without a word.
+ setModelInfo({ name, error: `Ollama could not describe this model: ${e instanceof Error ? e.message : String(e)}` })
+ }
+ setInfoOpen(true)
+ }
+
+ /** D1 (a user on Discord, 01.11.2026): the ⓘ of an image model asked
+ * Ollama, which knows no ComfyUI file, and the error went nowhere. The
+ * dialog opens at once with what the list knows; the disk fills in the
+ * rest, or the reason it could not. */
+ const handleFileInfo = async (name: string) => {
+ const row = models.find((m: AIModel) => m.name === name)
+ const source = row && 'source' in row ? row.source : undefined
+ fileInfoFor.current = name
+ const base: ModelFileInfoState = {
+ name,
+ kind: comfyKindLabel(source),
+ size: row?.size ?? 0,
+ facts: null,
+ error: null,
+ page: useModelSourceStore.getState().pageFor(name),
+ }
+ setFileInfo(base)
+ try {
+ const facts = await comfyModelInfo(name)
+ if (fileInfoFor.current === name) setFileInfo({ ...base, facts })
+ } catch (e) {
+ if (fileInfoFor.current === name) setFileInfo({ ...base, error: e instanceof Error ? e.message : String(e) })
}
}
@@ -461,6 +498,7 @@ export function ModelManager() {
total={loraRows.length}
searchQuery={searchQuery}
onDelete={(name) => setConfirmDelete(name)}
+ onInfo={(name) => { void handleFileInfo(name) }}
onGetNew={() => setTab('discover')}
/>
) : models.length === 0 ? (
@@ -671,7 +709,12 @@ export function ModelManager() {
</ModalActions>
</Modal>
+ <ModelFileInfo info={fileInfo} onClose={() => { fileInfoFor.current = null; setFileInfo(null) }} />
+
<Modal open={infoOpen} onClose={() => setInfoOpen(false)} title={typeof modelInfo?.name === 'string' && modelInfo.name ? displayModelName(modelInfo.name) : 'Model Info'}>
+ {typeof modelInfo?.error === 'string' && (
+ <p role="alert" className="t-micro text-red-500 dark:text-red-400 mb-3 break-words">{modelInfo.error}</p>
+ )}
{typeof modelInfo?.deleteHint === 'string' && (
<p className="t-label text-gray-700 dark:text-gray-200 mb-3">{modelInfo.deleteHint}</p>
)}
diff --git a/src/components/models/__tests__/models-info-d1.test.tsx b/src/components/models/__tests__/models-info-d1.test.tsx
new file mode 100644
index 00000000..b5e37b6a
--- /dev/null
+++ b/src/components/models/__tests__/models-info-d1.test.tsx
@@ -0,0 +1,229 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * D1 (a user on Discord, 01.11.2026): Models, Installed, Image. Das ⓘ neben
+ * dem Papierkorb tat bei einem ComfyUI-Modell nichts (es fragte Ollama, und
+ * `catch {}` schluckte die Antwort), LoRA-Zeilen hatten gar keins, und es gab
+ * keinen Weg zur Seite, von der die Datei kam.
+ *
+ * Gemessen an der gerenderten Seite in beiden Fassungen: der Klick oeffnet
+ * Details mit Datei, Typ, Groesse und Ordner; ein Fehler steht im Dialog; die
+ * Quellseite steht nur da, wenn LU sie beim Download notiert hat.
+ *
+ * Run: npx vitest run src/components/models/__tests__/models-info-d1.test.tsx
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { createElement } from 'react'
+import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'
+import type { AIModel } from '../../../types/models'
+
+// ── Der Unterbau, den die Seite anfasst ────────────────────────────────
+
+const openExternal = vi.fn(async (_url: string) => {})
+const comfyModelInfo = vi.fn(async (_name: string): Promise<unknown> => ({}))
+const showModel = vi.fn(async (_name: string): Promise<Record<string, unknown>> => ({}))
+const backendCall = vi.fn(async (_cmd: string, _args?: unknown) => ({ status: 'deleted' }))
+const searchCivitaiModels = vi.fn(
+ async (_query: string, _type: string, _key?: string, _host?: string) => [] as unknown[],
+)
+const startModelDownload = vi.fn(
+ async (_url: string, _subfolder: string, _filename: string) => ({ status: 'ok', id: '1' }),
+)
+const installBundleComplete = vi.fn(async (_name: string) => ({}))
+const setActiveModel = vi.fn(async () => {})
+const fetchModels = vi.fn(async () => {})
+let macHost = false
+let comfyLaeuft = true
+
+// Die Seite hat seit dem 08.10.2026 zwei Fassungen: die klassische auf
+// Windows und Linux, das Redesign auf dem Mac (skin/which.ts entscheidet).
+// Die Regeln, die diese Datei bewacht, gelten fuer beide, also laeuft jeder
+// Fall einmal je Fassung.
+const face = vi.hoisted(() => ({ name: 'classic' as 'classic' | 'mac' }))
+vi.mock('../skin/which', () => ({ modelSkinName: () => face.name }))
+
+vi.mock('../../../api/backend', () => ({
+ backendCall: (cmd: string, args?: unknown) => backendCall(cmd, args),
+ openExternal: (url: string) => openExternal(url),
+ isTauri: () => false,
+ isMacOS: () => false,
+}))
+vi.mock('../../../api/discover', () => ({
+ lookupFileMeta: () => null,
+ searchCivitaiModels: (query: string, type: string, key?: string, host?: string) =>
+ searchCivitaiModels(query, type, key, host),
+ // The panel downloads through startCivitaiDownload; for a safetensors LoRA
+ // that is exactly one startModelDownload (api/discover).
+ startCivitaiDownload: (m: { downloadUrl: string; subfolder: string; filename: string }) =>
+ startModelDownload(m.downloadUrl, m.subfolder, m.filename),
+ // The catalog LoRAs above the search (LoraAddons) ask what is on disk and
+ // install through the bundle path.
+ checkBundlesInstalled: async () => ({}),
+ // What of the CivitAI hits is on disk already: nothing here.
+ checkCivitaiInstalled: async () => new Set<number>(),
+ civitaiInstalledInFolder: () => new Set<number>(),
+ installBundleComplete: (b: { name: string }) => installBundleComplete(b.name),
+ remoteBundleNotice: () => '',
+ comfyModelInfo: (name: string) => comfyModelInfo(name),
+}))
+vi.mock('../../../api/comfyui', () => ({
+ checkComfyConnection: vi.fn(async () => comfyLaeuft),
+ refreshComfyModels: vi.fn(async () => {}),
+}))
+// In der Mac-Fassung sagt der Fuss der Leiste, was diese Maschine hat, und
+// die Fassung fragt dafuer selbst nach dem Speicher. Beide
+// Fragen gehen durch `backendCall`, das hier als Zeuge fuer das Loeschen
+// gezaehlt wird. Sie bekommen deshalb eine stumme Antwort, damit „nichts
+// geloescht" weiter „kein einziger Aufruf" heisst.
+vi.mock('../../../hooks/useGraphicsMemory', () => ({ useGraphicsMemoryGb: () => null }))
+vi.mock('../../../lib/hardware', async (orig) => ({
+ ...(await orig<typeof import('../../../lib/hardware')>()),
+ getTotalRamGb: vi.fn(async () => 0),
+}))
+vi.mock('../../../api/mlx-image', () => ({ isMlxImageHost: () => macHost }))
+vi.mock('../../../api/ollama', () => ({ showModel: (n: string) => showModel(n) }))
+vi.mock('../../../api/engine', () => ({
+ customModelDirs: () => [],
+ deleteBundledModel: vi.fn(),
+ stopBundledEngine: vi.fn(),
+}))
+vi.mock('../MacMediaLane', () => ({ MacMediaLane: () => createElement('div', null, 'mlx-panel') }))
+// Am Mac ist die LoRA-Bahn der LoRA-Ordner der Bild-Engine (MacLoraLane), nicht
+// der von ComfyUI. Hier steht ein Zeuge an ihrer Stelle; die Bahn selbst misst
+// der-mac-hat-einen-lora-ordner.test.tsx.
+vi.mock('../MacLoraLane', () => ({
+ MacLoraLane: ({ tab }: { tab: string }) => createElement('div', { 'data-testid': 'mac-lora-lane' }, `mac-lora-lane ${tab}`),
+}))
+vi.mock('../../../hooks/useMlxLoras', () => ({
+ useMlxLoras: (enabled: boolean) => ({
+ loaded: true, dir: '/data/loras', error: null, refresh: async () => {},
+ loras: enabled ? [{ name: 'qwen-detail.safetensors', sizeBytes: 1, keys: 'peft' }] : [],
+ }),
+}))
+vi.mock('../../../hooks/useMlxMedia', () => {
+ const lane = { models: [], engineReady: true, unsupported: null, engineInstall: null, modelInstall: null, queuedId: null, error: null }
+ return { useMlxMedia: () => ({ loaded: true, image: lane, video: lane, music: lane, get: () => {}, setUpEngine: () => {}, remove: async () => {}, clearError: () => {}, refresh: async () => {} }) }
+})
+vi.mock('../DiscoverModels', () => ({ DiscoverModels: () => createElement('div', null, 'discover-panel') }))
+vi.mock('../../chat/LuEngineSwitchBar', () => ({ LuEngineSwitchBar: () => null }))
+vi.mock('../../../hooks/useBuiltinEngineStatus', () => ({
+ useBuiltinEngineStatus: () => null,
+ engineIsIdle: () => false,
+}))
+
+const CHECKPOINT: AIModel = {
+ name: 'sdxl_base.safetensors', model: 'sdxl_base.safetensors', size: 6_000_000_000,
+ format: 'safetensors', architecture: 'sdxl', type: 'image', providerName: 'ComfyUI',
+ source: 'checkpoint',
+}
+const LORA: AIModel = {
+ name: 'styles/pixel_art_xl.safetensors', model: 'styles/pixel_art_xl.safetensors', size: 170_917_888,
+ format: 'safetensors', architecture: 'sdxl', type: 'image', providerName: 'ComfyUI',
+ source: 'lora',
+}
+
+let bestand: AIModel[] = []
+let lane = 'image'
+vi.mock('../../../hooks/useModels', () => ({
+ useModels: () => ({
+ models: bestand,
+ activeModel: null,
+ setActiveModel,
+ fetchModels,
+ removeModel: vi.fn(),
+ categoryFilter: lane,
+ setCategoryFilter: vi.fn(),
+ inventoryLoaded: true,
+ inventoryRefreshing: false,
+ }),
+}))
+
+import { ModelManager } from '../ModelManager'
+import { useModelSourceStore } from '../../../stores/modelSourceStore'
+
+const FACTS = {
+ path: '/c/ComfyUI/models/checkpoints/sdxl_base.safetensors',
+ folder: '/c/ComfyUI/models/checkpoints',
+ bytes: 6_938_078_334,
+ modified: 1_761_955_200,
+ ownFolder: false,
+ copies: 1,
+}
+
+beforeEach(() => {
+ macHost = false
+ comfyLaeuft = true
+ bestand = [CHECKPOINT, LORA]
+ lane = 'image'
+ comfyModelInfo.mockReset()
+ comfyModelInfo.mockResolvedValue(FACTS)
+ showModel.mockReset()
+ openExternal.mockClear()
+ useModelSourceStore.setState({ pages: {} })
+})
+afterEach(cleanup)
+
+function openImageInstalled() {
+ render(createElement(ModelManager))
+ fireEvent.click(screen.getByRole('button', { name: /^Installed/ }))
+}
+
+function detailsButtonOf(text: string): HTMLElement {
+ // Der Knopf der Zeile, in der der Name steht.
+ const row = screen.getAllByText(text)[0].closest('[data-testid="model-card"], [data-testid="lora-row"], .lu-tile') as HTMLElement
+ return within(row).getByRole('button', { name: /Details/ })
+}
+
+describe.each(['classic', 'mac'] as const)('Fassung %s', (fassung) => {
+ beforeEach(() => { face.name = fassung })
+
+ it('THE FIX: das ⓘ eines Bildmodells oeffnet Details aus der Platte, ohne Ollama', async () => {
+ openImageInstalled()
+ fireEvent.click(detailsButtonOf('sdxl_base.safetensors'))
+ const dlg = await screen.findByTestId('model-file-info')
+ expect(comfyModelInfo).toHaveBeenCalledWith('sdxl_base.safetensors')
+ expect(showModel).not.toHaveBeenCalled()
+ await waitFor(() => expect(within(dlg).getByText('/c/ComfyUI/models/checkpoints')).toBeTruthy())
+ expect(within(dlg).getByText('Checkpoint')).toBeTruthy()
+ expect(within(dlg).getByText(/6\.\d+ GB|6\.\d+ GiB|6,\d+ GB/)).toBeTruthy()
+ // Ohne notierte Quelle keine Zeile dafuer.
+ expect(screen.queryByRole('button', { name: /Open source page/ })).toBeNull()
+ })
+
+ it('ein Fehler der Platte steht im Dialog, statt still zu verschwinden', async () => {
+ comfyModelInfo.mockRejectedValue(new Error('sdxl_base.safetensors was not found in the ComfyUI models folders'))
+ openImageInstalled()
+ fireEvent.click(detailsButtonOf('sdxl_base.safetensors'))
+ const alert = await screen.findByRole('alert')
+ expect(alert.textContent).toContain('was not found in the ComfyUI models folders')
+ })
+
+ it('LoRA-Zeilen haben ein ⓘ, mit Unterordner gefragt, und die notierte Seite oeffnet', async () => {
+ useModelSourceStore.getState().record('pixel_art_xl.safetensors', 'https://civitai.com/models/120096')
+ render(createElement(ModelManager))
+ fireEvent.click(screen.getByRole('button', { name: /^LoRAs/ }))
+ fireEvent.click(screen.getByRole('button', { name: /^Installed/ }))
+ const row = screen.getAllByTestId('lora-row')[0]
+ fireEvent.click(within(row).getByRole('button', { name: /Details/ }))
+ await screen.findByTestId('model-file-info')
+ expect(comfyModelInfo).toHaveBeenCalledWith('styles/pixel_art_xl.safetensors')
+ expect(screen.getByText('LoRA')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: /Open source page/ }))
+ expect(openExternal).toHaveBeenCalledWith('https://civitai.com/models/120096')
+ })
+})
+
+describe('Ollama-Modelle', () => {
+ beforeEach(() => { face.name = 'classic' })
+
+ it('ein Fehler von Ollama wird gezeigt, nicht geschluckt', async () => {
+ bestand = [{ name: 'llama3:8b', model: 'llama3:8b', size: 4_000_000_000, type: 'text', provider: 'ollama' } as unknown as AIModel]
+ lane = 'text'
+ showModel.mockRejectedValue(new Error('connection refused'))
+ render(createElement(ModelManager))
+ fireEvent.click(screen.getByRole('button', { name: /^Installed/ }))
+ fireEvent.click(screen.getAllByRole('button', { name: /Details/ })[0])
+ const alert = await screen.findByRole('alert')
+ expect(alert.textContent).toContain('connection refused')
+ })
+})
diff --git a/src/components/models/skin/ClassicLoraManager.tsx b/src/components/models/skin/ClassicLoraManager.tsx
index 7f784bf5..75fc6e27 100644
--- a/src/components/models/skin/ClassicLoraManager.tsx
+++ b/src/components/models/skin/ClassicLoraManager.tsx
@@ -3,12 +3,12 @@
// colours are the Mac's since 10.10.2026 (see classic.tsx). The Mac face is
// ../LoraManager.tsx, which also owns the row type and the hint sentence both
// faces say. Which one is drawn is decided in skin/which.ts.
-import { Layers, Trash2 } from 'lucide-react'
+import { Info, Layers, Trash2 } from 'lucide-react'
import { parseLocalCharacterLora } from '../../../api/trainer'
import { formatBytes } from '../../../lib/formatters'
import { LORA_USE_HINT, type LoraManagerProps } from '../LoraManager'
-export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onGetNew }: LoraManagerProps) {
+export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNew }: LoraManagerProps) {
if (total === 0) {
return (
<div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">
@@ -63,6 +63,16 @@ export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onGetNe
{character && <span className="font-mono">Trigger word: {character.trigger}</span>}
</div>
</div>
+ {onInfo && (
+ <button
+ onClick={() => onInfo(row.name)}
+ title="Details"
+ aria-label={`Details of ${row.name}`}
+ className="shrink-0 p-1.5 rounded-lg text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"
+ >
+ <Info size={13} />
+ </button>
+ )}
<button
onClick={() => onDelete(row.name)}
title="Delete"
diff --git a/src/lib/__tests__/model-source-d1.test.ts b/src/lib/__tests__/model-source-d1.test.ts
new file mode 100644
index 00000000..a7646227
--- /dev/null
+++ b/src/lib/__tests__/model-source-d1.test.ts
@@ -0,0 +1,82 @@
+/**
+ * D1: the source page of a downloaded model file. Only an https page of
+ * Hugging Face or CivitAI is kept and opened; a file LU did not download, or
+ * one from before 3.0.9, has none.
+ *
+ * Run: npx vitest run src/lib/__tests__/model-source-d1.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { comfyKindLabel, isModelSourcePage, modelSourceKey, sourcePageFromDownloadUrl } from '../model-source'
+import { useModelSourceStore } from '../../stores/modelSourceStore'
+
+const backendCall = vi.fn(async (_cmd: string, _args?: unknown) => ({ status: 'started', id: 'x' }))
+vi.mock('../../api/backend', async (orig) => ({
+ ...(await orig<typeof import('../../api/backend')>()),
+ backendCall: (cmd: string, args?: unknown) => backendCall(cmd, args),
+}))
+
+beforeEach(() => {
+ useModelSourceStore.setState({ pages: {} })
+ backendCall.mockClear()
+})
+
+describe('sourcePageFromDownloadUrl', () => {
+ it('a Hugging Face file is its repository page', () => {
+ expect(sourcePageFromDownloadUrl('https://huggingface.co/Comfy-Org/flux2/resolve/main/split_files/vae/flux2-vae.safetensors?download=true'))
+ .toBe('https://huggingface.co/Comfy-Org/flux2')
+ })
+ it('a CivitAI address names a version, not a page: none', () => {
+ expect(sourcePageFromDownloadUrl('https://civitai.com/api/download/models/135867')).toBeNull()
+ })
+ it('anything else, or plain http, is none', () => {
+ expect(sourcePageFromDownloadUrl('http://huggingface.co/a/b/resolve/main/x.gguf')).toBeNull()
+ expect(sourcePageFromDownloadUrl('https://evil.test/a/b/resolve/main/x.gguf')).toBeNull()
+ expect(sourcePageFromDownloadUrl('https://huggingface.co/a/resolve/main/x.gguf')).toBeNull()
+ expect(sourcePageFromDownloadUrl('not a url')).toBeNull()
+ })
+})
+
+describe('isModelSourcePage', () => {
+ it('https Hugging Face and CivitAI only', () => {
+ expect(isModelSourcePage('https://civitai.com/models/120096')).toBe(true)
+ expect(isModelSourcePage('https://civitai.red/models/120096')).toBe(true)
+ expect(isModelSourcePage('https://huggingface.co/org/repo')).toBe(true)
+ expect(isModelSourcePage('http://civitai.com/models/1')).toBe(false)
+ expect(isModelSourcePage('https://civitai.com.evil.test/models/1')).toBe(false)
+ expect(isModelSourcePage('https://user:[email protected]/models/1')).toBe(false)
+ expect(isModelSourcePage('javascript:alert(1)')).toBe(false)
+ expect(isModelSourcePage('file:///etc/passwd')).toBe(false)
+ })
+})
+
+describe('the store', () => {
+ it('keys by file name, whatever folder the list puts in front', () => {
+ expect(modelSourceKey('loras/styles/Pixel.safetensors')).toBe('pixel.safetensors')
+ expect(modelSourceKey('chars\\x.safetensors')).toBe('x.safetensors')
+ useModelSourceStore.getState().record('Pixel.safetensors', 'https://civitai.com/models/1')
+ expect(useModelSourceStore.getState().pageFor('styles/pixel.safetensors')).toBe('https://civitai.com/models/1')
+ })
+ it('a foreign or empty page is dropped and never overwrites a known one', () => {
+ const s = useModelSourceStore.getState()
+ s.record('a.safetensors', 'https://civitai.com/models/7')
+ s.record('a.safetensors', null)
+ s.record('a.safetensors', 'https://evil.test/x')
+ expect(useModelSourceStore.getState().pageFor('a.safetensors')).toBe('https://civitai.com/models/7')
+ expect(useModelSourceStore.getState().pageFor('unknown.safetensors')).toBeNull()
+ })
+ it('THE FIX: both download starts write the page the address shows', async () => {
+ const { startModelDownload, startModelDownloadToPath } = await import('../../api/discover')
+ await startModelDownload('https://huggingface.co/org/vae/resolve/main/v.safetensors', 'vae', 'v.safetensors')
+ await startModelDownloadToPath('https://huggingface.co/org/lora/resolve/main/l.safetensors', '/m/loras', 'l.safetensors')
+ expect(useModelSourceStore.getState().pageFor('v.safetensors')).toBe('https://huggingface.co/org/vae')
+ expect(useModelSourceStore.getState().pageFor('l.safetensors')).toBe('https://huggingface.co/org/lora')
+ })
+})
+
+describe('comfyKindLabel', () => {
+ it('names the folder kinds and says nothing for an unknown one', () => {
+ expect(comfyKindLabel('lora')).toBe('LoRA')
+ expect(comfyKindLabel('checkpoint')).toBe('Checkpoint')
+ expect(comfyKindLabel(undefined)).toBeNull()
+ })
+})
diff --git a/src/lib/model-source.ts b/src/lib/model-source.ts
new file mode 100644
index 00000000..aa1445a3
--- /dev/null
+++ b/src/lib/model-source.ts
@@ -0,0 +1,72 @@
+/**
+ * Where an installed model file came from (D1, a user on Discord,
+ * 01.11.2026: "from an installed model or LoRA, jump to its CivitAI or Hugging
+ * Face page"). LU writes the page down when it starts the download; a file
+ * from before 3.0.9, or one put there by hand, has none, and the Details
+ * dialog then shows no link.
+ */
+
+const HF_HOSTS = ['huggingface.co', 'hf.co']
+const CIVITAI_HOSTS = ['civitai.com', 'civitai.red']
+
+function hostIn(host: string, list: string[]): boolean {
+ return list.some((h) => host === h || host.endsWith(`.${h}`))
+}
+
+/** Only an https page of Hugging Face or CivitAI is kept and opened. A model
+ * page is untrusted text, and this link ends in the system's browser. */
+export function isModelSourcePage(url: string): boolean {
+ try {
+ const u = new URL(url)
+ if (u.protocol !== 'https:' || u.username || u.password) return false
+ const host = u.hostname.toLowerCase()
+ return hostIn(host, HF_HOSTS) || hostIn(host, CIVITAI_HOSTS)
+ } catch {
+ return false
+ }
+}
+
+/**
+ * The page a download address belongs to, when the address shows it: a
+ * Hugging Face `…/{owner}/{repo}/resolve/…` file is that repository's page.
+ * A CivitAI download address names a version, not the page, so null: the
+ * CivitAI panels pass the page they showed instead.
+ */
+export function sourcePageFromDownloadUrl(downloadUrl: string): string | null {
+ let u: URL
+ try {
+ u = new URL(downloadUrl)
+ } catch {
+ return null
+ }
+ if (u.protocol !== 'https:' || !hostIn(u.hostname.toLowerCase(), HF_HOSTS)) return null
+ const parts = u.pathname.split('/').filter(Boolean)
+ const at = parts.indexOf('resolve')
+ if (at !== 2) return null
+ return `https://huggingface.co/${parts[0]}/${parts[1]}`
+}
+
+/** One key per file, whatever folder or subfolder the name carries: the
+ * inventory says `loras/sub/x.safetensors` or `x.safetensors`, the download
+ * knows `x.safetensors`. */
+export function modelSourceKey(filename: string): string {
+ return (filename.split(/[\\/]/).pop() ?? filename).toLowerCase()
+}
+
+/** What the Details dialog says a ComfyUI folder holds. */
+export function comfyKindLabel(source: string | undefined): string | null {
+ switch (source) {
+ case 'checkpoint': return 'Checkpoint'
+ case 'diffusion_model': return 'Diffusion model'
+ case 'motion_module': return 'Motion module'
+ case 'lora': return 'LoRA'
+ case 'vae': return 'VAE'
+ case 'text_encoder': return 'Text encoder'
+ case 'clip_vision': return 'CLIP vision'
+ case 'controlnet': return 'ControlNet'
+ case 'upscale_model': return 'Upscaler'
+ case 'embedding': return 'Embedding'
+ case 'style_model': return 'Style model'
+ default: return null
+ }
+}
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.ts
index 6801ea85..aac15859 100644
--- a/src/lib/store-backup.ts
+++ b/src/lib/store-backup.ts
@@ -60,6 +60,9 @@ export const STORE_KEYS = [
// re-downloading tens of GB
'staged-changes', 'locally-uncensored-todos', 'locally-uncensored-ui',
'lu_release_notes', 'locally-uncensored-downloads',
+ // D1 (3.0.9): the Hugging Face or CivitAI page of each downloaded model
+ // file, for "Open source page" in Models. Lost, it cannot be re-derived.
+ 'locally-uncensored-model-sources',
// Die lokale Modell-API (2.6.8). Sie MUSS hier stehen, denn sie traegt das
// einzige Geheimnis in dieser Liste: das API-Token. Geht es bei einem Update
// verloren, antwortet die API allen bereits eingerichteten Programmen des
diff --git a/src/mobile/boot/__tests__/settings-durable.test.ts b/src/mobile/boot/__tests__/settings-durable.test.ts
index ae2fce99..993644d2 100644
--- a/src/mobile/boot/__tests__/settings-durable.test.ts
+++ b/src/mobile/boot/__tests__/settings-durable.test.ts
@@ -91,6 +91,7 @@ describe('which keys are kept', () => {
'chat-models': 'the list of models, read from the device again at every start',
'create-store': 'large (the gallery), rewritten while a job runs; a running paid job is kept through lu-pending-cloud-jobs',
'locally-uncensored-downloads': 'downloads of the desktop; the phone keeps its own list on the native side',
+ 'locally-uncensored-model-sources': 'source pages of the desktop model files (D1); the phone has no Models page',
'lu-cloud-catalog': 'a cache of the cloud catalog',
'lu-cloud-gate': 'the gate pop-up of the desktop (3.0.8): a cache of the public catalogue and the model clicked there',
'lu-cloud-outage': 'which outage notice was closed (3.0.8, A28): shown once more at worst',
diff --git a/src/stores/modelSourceStore.ts b/src/stores/modelSourceStore.ts
new file mode 100644
index 00000000..ae043322
--- /dev/null
+++ b/src/stores/modelSourceStore.ts
@@ -0,0 +1,54 @@
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import { safeJSONStorage } from '../lib/storage-quota'
+import { isModelSourcePage, modelSourceKey, sourcePageFromDownloadUrl } from '../lib/model-source'
+
+/** Plenty for every model file a user keeps; the oldest go first. */
+const LIMIT = 2000
+
+interface ModelSourceState {
+ /** File name (lower case, no folder) → its Hugging Face or CivitAI page. */
+ pages: Record<string, string>
+ /** Writes the page down. A page that is not https Hugging Face or CivitAI
+ * is dropped, and so is an empty one: it never overwrites a known page. */
+ record: (filename: string, page: string | null | undefined) => void
+ pageFor: (filename: string) => string | null
+}
+
+/**
+ * D1: the source page of each downloaded model file, kept across restarts.
+ * Its own store, not the download record: that one is trimmed to the last
+ * downloads and is about resuming, not about what is installed.
+ */
+export const useModelSourceStore = create<ModelSourceState>()(persist((set, get) => ({
+ pages: {},
+ record: (filename, page) => {
+ if (!filename || !page || !isModelSourcePage(page)) return
+ const key = modelSourceKey(filename)
+ set((s) => {
+ if (s.pages[key] === page) return s
+ const next = { ...s.pages }
+ delete next[key]
+ next[key] = page
+ const keys = Object.keys(next)
+ for (const k of keys.slice(0, Math.max(0, keys.length - LIMIT))) delete next[k]
+ return { pages: next }
+ })
+ },
+ pageFor: (filename) => {
+ const page = get().pages[modelSourceKey(filename)]
+ return page && isModelSourcePage(page) ? page : null
+ },
+}), {
+ name: 'locally-uncensored-model-sources',
+ storage: safeJSONStorage(),
+ version: 1,
+ partialize: (s) => ({ pages: s.pages }) as ModelSourceState,
+ // Version 1 is the first: nothing older to carry over.
+ migrate: (persisted) => persisted as ModelSourceState,
+}))
+
+/** Called by both download starts: the page the address itself shows. */
+export function recordSourceFromDownload(filename: string, downloadUrl: string): void {
+ useModelSourceStore.getState().record(filename, sourcePageFromDownloadUrl(downloadUrl))
+}