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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(models): categories, one-click uninstall, file choice, LoRA notes, remembered page (3.1.0)
purplefa927b990b01
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.tsindex b639a7ef..6ac13f5a 100644--- a/dev-server/remote-stubs.ts+++ b/dev-server/remote-stubs.ts@@ -98,6 +98,8 @@ export function registerRemoteStubs(routes: RouteMount): void {'/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/comfy-model-reveal',+ '/local-api/bundled-model-delete-plan','/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.rsindex f32531cf..e33344d2 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -838,6 +838,77 @@ pub async fn comfy_model_info(Ok(file_facts(file, own_folder, hits.len()))}+/// C41: show a ComfyUI model file (a LoRA, a checkpoint) in the file+/// manager. Found the way Details finds it, so it can only ever point at a+/// file in the models folders or the user's own Storage folder.+#[cfg(desktop)]+#[allow(non_snake_case)]+#[tauri::command]+pub async fn comfy_model_reveal(+ 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 ({}). Open the models folder 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;+ if hits.is_empty() {+ hits = own_folder_hits(&base, &extraDirs.unwrap_or_default());+ }+ let file = hits+ .first()+ .ok_or_else(|| format!("{} was not found in the ComfyUI models folders", filename))?;+ reveal_in_file_manager(file)?;+ Ok(serde_json::json!({ "path": file.to_string_lossy() }))+}++/// The file selected in Finder or Explorer; on Linux, where there is no+/// common way to select a file, its folder.+#[cfg(desktop)]+fn reveal_in_file_manager(file: &Path) -> Result<(), String> {+ #[cfg(target_os = "macos")]+ let mut cmd = {+ let mut c = std::process::Command::new("open");+ c.arg("-R").arg(file);+ c+ };+ #[cfg(target_os = "windows")]+ let mut cmd = {+ // One argument, the comma belongs to it.+ let mut c = std::process::Command::new("explorer");+ let mut arg = std::ffi::OsString::from("/select,");+ arg.push(file.as_os_str());+ c.arg(arg);+ c+ };+ #[cfg(all(unix, not(target_os = "macos")))]+ let mut cmd = {+ let mut c = crate::process_util::foreign_system_command("xdg-open");+ c.arg(file.parent().unwrap_or(file));+ c+ };+ crate::process_util::suppress_window(&mut cmd);+ // explorer.exe answers 1 even when it worked, so only a failed spawn counts.+ cmd.spawn()+ .map(|_| ())+ .map_err(|e| format!("Could not open the folder: {}", os_error::english(&e)))+}+/// 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> {diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 98dda990..3c7200b1 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -4866,11 +4866,40 @@ pub(crate) fn gguf_delete_plan(path: &Path, roots: &[PathBuf]) -> Result<Vec<Pat/// the mapped file cannot be removed while the engine holds it, and a delete/// that half works is worse than one that says why. The frontend stops the/// engine first when the row is the active one.+/// C17: what Delete would take off the disk for an LU Engine row, without+/// taking it: every file of the model (all parts of a split set, the image+/// part) with its size. The same plan `delete_bundled_model` acts on, so the+/// dialog cannot list other files than the ones that go.+#[tauri::command]+pub async fn bundled_model_delete_plan(+ path: String,+ extra_dirs: Option<Vec<String>>,+) -> Result<serde_json::Value, String> {+ tokio::task::spawn_blocking(move || {+ let roots = bundled_scan_dirs(&builtin_models_dir()?, &extra_dirs.unwrap_or_default());+ let files = gguf_delete_plan(Path::new(&path), &roots)?;+ let rows: Vec<serde_json::Value> = files+ .iter()+ .map(|f| {+ let bytes = std::fs::metadata(f).map(|m| m.len()).unwrap_or(0);+ serde_json::json!({ "path": f.to_string_lossy(), "bytes": bytes })+ })+ .collect();+ let bytes: u64 = files.iter().map(|f| std::fs::metadata(f).map(|m| m.len()).unwrap_or(0)).sum();+ Ok(serde_json::json!({ "files": rows, "bytes": bytes }))+ })+ .await+ .map_err(|e| format!("bundled_model_delete_plan task: {e}"))?+}++/// `trash`: move the files to the system's Trash instead of deleting them+/// (C17, the uninstall dialog offers it), so a misclick can be put back.#[tauri::command]pub async fn delete_bundled_model(app: tauri::AppHandle,path: String,extra_dirs: Option<Vec<String>>,+ trash: Option<bool>,) -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(move || {let state = app.state::<AppState>();@@ -4903,10 +4932,16 @@ pub async fn delete_bundled_model(let roots = bundled_scan_dirs(&builtin_models_dir()?, &extra_dirs.unwrap_or_default());let files = gguf_delete_plan(Path::new(&path), &roots)?;let mut bytes = 0u64;+ let to_bin = trash.unwrap_or(false);for f in &files {bytes += std::fs::metadata(f).map(|m| m.len()).unwrap_or(0);- std::fs::remove_file(f)- .map_err(|e| format!("Could not delete {}: {}", f.display(), os_error::english(&e)))?;+ if to_bin {+ crate::commands::os_trash::system_trash(f)+ .map_err(|e| format!("Could not move {} to the Trash: {}", f.display(), e))?;+ } else {+ std::fs::remove_file(f)+ .map_err(|e| format!("Could not delete {}: {}", f.display(), os_error::english(&e)))?;+ }}#[cfg(desktop)]let answer = serde_json::json!({ "deleted": files.len(), "bytes": bytes });diff --git a/src-tauri/src/commands/mobile_guard.rs b/src-tauri/src/commands/mobile_guard.rsindex f31d69ec..0b340796 100644--- a/src-tauri/src/commands/mobile_guard.rs+++ b/src-tauri/src/commands/mobile_guard.rs@@ -240,6 +240,7 @@ pub const ALLOWED: &[&str] = &["swap_bundled_model","list_bundled_models","delete_bundled_model",+ "bundled_model_delete_plan","start_bundled_embed","stop_bundled_embed","bundled_embed_status",diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 0661a099..df29a538 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -959,6 +959,8 @@ pub fn run() {commands::download::check_model_sizes,commands::download::delete_comfy_model,commands::download::comfy_model_info,+ #[cfg(desktop)]+ commands::download::comfy_model_reveal,// Check files and Repair (GH #113)commands::model_verify::verify_model_files,commands::model_verify::verify_model_files_status,@@ -973,6 +975,7 @@ pub fn run() {commands::engine::swap_bundled_model,commands::engine::list_bundled_models,commands::engine::delete_bundled_model,+ commands::engine::bundled_model_delete_plan,#[cfg(desktop)]commands::engine::list_importable_models,// The user's own model folder, handed to ComfyUI (GH #122)diff --git a/src/api/__tests__/civitai-beschreibung-ist-text.test.ts b/src/api/__tests__/civitai-beschreibung-ist-text.test.tsindex 0f3f8500..06ccc0b3 100644--- a/src/api/__tests__/civitai-beschreibung-ist-text.test.ts+++ b/src/api/__tests__/civitai-beschreibung-ist-text.test.ts@@ -58,6 +58,12 @@ describe('civitaiDescriptionToText', () => {it('und die Suche schickt ihre Beschreibung wirklich durch diese Funktion', () => {const src = readFileSync(resolve(__dirname, '..', 'discover.ts'), 'utf8')- expect(src).toContain("civitaiDescriptionToText(asString(prop(item, 'description')) ?? '')")+ // C18 (3.1.0): the HTML is read once; the line of the hit and the full+ // text of the Details dialog both go through the text conversion.+ expect(src).toContain("const rawHtml = asString(prop(item, 'description')) ?? ''")+ expect(src).toContain('const rawDesc = civitaiDescriptionToText(rawHtml)')+ expect(src).toContain('fullDescription: rawHtml ? civitaiDescriptionToParagraphs(rawHtml) : undefined')+ const para = src.slice(src.indexOf('export function civitaiDescriptionToParagraphs'), src.indexOf('const CIVITAI_MODEL_FILE'))+ expect(para).toContain('return civitaiDescriptionToText(withBreaks)')})})diff --git a/src/api/__tests__/model-file-choice-c18-c21.test.ts b/src/api/__tests__/model-file-choice-c18-c21.test.tsnew file mode 100644index 00000000..366a5f5f--- /dev/null+++ b/src/api/__tests__/model-file-choice-c18-c21.test.ts@@ -0,0 +1,126 @@+// C18: the full CivitAI description reaches the Details dialog.+// C21: the user can pick the version and the file (bf16, fp8, a quant)+// instead of LU always taking the newest and first.+import { describe, it, expect } from 'vitest'+import {+ civitaiDescriptionToParagraphs, civitaiVersionChoices, civitaiHitWithFile, civitaiSubfolder,+ listGgufChoices, discoverModelForChoice, selectGgufFromTree, ggufRequestFor,+ type CivitAIModelResult, type HfTreeEntry, type DiscoverModel,+} from '../discover'++const LONG = `<p>${'Trigger word: pxl. '.repeat(20)}</p><ul><li>Strength 0.8</li><li>CFG 4</li></ul><p>Do not use with & other LoRAs.<br>Thanks!</p><script>alert(1)</script>`++describe('C18: the whole description', () => {+ it('keeps every word, far past 120 characters', () => {+ const text = civitaiDescriptionToParagraphs(LONG)+ expect(text.length).toBeGreaterThan(300)+ expect(text).toContain('Do not use with & other LoRAs.')+ })++ it('keeps paragraphs and list items as lines, and no markup', () => {+ const text = civitaiDescriptionToParagraphs(LONG)+ expect(text).toContain('\n• Strength 0.8')+ expect(text).toContain('\nThanks!')+ expect(text).not.toMatch(/<[a-z/]/i)+ })+})++const ITEM = {+ id: 7,+ name: 'Pixel LoRA',+ modelVersions: [+ {+ id: 102, name: 'v2', baseModel: 'SDXL 1.0', publishedAt: '2026-10-01T00:00:00Z',+ files: [+ { name: 'pixel_v2_fp16.safetensors', sizeKB: 1024, primary: true, downloadUrl: 'https://civitai.com/api/download/models/102?fp=fp16', metadata: { fp: 'fp16', size: 'pruned', format: 'SafeTensor' }, hashes: { SHA256: 'A'.repeat(64) } },+ { name: 'pixel_v2_fp32.safetensors', sizeKB: 2048, downloadUrl: 'https://civitai.com/api/download/models/102?fp=fp32', metadata: { fp: 'fp32', size: 'full', format: 'SafeTensor' } },+ { name: 'pixel_v2.ckpt', sizeKB: 2048, downloadUrl: 'https://civitai.com/api/download/models/102?format=PickleTensor', metadata: { format: 'PickleTensor' } },+ { name: 'training_data.zip', sizeKB: 9999, downloadUrl: 'https://civitai.com/api/download/models/102?type=Training', type: 'Training Data' },+ ],+ },+ { id: 101, name: 'v1', baseModel: 'SD 1.5', files: [{ name: 'pixel_v1.safetensors', sizeKB: 512, downloadUrl: 'https://civitai.com/api/download/models/101' }] },+ { id: 100, name: 'v0', files: [{ name: 'pixel_v0.ckpt', sizeKB: 512, downloadUrl: 'https://civitai.com/api/download/models/100' }] },+ ],+}++describe('C21: CivitAI versions and files', () => {+ it('lists every version with its model files, newest first', () => {+ const v = civitaiVersionChoices(ITEM)+ expect(v.map((x) => x.name)).toEqual(['v2', 'v1'])+ expect(v[0].files.map((f) => f.name)).toEqual(['pixel_v2_fp16.safetensors', 'pixel_v2_fp32.safetensors'])+ expect(v[0].files[0]).toMatchObject({ fp: 'fp16', size: 'pruned', format: 'SafeTensor', primary: true, sizeBytes: 1024 * 1024, sha256: 'a'.repeat(64) })+ expect(v[0].baseModel).toBe('SDXL 1.0')+ expect(v[0].published).toBe('2026-10-01')+ })++ it('THE RULE: no pickle file and no training data is offered', () => {+ const names = civitaiVersionChoices(ITEM).flatMap((v) => v.files.map((f) => f.name))+ expect(names).not.toContain('pixel_v2.ckpt')+ expect(names).not.toContain('training_data.zip')+ })++ it('the mirror host goes into every file address', () => {+ const v = civitaiVersionChoices(ITEM, 'civitai.red')+ expect(v[0].files[0].downloadUrl).toMatch(/^https:\/\/civitai\.red\//)+ })++ it('a picked file downloads as itself, into the folder of its type', () => {+ const hit: CivitAIModelResult = { id: 7, name: 'Pixel LoRA', description: '', type: 'LORA', sourceUrl: 'https://civitai.com/models/7', filename: 'pixel_v2_fp16.safetensors', subfolder: 'loras' }+ const v = civitaiVersionChoices(ITEM)+ const picked = civitaiHitWithFile(hit, v[1], v[1].files[0])+ expect(picked).toMatchObject({ filename: 'pixel_v1.safetensors', subfolder: 'loras', downloadUrl: 'https://civitai.com/api/download/models/101', versionId: 101 })+ })++ it('a GGUF checkpoint goes to diffusion_models, a LoRA named Flux to loras', () => {+ expect(civitaiSubfolder('Checkpoint', 'Some Model', 'q.gguf')).toBe('diffusion_models')+ expect(civitaiSubfolder('Checkpoint', 'Some Model', 'q.safetensors')).toBe('checkpoints')+ expect(civitaiSubfolder('LORA', 'Flux Realism', 'r.safetensors')).toBe('loras')+ })+})++const TREE: HfTreeEntry[] = [+ { type: 'file', path: 'model-Q8_0.gguf', size: 8_000 },+ { type: 'file', path: 'model-Q4_K_M.gguf', size: 4_000 },+ { type: 'file', path: 'BF16/model-BF16-00001-of-00002.gguf', size: 9_000 },+ { type: 'file', path: 'BF16/model-BF16-00002-of-00002.gguf', size: 9_000 },+ { type: 'file', path: 'Q2/model-Q2_K-00001-of-00003.gguf', size: 1_000 },+ { type: 'file', path: 'mmproj-F16.gguf', size: 600 },+ { type: 'file', path: 'README.md', size: 10 },+]++describe('C21: the GGUF files of a Hugging Face repository', () => {+ it('lists each file and each split set once, smallest first, without the image part', () => {+ const list = listGgufChoices(TREE)+ expect(list.map((c) => c.quant)).toEqual(['Q2_K', 'Q4_K_M', 'Q8_0', 'BF16'])+ const bf16 = list.find((c) => c.quant === 'BF16')!+ expect(bf16).toMatchObject({ parts: 2, totalBytes: 18_000, filename: 'model-BF16-00001-of-00002.gguf', incomplete: false })+ })++ it('a split set with missing parts is marked, not offered as loadable', () => {+ expect(listGgufChoices(TREE).find((c) => c.quant === 'Q2_K')?.incomplete).toBe(true)+ })++ it('THE FIX: the picked file is what the download resolves, never a swapped quant', () => {+ const base: DiscoverModel = {+ name: 'Test 8B', description: '', pulls: '', tags: [], updated: '',+ downloadUrl: 'https://huggingface.co/u/r/resolve/main/model-Q4_K_M.gguf', filename: 'model-Q4_K_M.gguf', sizeGB: 4, quantGuessed: true,+ }+ const pick = listGgufChoices(TREE).find((c) => c.quant === 'Q8_0')!+ const model = discoverModelForChoice(base, 'u/r', pick)+ expect(model.quantGuessed).toBe(false)+ const req = ggufRequestFor(model)!+ // A tight memory budget would swap a guessed quant; a picked one stays.+ const res = selectGgufFromTree(TREE, req.repoId, req.preferredQuant, req.exactPath, 2_000)+ expect(res?.files.map((f) => f.filename)).toEqual(['model-Q8_0.gguf'])+ expect(res?.fitSwap).toBeUndefined()+ })++ it('a picked split set brings every part', () => {+ const base: DiscoverModel = { name: 'T', description: '', pulls: '', tags: [], updated: '', downloadUrl: 'https://huggingface.co/u/r/resolve/main/model-Q4_K_M.gguf', filename: 'model-Q4_K_M.gguf' }+ const pick = listGgufChoices(TREE).find((c) => c.quant === 'BF16')!+ const req = ggufRequestFor(discoverModelForChoice(base, 'u/r', pick))!+ const res = selectGgufFromTree(TREE, req.repoId, req.preferredQuant, req.exactPath)+ expect(res?.sharded).toBe(true)+ expect(res?.files).toHaveLength(2)+ })+})diff --git a/src/api/backend.ts b/src/api/backend.tsindex 5b728695..1905f496 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -658,6 +658,10 @@ export async function backendCall<T = unknown>(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" },+ // C41 / C17: show a model file in the file manager, and what Delete would+ // take for an LU Engine row. Rust only, the dev server answers 501.+ comfy_model_reveal: { path: "/local-api/comfy-model-reveal", method: "POST" },+ bundled_model_delete_plan: { path: "/local-api/bundled-model-delete-plan", 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.tsindex ccd09eb9..93212678 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -108,6 +108,19 @@ export async function comfyModelInfo(filename: string): Promise<ComfyFileFacts>return backendCall('comfy_model_info', { filename, extraDirs: customModelDirs() })}+/** C41: show a ComfyUI model file in Finder or Explorer. Throws with the reason. */+export async function revealComfyModel(filename: string): Promise<void> {+ await backendCall('comfy_model_reveal', { filename, extraDirs: customModelDirs() })+}++/** C17: delete one ComfyUI model file, or move it to the Trash. */+export async function deleteComfyModelFile(filename: string, opts: { trash?: boolean } = {}): Promise<{ bytes: number }> {+ const res = await backendCall<{ bytes?: number }>('delete_comfy_model', {+ filename, extraDirs: customModelDirs(), ...(opts.trash ? { trash: true } : {}),+ })+ return { bytes: res?.bytes ?? 0 }+}+export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {try {return await backendCall("download_progress")@@ -1891,6 +1904,85 @@ export function selectGgufFromTree(}}+/** C21: one downloadable choice of a repository, a single file or a whole+ * split set. */+export interface GgufChoice {+ /** The path of the file (of the first part, for a split set). */+ path: string+ /** The file name the download is known by. */+ filename: string+ quant?: string+ parts: number+ totalBytes: number+ /** A split set the repository holds only some parts of. Not offered as a+ * download: llama.cpp cannot load it. */+ incomplete: boolean+}++/**+ * C21 (Discord, 31.10. and 01.11.2026): every GGUF a repository offers,+ * so the user can pick the quant instead of LU picking it. Pure; the image+ * part is no choice of its own (it comes with the model). Sorted small to+ * large, which is the order a quant table reads in.+ */+export function listGgufChoices(entries: HfTreeEntry[]): GgufChoice[] {+ const ggufs = entries.filter(e => e.type === 'file' && /\.gguf$/i.test(e.path) && !isUpstreamImagePart(e.path))+ const groups = new Map<string, GgufGroup>()+ for (const f of ggufs) {+ const key = f.path.replace(GGUF_SHARD_RE, '')+ const leaf = (f.path.split('/').pop() || '').replace(GGUF_SHARD_RE, '.gguf')+ const quant = (GGUF_QUANT_TOKEN.exec(leaf)?.[1] || GGUF_QUANT_TOKEN.exec(f.path)?.[1])?.toUpperCase()+ let g = groups.get(key)+ if (!g) { g = { key, quant, parts: [] }; groups.set(key, g) }+ g.parts.push(f)+ }+ return [...groups.values()]+ .map((g) => {+ const first = [...g.parts].sort((a, b) => a.path.localeCompare(b.path))[0]+ return {+ path: first.path,+ filename: first.path.split('/').pop() as string,+ quant: g.quant,+ parts: g.parts.length,+ totalBytes: groupBytes(g),+ incomplete: !!shardSetGap(g.parts.map(p => p.path)),+ }+ })+ .sort((a, b) => a.totalBytes - b.totalBytes || a.path.localeCompare(b.path))+}++/** C21: the GGUF choices of a Hugging Face repository, or null when its file+ * list cannot be read (offline, rate limited, gated). */+export async function fetchGgufChoices(repoId: string): Promise<GgufChoice[] | null> {+ try {+ const url = `https://huggingface.co/api/models/${repoId}/tree/main?recursive=true`+ const { isTauri, fetchExternal } = await import('./backend')+ const json = isTauri() ? await fetchExternal(url) : await (await fetch(url)).text()+ const entries = JSON.parse(json)+ return Array.isArray(entries) ? listGgufChoices(entries as HfTreeEntry[]) : null+ } catch (err) {+ log.warn('[discover] HF tree listing failed', { repoId, err })+ return null+ }+}++/** C21: a catalog or search entry, made to fetch the file the user picked.+ * The picked path is named, so the download resolves exactly that file (and+ * every part of it) and never swaps it for another quant. */+export function discoverModelForChoice(model: DiscoverModel, repoId: string, choice: GgufChoice): DiscoverModel {+ const sizeGB = choice.totalBytes > 0 ? Math.round(choice.totalBytes / 1_073_741_824 * 10) / 10 : undefined+ return {+ ...model,+ downloadUrl: `https://huggingface.co/${repoId}/resolve/main/${choice.path}`,+ filename: choice.filename,+ sizeGB,+ sizeBytes: choice.parts === 1 && choice.totalBytes > 0 ? choice.totalBytes : undefined,+ quantGuessed: false,+ // Its own checksum, not the one of the catalog's file.+ sha256: undefined,+ }+}+function groupBytes(g: GgufGroup): number {return g.parts.reduce((s, p) => s + (p.size || p.lfs?.size || 0), 0)}@@ -2247,6 +2339,37 @@ export interface CivitAIModelResult {stats?: { downloads: number; likes: number }creator?: stringsourceUrl: string+ /** C18: the whole description as text, paragraphs kept, for the Details+ * dialog. `description` above stays the one short line of the hit row. */+ fullDescription?: string+ /** C21: every version of the hit with its model files, newest first, so the+ * user can fetch another version or another precision than the default. */+ versions?: CivitaiVersionChoice[]+ /** The id of the version the default download takes (the newest). */+ versionId?: number+}++/** One downloadable model file of a CivitAI version (C21). */+export interface CivitaiFileChoice {+ name: string+ sizeBytes?: number+ downloadUrl: string+ /** CivitAI's own words for the file: fp16 / bf16 / fp8, pruned / full,+ * SafeTensor / GGUF. Shown as they are. */+ fp?: string+ size?: string+ format?: string+ /** The file CivitAI downloads for the version by default. */+ primary: boolean+ sha256?: string+}++export interface CivitaiVersionChoice {+ id: number+ name: string+ baseModel?: string+ published?: string+ files: CivitaiFileChoice[]}export const CIVITAI_DEFAULT_HOST = 'civitai.com'@@ -2333,6 +2456,92 @@ export function civitaiDescriptionToText(html: string): string {.trim()}+/**+ * C18: the full description of a CivitAI hit as readable text. The HTML is+ * reduced to its paragraphs and list items; no markup survives, so nothing of+ * CivitAI's page is ever rendered as HTML inside the app.+ */+export function civitaiDescriptionToParagraphs(html: string): string {+ const withBreaks = html+ .replace(/<\s*br\s*\/?>/gi, '\n')+ .replace(/<\s*li[^>]*>/gi, '\n• ')+ .replace(/<\/\s*(p|div|h[1-6]|li|ul|ol|blockquote|pre|tr)\s*>/gi, '\n')+ return civitaiDescriptionToText(withBreaks)+ .split('\n')+ .map((line) => line.replace(/[ \t]+/g, ' ').trim())+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .trim()+}++/** Files that load as a model. Pickle files (.ckpt, .pt, .bin) can run code+ * when they are opened, and training data, archives and configs are no+ * model, so neither is offered as a choice. */+const CIVITAI_MODEL_FILE = /\.(safetensors|sft|gguf)$/i++/** C21: the versions of one CivitAI item and their model files, pure. */+export function civitaiVersionChoices(item: unknown, host: string = CIVITAI_DEFAULT_HOST): CivitaiVersionChoice[] {+ return asRecordArray(prop(item, 'modelVersions')).map((v) => {+ const files = asRecordArray(prop(v, 'files'))+ .filter((f) => CIVITAI_MODEL_FILE.test(asString(prop(f, 'name')) ?? ''))+ .map((f): CivitaiFileChoice | null => {+ const url = civitaiHostSwap(asString(prop(f, 'downloadUrl')), host)+ const name = asString(prop(f, 'name'))+ if (!url || !name) return null+ const kb = asNumber(prop(f, 'sizeKB'))+ const sha = asString(propPath(f, 'hashes', 'SHA256'))?.toLowerCase()+ return {+ name,+ downloadUrl: url,+ sizeBytes: kb && kb > 0 ? Math.round(kb * 1024) : undefined,+ fp: asString(propPath(f, 'metadata', 'fp')) ?? undefined,+ size: asString(propPath(f, 'metadata', 'size')) ?? undefined,+ format: asString(propPath(f, 'metadata', 'format')) ?? undefined,+ primary: prop(f, 'primary') === true,+ sha256: sha && /^[0-9a-f]{64}$/.test(sha) ? sha : undefined,+ }+ })+ .filter((f): f is CivitaiFileChoice => f !== null)+ return {+ id: asNumber(prop(v, 'id')) ?? 0,+ name: asString(prop(v, 'name')) ?? 'Version',+ baseModel: asString(prop(v, 'baseModel')) ?? undefined,+ published: (asString(prop(v, 'publishedAt')) ?? asString(prop(v, 'createdAt')))?.slice(0, 10),+ files,+ }+ }).filter((v) => v.files.length > 0)+}++/** Which models folder a CivitAI file goes to. One rule for the default hit+ * and for a file the user picked (C21). */+export function civitaiSubfolder(type: string, itemName: string, filename: string): string {+ if (type === 'LORA') return 'loras'+ if (type === 'VAE') return 'vae'+ if (type === 'TextualInversion') return 'embeddings'+ // Only for a checkpoint search: the name of a LORA, a VAE or an embedding+ // says which base model it was trained against, not what kind of file it+ // is, so "Flux Realism LoRA" used to be written into diffusion_models.+ // A GGUF quant is a bare diffusion model whatever its name says, and the+ // only loader that lists .gguf (ComfyUI-GGUF's UnetLoaderGGUF) reads+ // diffusion_models/unet (a user, Discord 2026-09-23).+ const name = itemName.toLowerCase()+ if (name.includes('flux') || name.includes('wan') || name.includes('hunyuan') || isGgufFile(filename)) return 'diffusion_models'+ return 'checkpoints'+}++/** C21: the hit as it downloads with the file the user picked. */+export function civitaiHitWithFile(hit: CivitAIModelResult, version: CivitaiVersionChoice, file: CivitaiFileChoice): CivitAIModelResult {+ return {+ ...hit,+ downloadUrl: file.downloadUrl,+ filename: file.name,+ subfolder: civitaiSubfolder(hit.type, hit.name, file.name),+ sizeBytes: file.sizeBytes,+ sizeGB: file.sizeBytes ? Math.round(file.sizeBytes / 1_073_741_824 * 10) / 10 : undefined,+ versionId: version.id,+ }+}+/** A GGUF quant, read by the ComfyUI-GGUF pack and by nothing else. */export function isGgufFile(filename: string | undefined): boolean {return /\.gguf$/i.test(filename ?? '')@@ -2479,32 +2688,16 @@ export async function searchCivitaiModels(const downloadCount = asNumber(prop(stats, 'downloadCount'))const creator = asString(propPath(item, 'creator', 'username'))- // Determine subfolder based on model type- let subfolder = 'checkpoints'- if (type === 'LORA') subfolder = 'loras'- else if (type === 'VAE') subfolder = 'vae'- else if (type === 'TextualInversion') subfolder = 'embeddings'- // Check if it's a diffusion model (FLUX, Wan, etc.). Only for a- // checkpoint search: the name of a LORA, a VAE or an embedding says- // which base model it was trained against, not what kind of file it is,- // so "Flux Realism LoRA" used to be written into diffusion_models, where- // the LoRA loader does not look and the LoRA stack in Create could never- // offer it.- const name = (itemName ?? '').toLowerCase()- if (type === 'Checkpoint' && (name.includes('flux') || name.includes('wan') || name.includes('hunyuan'))) {- subfolder = 'diffusion_models'- }-const filename = asString(prop(file, 'name'))|| `${(itemName ?? '').replace(/[^a-zA-Z0-9._-]/g, '_')}.safetensors`- // A GGUF quant is a bare diffusion model whatever its name says, and the- // only loader that lists .gguf (ComfyUI-GGUF's UnetLoaderGGUF) reads- // diffusion_models/unet. In checkpoints/ nothing ever saw it (a user,- // Discord 2026-09-23: qwenImageEdit2511_q50.gguf "Complete", Installed 0).- if (type === 'Checkpoint' && isGgufFile(filename)) subfolder = 'diffusion_models'+ // The folder follows from the type, see civitaiSubfolder.+ const subfolder = civitaiSubfolder(type, itemName ?? '', filename)const descParts: string[] = []- const rawDesc = civitaiDescriptionToText(asString(prop(item, 'description')) ?? '')+ const rawHtml = asString(prop(item, 'description')) ?? ''+ const rawDesc = civitaiDescriptionToText(rawHtml)+ // The row shows one line of it; the whole text goes to the Details+ // dialog (C18), where it used to be lost to this cut.if (rawDesc) descParts.push(rawDesc.slice(0, 120))if (downloadCount) descParts.push(`${formatCount(downloadCount)} downloads`)if (creator) descParts.push(`by ${creator}`)@@ -2525,6 +2718,9 @@ export async function searchCivitaiModels(: undefined,creator,sourceUrl: `https://${host}/models/${itemId}`,+ fullDescription: rawHtml ? civitaiDescriptionToParagraphs(rawHtml) : undefined,+ versions: civitaiVersionChoices(item, host),+ versionId: asNumber(prop(version, 'id')) ?? undefined,}})} catch (err) {diff --git a/src/api/engine.ts b/src/api/engine.tsindex b261e51d..3bd5097b 100644--- a/src/api/engine.ts+++ b/src/api/engine.ts@@ -197,14 +197,25 @@ export async function startBundledEngine(modelPath: string, tuning?: BuiltinEngi/** Delete an LU Engine row's file(s): the GGUF, or every part of a split.* The backend refuses the loaded model, so the caller stops the engine first* when the row is the active one. */-export async function deleteBundledModel(path: string): Promise<{ deleted: number; bytes: number }> {+export async function deleteBundledModel(path: string, opts: { trash?: boolean } = {}): Promise<{ deleted: number; bytes: number }> {const res = await backendCall<{ deleted?: number; bytes?: number }>('delete_bundled_model', {path,extraDirs: customModelDirs(),+ ...(opts.trash ? { trash: true } : {}),})return { deleted: res?.deleted ?? 0, bytes: res?.bytes ?? 0 }}+/** C17: the files Delete takes for an LU Engine row (all parts, the image+ * part), with their sizes, before anything is deleted. */+export async function bundledModelDeletePlan(path: string): Promise<{ files: { path: string; bytes: number }[]; bytes: number }> {+ const res = await backendCall<{ files?: { path: string; bytes: number }[]; bytes?: number }>('bundled_model_delete_plan', {+ path,+ extraDirs: customModelDirs(),+ })+ return { files: res?.files ?? [], bytes: res?.bytes ?? 0 }+}+export function stopBundledEngine() {return backendCall('stop_bundled_engine')}diff --git a/src/components/create/experimental/ParamGroups.tsx b/src/components/create/experimental/ParamGroups.tsxindex 246f406c..c57003f9 100644--- a/src/components/create/experimental/ParamGroups.tsx+++ b/src/components/create/experimental/ParamGroups.tsx@@ -38,6 +38,7 @@ import { MAX_SHOTS, MAX_SHOT_CHARS, supportsMultishot } from '../../../lib/ltx-mimport { frameRangeFor, framesOnRange, lengthHint } from '../../../lib/video-length'import { LongVideoControls } from './LongVideoControls'import { useMacMemoryGb } from '../../../lib/mac-memory'+import { useLoraNotesStore, applyLoraNotes } from '../../../stores/loraNotesStore'// Video families whose dynamic-workflow strategy actually wires a LoRA node:// the generic UNET path (wan/hunyuan/ltx/mochi/cosmos) plus Wan 2.2's dedicated@@ -116,7 +117,10 @@ export function ParamGroups() {const laneType = (isVideo ? s.videoModelList : s.imageModelList).find((m) => m.name === laneModel)?.type ?? classifyModel(laneModel)const runLoras = lorasForRun(s.selectedLoras, loraList, laneType).useconst activeLoras = runLoras.length- const stackRows = loraRows(loraList, s.selectedLoras, laneType)+ // C41: the names the user gave the LoRAs in Models, and the ones hidden+ // there left out (a ticked one stays, so it can be turned off).+ const loraNotes = useLoraNotesStore((st) => st.notes)+ const stackRows = applyLoraNotes(loraRows(loraList, s.selectedLoras, laneType), loraNotes, { picked: new Set(s.selectedLoras.map((l) => l.name)) })// The search and the scroll position outlive the drawer (loraStackView.ts).const [loraQuery, setLoraQuery] = useState(() => loraStackView().query)const shownRows = filterLoraRows(stackRows, loraQuery)@@ -615,7 +619,7 @@ export function ParamGroups() {return (<div key={name} className={cn('rounded-md border transition-colors', active ? 'border-white/15 bg-white/[0.06]' : 'border-white/[0.06]')}><div className="flex items-stretch">- <button onClick={() => s.toggleLora(name)} title={file} className="flex-1 min-w-0 flex items-center justify-between gap-2 pl-2.5 pr-1 py-1.5 t-control text-left text-gray-300">+ <button onClick={() => s.toggleLora(name)} title={loraNotes[name]?.note ? `${file}\n${loraNotes[name]?.note}` : file} className="flex-1 min-w-0 flex items-center justify-between gap-2 pl-2.5 pr-1 py-1.5 t-control text-left text-gray-300"><span className="min-w-0 [overflow-wrap:anywhere]">{label}</span><span className={cn('t-mono shrink-0', active && fits ? (isMlxLocal ? 'text-emerald-600 dark:text-emerald-400' : 'text-emerald-400') : 'text-gray-600')}>{fits ? (active ? 'on' : 'off') : `${familyLabel} only`}</span></button>diff --git a/src/components/models/CivitaiHitDetails.tsx b/src/components/models/CivitaiHitDetails.tsxnew file mode 100644index 00000000..77d01c37--- /dev/null+++ b/src/components/models/CivitaiHitDetails.tsx@@ -0,0 +1,134 @@+/**+ * The Details dialog of a CivitAI hit.+ *+ * C18 (T1, 30.10.2026): the description was cut to 120 characters when the+ * hit was read, so the trigger words, the recommended settings and the+ * warnings the author wrote were nowhere in the app. The whole text stands+ * here now, as plain paragraphs (never CivitAI's HTML).+ *+ * C21 (Discord, 31.10. and 01.11.2026): Download always took the newest+ * version and its first file. A LoRA for another base model, an older version+ * that worked better, or the fp16 file instead of the fp32 one could not be+ * had. Here every version and its model files can be picked, with size and+ * CivitAI's own words for the precision.+ */+import { useMemo, useState } from 'react'+import { Download, ExternalLink } from 'lucide-react'+import { Modal } from '../ui/Modal'+import { ModalActions, ModalButton } from '../ui/ModalActions'+import { formatBytes, formatCount } from '../../lib/formatters'+import { openExternal } from '../../api/backend'+import type { CivitAIModelResult, CivitaiFileChoice, CivitaiVersionChoice } from '../../api/discover'++interface Props {+ hit: CivitAIModelResult | null+ onClose: () => void+ /** Starts the download of the picked file. */+ onDownload: (version: CivitaiVersionChoice, file: CivitaiFileChoice) => void+}++/** "fp16 · pruned · SafeTensor", from what CivitAI says about the file. */+export function civitaiFileWords(f: CivitaiFileChoice): string {+ return [f.fp, f.size, f.format].filter(Boolean).join(' · ')+}++export function CivitaiHitDetails({ hit, onClose, onDownload }: Props) {+ return (+ <Modal open={!!hit} onClose={onClose} title={hit?.name ?? 'Details'} maxWidth="max-w-2xl">+ {hit && <Body key={hit.id} hit={hit} onClose={onClose} onDownload={onDownload} />}+ </Modal>+ )+}++function Body({ hit, onClose, onDownload }: { hit: CivitAIModelResult; onClose: () => void; onDownload: Props['onDownload'] }) {+ const versions = useMemo(() => hit.versions ?? [], [hit.versions])+ const [versionId, setVersionId] = useState<number | undefined>(() => hit.versionId ?? versions[0]?.id)+ const version = versions.find((v) => v.id === versionId) ?? versions[0]+ // The file the default download takes: the primary one, else the first.+ const defaultFile = (v: CivitaiVersionChoice | undefined) => v?.files.find((f) => f.primary)?.name ?? v?.files[0]?.name+ const [fileName, setFileName] = useState<string | undefined>(() => defaultFile(version))+ const file = version?.files.find((f) => f.name === fileName) ?? version?.files[0]++ return (+ <div className="space-y-3" data-testid="civitai-details">+ <div className="flex items-center gap-2 flex-wrap t-micro text-gray-500 dark:text-gray-400">+ <span className="px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/5">{hit.type === 'LORA' ? 'LoRA' : hit.type}</span>+ {hit.creator && <span>by {hit.creator}</span>}+ {hit.stats && <span>{formatCount(hit.stats.downloads)} downloads</span>}+ </div>++ {hit.fullDescription ? (+ <div+ className="t-body leading-relaxed text-gray-700 dark:text-gray-200 whitespace-pre-line max-h-64 overflow-y-auto scrollbar-thin pr-1"+ data-testid="civitai-full-description"+ >+ {hit.fullDescription}+ </div>+ ) : (+ <p className="t-micro text-gray-500 dark:text-gray-400">The author wrote no description.</p>+ )}++ {versions.length > 0 && version && (+ <div className="space-y-2 pt-1">+ <label className="flex items-center gap-2 t-label text-gray-700 dark:text-gray-200">+ Version+ <select+ className="lu-control"+ value={version.id}+ onChange={(e) => {+ const next = versions.find((v) => v.id === Number(e.target.value))+ setVersionId(next?.id)+ setFileName(defaultFile(next))+ }}+ data-testid="civitai-version"+ >+ {versions.map((v, i) => (+ <option key={v.id} value={v.id}>+ {v.name}{v.baseModel ? ` · ${v.baseModel}` : ''}{v.published ? ` · ${v.published}` : ''}{i === 0 ? ' (newest)' : ''}+ </option>+ ))}+ </select>+ </label>+ <fieldset className="space-y-1" data-testid="civitai-files">+ <legend className="t-micro text-gray-500 dark:text-gray-400 mb-1">+ {version.files.length > 1 ? 'Files of this version. Pick the one you want.' : 'File of this version'}+ </legend>+ {version.files.map((f) => (+ <label+ key={f.name}+ className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-white/10 cursor-pointer has-[:checked]:border-gray-400 dark:has-[:checked]:border-white/30"+ >+ <input type="radio" name={`civitai-file-${hit.id}`} checked={file?.name === f.name} onChange={() => setFileName(f.name)} />+ <span className="flex-1 min-w-0">+ <span className="block truncate text-xs text-gray-900 dark:text-gray-100 font-mono">{f.name}</span>+ <span className="block t-micro text-gray-500 dark:text-gray-400">+ {[civitaiFileWords(f), f.primary ? 'default' : ''].filter(Boolean).join(' · ') || 'model file'}+ </span>+ </span>+ {f.sizeBytes ? <span className="t-micro tabular-nums text-gray-500 dark:text-gray-400 shrink-0">{formatBytes(f.sizeBytes)}</span> : null}+ </label>+ ))}+ </fieldset>+ </div>+ )}+ {versions.length === 0 && (+ <p className="t-micro text-gray-500 dark:text-gray-400">CivitAI lists no safetensors or GGUF file for this model, so LU offers no file choice for it.</p>+ )}++ <ModalActions>+ <ModalButton variant="quiet" onClick={() => openExternal(hit.sourceUrl)}>+ <ExternalLink size={12} className="inline mr-1" /> View on CivitAI+ </ModalButton>+ {version && file && (+ <ModalButton+ variant="primary"+ data-testid="civitai-download-picked"+ onClick={() => { onDownload(version, file); onClose() }}+ >+ <Download size={12} className="inline mr-1" /> Download {file.sizeBytes ? `(${formatBytes(file.sizeBytes)})` : ''}+ </ModalButton>+ )}+ </ModalActions>+ </div>+ )+}diff --git a/src/components/models/CivitaiSearchPanel.tsx b/src/components/models/CivitaiSearchPanel.tsxindex 504af3e7..e926602c 100644--- a/src/components/models/CivitaiSearchPanel.tsx+++ b/src/components/models/CivitaiSearchPanel.tsx@@ -8,9 +8,11 @@* is decided once, in `searchCivitaiModels`, from that same type.*/import { useEffect, useMemo, useRef, useState } from 'react'-import { Search, Loader2, ExternalLink, Download, CheckCircle } from 'lucide-react'+import { Search, Loader2, ExternalLink, Download, CheckCircle, Info } from 'lucide-react'import { useModelSourceStore } from '../../stores/modelSourceStore'-import { checkCivitaiInstalled, civitaiInstalledInFolder, searchCivitaiModels, startCivitaiDownload, startModelDownloadToPath, type CivitAIModelResult } from '../../api/discover'+import { checkCivitaiInstalled, civitaiHitWithFile, civitaiInstalledInFolder, searchCivitaiModels, startCivitaiDownload, startModelDownloadToPath, type CivitAIModelResult } from '../../api/discover'+import { CivitaiHitDetails } from './CivitaiHitDetails'+import { usePageMemoryStore } from '../../stores/pageMemoryStore'import { openExternal } from '../../api/backend'import { useDownloadStore } from '../../stores/downloadStore'import { useWorkflowStore } from '../../stores/workflowStore'@@ -49,15 +51,30 @@ interface Props {}export function CivitaiSearchPanel({ modelType, title, placeholder, search = '', searchSubmitToken = 0, baseModel, destDir, installed }: Props) {- const [results, setResults] = useState<CivitAIModelResult[]>([])+ // C22: the last search of this panel and its hits stay for the session.+ // Keyed by what the panel searches and where it writes (the Mac's LoRA+ // folder is its own panel).+ const memoryKey = `${modelType}|${baseModel ?? ''}|${destDir ?? ''}`+ const remembered = usePageMemoryStore.getState().civitai[memoryKey]+ const [hits, setHits] = useState<CivitAIModelResult[]>(() => remembered?.results ?? [])+ // C21: a hit whose file the user picked in Details downloads, shows its+ // progress and says Installed as that file.+ const [picked, setPicked] = useState<Record<number, CivitAIModelResult>>({})+ const results = useMemo(() => hits.map((h) => picked[h.id] ?? h), [hits, picked])+ const setResults = (next: CivitAIModelResult[], forQuery: string) => {+ setHits(next)+ setPicked({})+ usePageMemoryStore.getState().setCivitai(memoryKey, { query: forQuery, results: next })+ }+ const [details, setDetails] = useState<CivitAIModelResult | null>(null)const [searching, setSearching] = useState(false)- const [query, setQuery] = useState(search)+ const [query, setQuery] = useState(search || remembered?.query || '')// Track whether the *latest* CivitAI search has been issued at least once,// so an empty-state hint can render between "before-first-search" and// "search returned 0 hits". Without this we fall through to the silent gap// A user described: empty list, no console output, looks like the// button did nothing.- const [searched, setSearched] = useState(false)+ const [searched, setSearched] = useState(() => !!remembered)// CivitAI mirror host (#53), civitai.red for regions where .com is blocked.const civitaiHost = useWorkflowStore((s) => s.civitaiHost)const setCivitaiHost = useWorkflowStore((s) => s.setCivitaiHost)@@ -104,7 +121,7 @@ export function CivitaiSearchPanel({ modelType, title, placeholder, search = '',? await searchCivitaiModels(text, modelType, apiKey, host, { baseModel, safetensorsOnly: !!destDir }): await searchCivitaiModels(text, modelType, apiKey, host)if (mine !== searchSeq.current) return- setResults(hits)+ setResults(hits, text)setSearching(false)}@@ -198,6 +215,7 @@ export function CivitaiSearchPanel({ modelType, title, placeholder, search = '',<div className="flex items-center gap-2"><span className="text-sm font-medium text-gray-900 dark:text-white truncate">{model.name}</span>{model.sizeGB && <span className="t-micro text-gray-400 flex-shrink-0">{model.sizeGB} GB</span>}+ {picked[model.id] && <span className="t-micro text-gray-500 dark:text-gray-400 font-mono truncate" title="The file you picked in Details">{model.filename}</span>}</div>{model.description && <p className="t-micro text-gray-500 line-clamp-1 mt-0.5">{model.description}</p>}{isDl && dlState && dlState.total > 0 && (@@ -222,6 +240,21 @@ export function CivitaiSearchPanel({ modelType, title, placeholder, search = '',<Download size={14} /></button>) : null}+ <button+ onClick={() => {+ const hit = hits.find((h) => h.id === model.id) ?? model+ // The Mac's LoRA folder lists .safetensors only.+ setDetails(destDir+ ? { ...hit, versions: hit.versions?.map((v) => ({ ...v, files: v.files.filter((f) => /\.safetensors$/i.test(f.name)) })).filter((v) => v.files.length > 0) }+ : hit)+ }}+ className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 transition-colors"+ title="Details: full description, versions and files"+ aria-label={`Details of ${model.name}`}+ data-testid="civitai-details-open"+ >+ <Info size={14} />+ </button><button onClick={() => openExternal(model.sourceUrl)} className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 transition-colors" title="View on CivitAI" aria-label="View on CivitAI"><ExternalLink size={14} /></button>@@ -232,6 +265,17 @@ export function CivitaiSearchPanel({ modelType, title, placeholder, search = '',</div>)}+ <CivitaiHitDetails+ hit={details}+ onClose={() => setDetails(null)}+ onDownload={(version, file) => {+ if (!details) return+ const chosen = civitaiHitWithFile(details, version, file)+ setPicked((p) => ({ ...p, [details.id]: chosen }))+ void download(chosen)+ }}+ />+{/* Listen-Ladezustand 2 von 4: dieselbe Begruendung eine Karte weiteroben, nur mit der Zeilengeometrie der Trefferliste. */}{searching && <CivitaiResultsSkeleton />}diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsxindex e39f71ea..96c9c97b 100644--- a/src/components/models/DiscoverModels.tsx+++ b/src/components/models/DiscoverModels.tsx@@ -13,6 +13,7 @@ import {startModelDownload,installBundleComplete, remoteBundleNotice, checkBundlesOnDisk, resolveHfGgufFiles, ggufRequestFor, quantBudgetBytes, planModelDownload,imagePartFor, imagePartOf, checkDownloadSpace,+ fetchGgufChoices, discoverModelForChoice, type GgufChoice,type DiscoverModel, type DownloadProgress, type ModelBundle, type HfGgufFile, type ImagePartSource, type PlannedDownload,} from '../../api/discover'import { startPlannedDownload } from '../../api/model-download'@@ -63,6 +64,12 @@ import { CivitaiSearchPanel } from './CivitaiSearchPanel'import { ModelFileCheck, type FileCheckSubject } from './ModelFileCheck'import { bundleCheckTargets, chatModelCheckTargets, chatModelCheckable } from '../../lib/model-file-check'import { NEURONS_ENABLED } from '../../lib/features'+import { UninstallDialog, type UninstallRequest } from './UninstallDialog'+import { usePageMemoryStore, DEFAULT_DISCOVER_LANE, type DiscoverLaneMemory } from '../../stores/pageMemoryStore'+import {+ TEXT_CATEGORIES, IMAGE_CATEGORIES, VIDEO_CATEGORIES, SORTS,+ filterByCategory, categoryCounts, sortItems, type CategoryDef, type VideoItem,+} from '../../lib/discover-categories'interface Props {category: ModelCategory@@ -284,8 +291,18 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, oconst [ramGb, setRamGb] = useState<number | null>(null)// Mainstream is the default + first tab (2026-07-17) — Unfiltered is// one click away but new users land on the neutral list.- const [subTab, setSubTab] = useState<'uncensored' | 'mainstream'>('mainstream')- const [vramTier, setVramTier] = useState<SizeTier>('all')+ // C22: the filters of each lane live in the page memory, so a trip to Chat+ // or Create and back finds them as they were.+ const laneMemory: DiscoverLaneMemory = usePageMemoryStore((s) => s.discover[category]) ?? DEFAULT_DISCOVER_LANE+ const setLane = usePageMemoryStore((s) => s.setDiscoverLane)+ const subTab = laneMemory.subTab+ const setSubTab = (v: 'uncensored' | 'mainstream') => setLane(category, { subTab: v })+ const vramTier: SizeTier = laneMemory.sizeTier+ const setVramTier = (v: SizeTier) => setLane(category, { sizeTier: v })+ const categoryId = laneMemory.category+ const setCategoryId = (v: string) => setLane(category, { category: v })+ const sortId = laneMemory.sort+ const setSortId = (v: string) => setLane(category, { sort: v })// Details modal — the card shows one calm line; the FULL catalog description// (incl. per-model tips like "run thinking-OFF") lives here.const [infoModel, setInfoModel] = useState<DiscoverModel | null>(null)@@ -431,7 +448,15 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, oreturn vram > 20 // highend (open-ended)})- const filteredBundles = vramFilteredBundles+ // "Better Categories": what the bundle is for, the lanes of Create.+ const videoItems: VideoItem[] = vramFilteredBundles.map((bundle) => ({ bundle, lane: laneOf.get(bundle.name) }))+ const categorizedBundles: ModelBundle[] = isVideo+ ? filterByCategory(videoItems, VIDEO_CATEGORIES, categoryId).map((v) => v.bundle)+ : isImage ? filterByCategory(vramFilteredBundles, IMAGE_CATEGORIES, categoryId) : vramFilteredBundles+ const filteredBundles = sortItems(categorizedBundles, sortId, {+ size: (b) => b.totalSizeGB || undefined,+ name: (b) => b.name,+ })// Which model the Use button is currently loading. A GGUF start blocks for// seconds to minutes, and without this the button stayed live and a second@@ -527,6 +552,8 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o}const [installingBundle, setInstallingBundle] = useState<string | null>(null)+ // C17: the bundle whose uninstall dialog is open.+ const [uninstall, setUninstall] = useState<UninstallRequest | null>(null)const [installError, setInstallError] = useState<string | null>(null)// Kein Fehler, sondern eine Auskunft: der Nutzer hat den Download angehalten// oder abgebrochen, und die Installation sagt, was das fuer die Engine@@ -662,7 +689,13 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o}}- const [hfSearchResults, setHfSearchResults] = useState<DiscoverModel[]>([])+ // C22: the hits of the last search stay for the session, with the words+ // they were found for.+ const [hfSearchResults, setHfSearchResultsState] = useState<DiscoverModel[]>(() => usePageMemoryStore.getState().hfSearch?.results ?? [])+ const setHfSearchResults = (results: DiscoverModel[], query = '') => {+ setHfSearchResultsState(results)+ usePageMemoryStore.getState().setHfSearch(results.length ? { query, results } : null)+ }// Each Enter is a new search. Only the newest one may write the results and// end the spinner: a slow answer to an older query arriving late used to// overwrite the hits of the query now in the box.@@ -678,7 +711,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, otry {const results = await searchHuggingFaceModels(search.trim())if (mine === hfSearchSeq.current) {- setHfSearchResults(results)+ setHfSearchResults(results, search.trim())setHfSearchError(null)}} catch (err) {@@ -1035,12 +1068,23 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o// ── Derived view data for the tile grid ─────────────────────────────const activeTextModels = subTab === 'uncensored' ? filteredUncensored : filteredMainstream- const textGroups = isText ? groupModels(activeTextModels) : []+ const allTextGroups = isText ? groupModels(activeTextModels) : []+ // A card is a group of quants of one model: it belongs to a category when+ // any of its variants does (the tags of a family can differ per quant).+ const groupCategories: CategoryDef<DiscoverModel[]>[] = TEXT_CATEGORIES.map((d) => ({ ...d, match: (g: DiscoverModel[]) => g.some(d.match) }))+ const textGroups = sortItems(filterByCategory(allTextGroups, groupCategories, categoryId), sortId, {+ size: (g) => {+ const sizes = g.map((m) => modelFootprintGb(m)).filter((x): x is number => typeof x === 'number' && x > 0)+ return sizes.length ? Math.min(...sizes) : undefined+ },+ released: (g) => g.map((m) => m.released).filter((r): r is string => !!r).sort().pop(),+ name: (g) => g[0].group ?? g[0].name,+ })// "Start here" — up to 3 derived picks for the current tab. Pure derivation// from existing flags (hot/agent/lightweight) + the hardware fit; no new// catalog data and no picks while searching or filtering.- const showPicks = isText && !search && vramTier === 'all' && textGroups.length > 4+ const showPicks = isText && !search && vramTier === 'all' && categoryId === 'all' && sortId === 'recommended' && textGroups.length > 4const scoredGroups = showPicks? chatRecommendationGroups(textGroups).map(g => {@@ -1079,14 +1123,50 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o// what a click does is decided in this file, once, for both.const skin = modelSkin()+ // The category chips with their counts. Counted on the list the other+ // filters leave, so a number never promises cards the size filter hides.+ const categoryChips: { id: string; label: string; hint: string; count: number }[] = (() => {+ const pick = <T,>(items: readonly T[], defs: readonly CategoryDef<T>[]) => {+ const counts = categoryCounts(items, defs)+ return [+ { id: 'all', label: 'All', hint: 'Every model of this list', count: counts.all },+ ...defs.map((d) => ({ id: d.id, label: d.label, hint: d.hint, count: counts[d.id] ?? 0 })),+ ]+ }+ if (isText) return pick(allTextGroups, groupCategories)+ if (isVideo) return pick(videoItems, VIDEO_CATEGORIES)+ if (isImage) return pick(vramFilteredBundles, IMAGE_CATEGORIES)+ return []+ })()+ // An empty category is left out, except the one that is picked: the user+ // has to be able to see what holds the list empty and click it away.+ const shownCategoryChips = categoryChips.filter((c) => c.id === 'all' || c.count > 0 || c.id === categoryId)+ const sortChoices = SORTS.filter((o) => isText || !o.textOnly)+// The image part of the model in the details dialog: the catalog's, or for// a model the catalog does not know, the one its repository lists. That// second answer needs one request, asked when the dialog opens.const infoImagePart: ImagePartSource | null = infoModel? imagePartOf(infoModel) ?? (infoPart?.model === infoModel.name ? infoPart.part : null): null+ // C21: the files of the repository behind the model in the details dialog,+ // listed on request (one request to Hugging Face, not one per card).+ const [fileChoices, setFileChoices] = useState<{ model: string; repoId: string; list: GgufChoice[] | null; loading: boolean } | null>(null)+ const infoRepoId = (m: DiscoverModel | null): string | null => {+ if (!m || m.ollamaModel || m.canPull === false || !m.downloadUrl) return null+ return ggufRequestFor(m)?.repoId ?? null+ }+ const loadFileChoices = (m: DiscoverModel) => {+ const repoId = infoRepoId(m)+ if (!repoId) return+ setFileChoices({ model: m.name, repoId, list: null, loading: true })+ void fetchGgufChoices(repoId).then((list) => {+ setFileChoices((cur) => (cur && cur.model === m.name ? { ...cur, list, loading: false } : cur))+ })+ }const openInfo = (model: DiscoverModel) => {setInfoModel(model)+ setFileChoices(null)// The same question the download asks (`ggufRequestFor`): the file the// entry names decides, the quant is only the fallback.const request = ggufRequestFor(model)@@ -1181,6 +1261,37 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o))}</div>)}+ categories={shownCategoryChips.length > 1 && (+ <div className="flex items-center gap-2 flex-wrap" data-testid="discover-categories">+ <div className={SEGMENT_TRACK} role="group" aria-label="Category">+ {shownCategoryChips.map((c) => (+ <button+ key={c.id}+ onClick={() => setCategoryId(c.id)}+ aria-pressed={categoryId === c.id || (c.id === 'all' && !categoryChips.some((x) => x.id === categoryId))}+ title={c.hint}+ className="lu-control"+ data-testid={`discover-category-${c.id}`}+ >+ {c.label}+ <span className="opacity-60 ml-1 tabular-nums">{c.count}</span>+ </button>+ ))}+ </div>+ <label className="flex items-center gap-1.5 t-micro text-gray-500 dark:text-gray-400 ml-auto">+ Sort+ <select+ value={sortChoices.some((o) => o.id === sortId) ? sortId : 'recommended'}+ onChange={(e) => setSortId(e.target.value)}+ className="lu-control"+ aria-label="Sort models"+ data-testid="discover-sort"+ >+ {sortChoices.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}+ </select>+ </label>+ </div>+ )}hardware={{ vramGb: systemVRAM, ramGb, sharedMemory }}switchBar={<LuEngineSwitchBar />}// D-S22 · die Legende zu den Faehigkeitszeichen auf den Kacheln.@@ -1259,6 +1370,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, oonRetry={() => retryBundle(bundle)}onClear={() => clearBundle(bundle)}onCheck={() => checkBundle(bundle)}+ onUninstall={() => setUninstall({ kind: 'bundle', bundle })}onOpenUrl={(u) => openExternal(u)}/></motion.div>@@ -1268,7 +1380,9 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o)}{(isImage || isVideo) && sortedBundles.length > 0 && filteredBundles.length === 0 && (- <p className={skin.cls.sizeFilterEmpty}>No models match this size filter. Try a different one.</p>+ <p className={skin.cls.sizeFilterEmpty}>+ {categoryId !== 'all' ? 'No models match this size and category. Try another one, or All.' : 'No models match this size filter. Try a different one.'}+ </p>)}{/* CivitAI Search (Image & Video). Checkpoints here; the LoRA rail@@ -1350,6 +1464,9 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-2.5">{gridGroups.map((g, i) => renderTile(g, i))}</div>+ {activeTextModels.length > 0 && textGroups.length === 0 && (+ <p className={skin.cls.searchEmpty}>No models of this category here. Pick All, or the other catalogue.</p>+ )}{activeTextModels.length === 0 && (<p className={skin.cls.searchEmpty}>{subTab === 'uncensored' ? 'No unfiltered models match your search' : 'No mainstream models match your search'}@@ -1448,6 +1565,59 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o</span></label>)}+ {/* C21: pick the file instead of LU picking it. */}+ {infoRepoId(infoModel) && (+ <div className="space-y-1.5 pt-1" data-testid="gguf-choices">+ {!fileChoices || fileChoices.model !== infoModel.name ? (+ <button className="lu-control" onClick={() => loadFileChoices(infoModel)} data-testid="gguf-choices-load">+ Choose another file of this model…+ </button>+ ) : fileChoices.loading ? (+ <p className="t-micro text-gray-500 dark:text-gray-400">Reading the files of {fileChoices.repoId}…</p>+ ) : !fileChoices.list ? (+ <p className="t-micro text-gray-500 dark:text-gray-400">Hugging Face did not answer, so the files cannot be listed now. Try again in a moment.</p>+ ) : fileChoices.list.length === 0 ? (+ <p className="t-micro text-gray-500 dark:text-gray-400">This repository has no GGUF file.</p>+ ) : (+ <>+ <p className="t-micro text-gray-500 dark:text-gray-400">+ Files in {fileChoices.repoId}, smallest first. Get downloads the one you pick to {getTargetOf(infoModel)}.+ {chatFitGb ? ` A file well under ${Math.round(chatFitGb)} GB leaves room for the context.` : ''}+ </p>+ <div className="max-h-56 overflow-y-auto scrollbar-thin space-y-1 pr-1">+ {fileChoices.list.map((c) => {+ const gb = c.totalBytes / 1_073_741_824+ const fit = chatFitGb && gb > 0 ? computeFit(gb, chatFitGb) : null+ const current = !!infoModel.filename && infoModel.filename === c.filename+ return (+ <div key={c.path} className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-white/10" data-testid="gguf-choice">+ <span className="flex-1 min-w-0">+ <span className="block truncate text-xs font-mono text-gray-900 dark:text-gray-100" title={c.path}>{c.quant ?? c.filename}</span>+ <span className="block t-micro text-gray-500 dark:text-gray-400 truncate">+ {[c.parts > 1 ? `${c.parts} parts` : c.filename, current ? 'the file of this card' : '', fit === 'big' ? (sharedMemory ? 'too big for this Mac' : 'too big for your GPU') : fit === 'tight' ? 'tight fit' : ''].filter(Boolean).join(' · ')}+ </span>+ </span>+ <span className="t-micro tabular-nums text-gray-500 dark:text-gray-400 shrink-0">{gb > 0 ? `${gb.toFixed(1)} GB` : ''}</span>+ <button+ className="lu-control shrink-0"+ disabled={c.incomplete}+ title={c.incomplete ? 'Not every part is uploaded yet, so this file cannot load.' : `Download ${c.filename}`}+ onClick={() => {+ const picked = discoverModelForChoice(infoModel, fileChoices.repoId, c)+ setInfoModel(null)+ void handleTextDownload(picked)+ }}+ >+ {c.incomplete ? 'Incomplete' : 'Get'}+ </button>+ </div>+ )+ })}+ </div>+ </>+ )}+ </div>+ )}{infoRepoUrl(infoModel) && (<buttononClick={() => openExternal(infoRepoUrl(infoModel)!)}@@ -1460,6 +1630,15 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o)}</Modal>+ <UninstallDialog+ request={uninstall}+ onClose={() => setUninstall(null)}+ onDone={async () => {+ refreshBundleStatuses()+ await fetchModels().catch(() => {})+ }}+ />+<ModelFileChecksubject={checkSubject}onClose={() => {diff --git a/src/components/models/LoraManager.tsx b/src/components/models/LoraManager.tsxindex e864f1f5..c1efa993 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 { Info, Layers, Trash2 } from 'lucide-react'+import { Info, Layers, Trash2, Pencil, Eye, EyeOff, FolderOpen } from 'lucide-react'import { parseLocalCharacterLora } from '../../api/trainer'import { formatBytes } from '../../lib/formatters'import { ModelEmptyState, SectionHead } from './ModelPageParts'@@ -20,6 +20,12 @@ export interface LoraRow {name: string/** Bytes on disk, 0 when the size probe could not answer. */size: number+ /** C41: the name the user gave it in LU. The file keeps its own. */+ label?: string+ /** C41: the user's note (trigger words, a strength that works). */+ note?: string+ /** C41: hidden from the LoRA stack in Create. */+ hidden?: boolean}export interface LoraManagerProps {@@ -38,6 +44,88 @@ export interface LoraManagerProps {onInfo?: (name: string) => void/** Sends the user to the Get new segment of this same rail. */onGetNew: () => void+ /** C41: rename and note. Absent: no button. */+ onEdit?: (name: string) => void+ /** C41: hide from (or bring back to) the LoRA stack in Create. */+ onToggleHidden?: (name: string) => void+ /** C41: show the file in Finder or Explorer. */+ onReveal?: (name: string) => void+ /** C41: how many LoRAs are hidden, and the switch that lists them too. */+ hiddenCount?: number+ showHidden?: boolean+ onShowHidden?: (show: boolean) => void+}++/** C41: the name, the file name under it when the user gave another, and+ * the note. The same in both faces. */+export function LoraRowName({ row, nameClass }: { row: LoraRow; nameClass: string }) {+ return (+ <>+ <span className={`truncate ${nameClass}`} title={row.name}>{row.label || row.name}</span>+ {row.hidden && (+ <span className="shrink-0 px-1.5 py-0.5 rounded t-micro bg-gray-100 dark:bg-white/[0.06] text-gray-500 dark:text-gray-400" data-testid="lora-hidden-mark">+ Hidden in Create+ </span>+ )}+ </>+ )+}++/** C41: the file name (when renamed) and the note, under the name. */+export function LoraRowDetails({ row }: { row: LoraRow }) {+ if (!row.label && !row.note) return null+ return (+ <div className="mt-0.5 space-y-0.5">+ {row.label && <p className="t-micro font-mono text-gray-500 dark:text-gray-400 truncate" data-testid="lora-file-name">{row.name}</p>}+ {row.note && <p className="t-micro text-gray-600 dark:text-gray-300 whitespace-pre-line line-clamp-3" data-testid="lora-note">{row.note}</p>}+ </div>+ )+}++/** C41: the buttons a LoRA row has beside Details and Delete. */+export function LoraRowActions({ row, onEdit, onToggleHidden, onReveal, buttonClass, iconSize }: {+ row: LoraRow+ onEdit?: (name: string) => void+ onToggleHidden?: (name: string) => void+ onReveal?: (name: string) => void+ buttonClass: string+ iconSize: number+}) {+ return (+ <>+ {onEdit && (+ <button onClick={() => onEdit(row.name)} title="Rename and note" aria-label={`Rename ${row.name}`} className={buttonClass}>+ <Pencil size={iconSize} />+ </button>+ )}+ {onToggleHidden && (+ <button+ onClick={() => onToggleHidden(row.name)}+ title={row.hidden ? 'Show it in the LoRA stack of Create again' : 'Hide it from the LoRA stack of Create. The file stays.'}+ aria-label={`${row.hidden ? 'Show' : 'Hide'} ${row.name}`}+ className={buttonClass}+ >+ {row.hidden ? <Eye size={iconSize} /> : <EyeOff size={iconSize} />}+ </button>+ )}+ {onReveal && (+ <button onClick={() => onReveal(row.name)} title="Show the file in its folder" aria-label={`Show ${row.name} in its folder`} className={buttonClass}>+ <FolderOpen size={iconSize} />+ </button>+ )}+ </>+ )+}++/** C41: "Show hidden (3)", where there are hidden ones. */+export function ShowHiddenLoras({ count, show, onShow, className }: { count?: number; show?: boolean; onShow?: (v: boolean) => void; className: string }) {+ if (!onShow || !count) return null+ return (+ <label className={`flex items-center gap-1.5 shrink-0 ${className}`}>+ <input type="checkbox" checked={!!show} onChange={(e) => onShow(e.target.checked)} data-testid="lora-show-hidden" />+ Show hidden ({count})+ </label>+ )}/** The one sentence that says where a downloaded LoRA is actually used. The@@ -46,7 +134,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, onInfo, onGetNew }: LoraManagerProps) {+export function LoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNew, onEdit, onToggleHidden, onReveal, hiddenCount, showHidden, onShowHidden }: LoraManagerProps) {if (total === 0) {return (<ModelEmptyState@@ -66,7 +154,10 @@ export function LoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNreturn (<section className="space-y-2"><SectionHead level="h2" icon={<Layers size={ICON_SM} />} title="Installed LoRAs" count={rows.length} />- <p className="t-micro text-gray-500 dark:text-gray-400">{LORA_USE_HINT}</p>+ <div className="flex items-center gap-3">+ <p className="t-micro text-gray-500 dark:text-gray-400 flex-1">{LORA_USE_HINT}</p>+ <ShowHiddenLoras count={hiddenCount} show={showHidden} onShow={onShowHidden} className="t-micro text-gray-500 dark:text-gray-400" />+ </div><div className="space-y-1.5">{rows.map((row) => {const character = parseLocalCharacterLora(row.name)@@ -78,7 +169,7 @@ export function LoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetN><div className="min-w-0 flex-1"><div className="flex items-center gap-2">- <span className="truncate text-xs font-medium text-gray-900 dark:text-gray-100">{row.name}</span>+ <LoraRowName row={row} nameClass="text-xs font-medium text-gray-900 dark:text-gray-100" />{character && (// The ink in the light: the edge colour that stood here// reaches 3.37:1 on a light row, enough for a border and@@ -92,7 +183,16 @@ export function LoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetN{row.size > 0 && <span className="tabular-nums">{formatBytes(row.size)}</span>}{character && <span className="font-mono">Trigger word: {character.trigger}</span>}</div>+ <LoraRowDetails row={row} /></div>+ <LoraRowActions+ row={row}+ onEdit={onEdit}+ onToggleHidden={onToggleHidden}+ onReveal={onReveal}+ buttonClass="lu-control lu-control--icon lu-control--outline shrink-0"+ iconSize={ICON_SM}+ />{onInfo && (<buttononClick={() => onInfo(row.name)}diff --git a/src/components/models/MacLoraLane.tsx b/src/components/models/MacLoraLane.tsxindex 418128f2..65dd1a87 100644--- a/src/components/models/MacLoraLane.tsx+++ b/src/components/models/MacLoraLane.tsx@@ -20,6 +20,9 @@ import { formatBytes } from '../../lib/formatters'import { installedRowMatchesSearch } from '../../lib/model-search'import { deleteMlxLora, mlxLoraAlphaNote, mlxLoraKeysNote, openMlxLoraFolder, MLX_LORAS_CHANGED, MAC_LORA_MODELS } from '../../api/mlx-loras'import type { MlxLoraFolder } from '../../hooks/useMlxLoras'+import { useLoraNotesStore } from '../../stores/loraNotesStore'+import { usePageMemoryStore } from '../../stores/pageMemoryStore'+import { LoraRowActions, LoraRowDetails, LoraRowName, ShowHiddenLoras } from './LoraManager'/** Where a LoRA is used. The names are the labels Create shows: the drawer* "Advanced settings", the group "Expert", the list "LoRA stack". */@@ -34,9 +37,14 @@ interface Props {search: stringsearchSubmitToken: numberonGetNew: () => void+ /** C41: opens the rename-and-note dialog of the Models page. */+ onEdit?: (name: string) => void}-export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew }: Props) {+export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew, onEdit }: Props) {+ // C41: names, notes and hidden marks, the same store the other lane uses.+ const notes = useLoraNotesStore((s) => s.notes)+ const showHidden = usePageMemoryStore((s) => s.lorasShowHidden)const [removing, setRemoving] = useState<string | null>(null)const [error, setError] = useState<string | null>(null)@@ -49,6 +57,7 @@ export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew }setRemoving(null)try {await deleteMlxLora(name)+ useLoraNotesStore.getState().forget(name)} catch (e) {setError(e instanceof Error ? e.message : String(e))}@@ -106,7 +115,15 @@ export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew }if (!folder.loaded) return <ModelQuietLine>Reading your LoRA folder…</ModelQuietLine>- const rows = search ? folder.loras.filter((l) => installedRowMatchesSearch(l.name, search)) : folder.loras+ const withNotes = folder.loras.map((l) => {+ const n = notes[l.name]+ return { ...l, size: l.sizeBytes, ...(n?.label ? { label: n.label } : {}), ...(n?.note ? { note: n.note } : {}), ...(n?.hidden ? { hidden: true } : {}) }+ })+ const hiddenCount = withNotes.filter((l) => l.hidden).length+ const q = search.trim().toLowerCase()+ const rows = withNotes+ .filter((l) => showHidden || !l.hidden)+ .filter((l) => !search || installedRowMatchesSearch(l.name, search) || (!!l.label && installedRowMatchesSearch(l.label, search)) || (!!l.note && l.note.toLowerCase().includes(q)))return (<div className="space-y-4" data-testid="mac-lora-lane">@@ -127,7 +144,10 @@ export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew }) : (<section className="space-y-2"><SectionHead level="h2" icon={<Layers size={ICON_SM} />} title="Installed LoRAs" count={rows.length} />- <p className="t-micro text-gray-500 dark:text-gray-400">{MAC_LORA_USE_HINT}</p>+ <div className="flex items-center gap-3">+ <p className="t-micro text-gray-500 dark:text-gray-400 flex-1">{MAC_LORA_USE_HINT}</p>+ <ShowHiddenLoras count={hiddenCount} show={showHidden} onShow={(v) => usePageMemoryStore.getState().setLorasShowHidden(v)} className="t-micro text-gray-500 dark:text-gray-400" />+ </div><div className="space-y-1.5">{rows.map((row) => {const note = mlxLoraKeysNote(row.keys)@@ -135,13 +155,25 @@ export function MacLoraLane({ folder, tab, search, searchSubmitToken, onGetNew }return (<div key={row.name} data-testid="lora-row" className="lu-tile flex items-center gap-3 px-3.5 py-2.5"><div className="min-w-0 flex-1">- <span className="block truncate text-xs font-medium text-gray-900 dark:text-gray-100">{row.name}</span>+ <div className="flex items-center gap-2">+ <LoraRowName row={row} nameClass="text-xs font-medium text-gray-900 dark:text-gray-100" />+ </div><div className="flex flex-wrap items-center gap-x-2 mt-1 t-micro text-gray-500 dark:text-gray-400">{row.sizeBytes > 0 && <span className="tabular-nums">{formatBytes(row.sizeBytes)}</span>}{note && <span data-testid="lora-keys-note">{note}</span>}{alphaNote && <span data-testid="lora-alpha-note">{alphaNote}</span>}</div>+ <LoraRowDetails row={row} /></div>+ <LoraRowActions+ row={row}+ onEdit={onEdit}+ onToggleHidden={(name) => useLoraNotesStore.getState().setNote(name, { hidden: !notes[name]?.hidden })}+ // The Mac's LoRAs all lie in the one folder.+ onReveal={openFolder}+ buttonClass="lu-control lu-control--icon shrink-0"+ iconSize={ICON_SM}+ /><buttononClick={() => setRemoving(row.name)}title="Delete"diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsxindex d38e1015..7515309a 100644--- a/src/components/models/ModelManager.tsx+++ b/src/components/models/ModelManager.tsx@@ -37,7 +37,7 @@ import { useMlxLoras } from '../../hooks/useMlxLoras'import { modelSkin, type RailEntry } from './skin'import { useMlxMedia } from '../../hooks/useMlxMedia'import { backendCall } from '../../api/backend'-import { addGgufFile, customModelDirs, deleteBundledModel, stopBundledEngine } from '../../api/engine'+import { addGgufFile, customModelDirs } from '../../api/engine'import { counterView } from '../../lib/inventory-counter'import { groupInstalledByProvider, needsBackendSwitchHeading, foldedRowsSentence, LU_ENGINE_GROUP } from '../../lib/lu-engine-rows'import { isBuiltinEngineEntry } from '../../lib/lmstudio-match'@@ -48,6 +48,10 @@ import { useBuiltinEngineStatus, engineIsIdle } from '../../hooks/useBuiltinEngiimport { LuEngineSwitchBar } from '../chat/LuEngineSwitchBar'import type { InstalledModelLike } from '../../lib/lmstudio-match'import type { ModelCategory, AIModel } from '../../types/models'+import { usePageMemoryStore } from '../../stores/pageMemoryStore'+import { UninstallDialog, type UninstallRequest } from './UninstallDialog'+import { useLoraNotesStore } from '../../stores/loraNotesStore'+import { revealComfyModel } from '../../api/discover'// One category drives BOTH views (Discover + Installed) — the old split// discoverMode/categoryFilter pair collapsed into the persisted store value.@@ -116,24 +120,46 @@ export function ModelManager() {// der Rest ist `unknown`. Gelesen wird ohnehin nur `name` (Modal-Titel) und// das Ganze als JSON.stringify.const [modelInfo, setModelInfo] = useState<({ name: string } & Record<string, unknown>) | null>(null)+ // The plain confirm of one file: the LoRA lane (a LoRA is one file).const [confirmDelete, setConfirmDelete] = useState<string | null>(null)+ // C17: a model row's bin opens the uninstall dialog, which lists every file+ // of the model and the space it frees before anything goes.+ const [uninstall, setUninstall] = useState<UninstallRequest | 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')+ // C22: Installed or Get new, the lane and the search are the page memory's,+ // so going to Chat or Create and back lands where the user left.+ const tab = usePageMemoryStore((s) => s.modelsTab)+ const setTab = usePageMemoryStore((s) => s.setModelsTab)// Header search: always visible (no hidden magnifier), live filter +// Enter submits the HuggingFace catalog search in Discover.// A button elsewhere may open Models with a search (Neurons' "Get the// original"): it starts the field and the catalog search once.- const [searchQuery, setSearchQuery] = useState(() => useUIStore.getState().discoverQuery ?? '')+ const [searchQuery, setSearchQueryState] = useState(() => useUIStore.getState().discoverQuery ?? usePageMemoryStore.getState().modelsSearch)+ const setSearchQuery = (q: string) => {+ setSearchQueryState(q)+ usePageMemoryStore.getState().setModelsSearch(q)+ }const [searchSubmitToken, setSearchSubmitToken] = useState(() => (useUIStore.getState().discoverQuery ? 1 : 0))// That search looks for an original model: its changed versions go last.const [originalFor] = useState(() => { const s = useUIStore.getState(); return s.discoverOriginal ? s.discoverQuery : null })useEffect(() => {- if (useUIStore.getState().discoverQuery) useUIStore.getState().clearDiscoverQuery()+ const ui = useUIStore.getState()+ // A button elsewhere that opens Get new (with or without a search) wins+ // over the remembered tab: it says where it sends the user.+ if (ui.discoverQuery || ui.discoverTarget) {+ setTab('discover')+ setExtraRail(null)+ }+ if (ui.discoverQuery) {+ usePageMemoryStore.getState().setModelsSearch(ui.discoverQuery)+ ui.clearDiscoverQuery()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [])const searchInputRef = useRef<HTMLInputElement>(null)@@ -163,7 +189,8 @@ export function ModelManager() {// Mac local media is MLX: there the lane is the LoRA folder of the Mac's// image engine (MacLoraLane), which the LoRA stack in Create reads. Until// that folder existed the rail was not offered on the Mac at all.- const [extraRail, setExtraRail] = useState<'lora' | 'music' | null>(null)+ const extraRail = usePageMemoryStore((s) => s.modelsExtraRail)+ const setExtraRail = usePageMemoryStore((s) => s.setModelsExtraRail)// A Hugging Face link (HfLinkInbox) opens the Chat lane of Discover, where// its dialog lives, whatever lane or tab was open.@@ -262,6 +289,9 @@ export function ModelManager() {}const [deleteError, setDeleteError] = useState<string | null>(null)+ // C41: the rename-and-note dialog of a LoRA, and what a folder open said.+ const [loraEdit, setLoraEdit] = useState<{ name: string; label: string; note: string } | null>(null)+ const [loraNotice, setLoraNotice] = useState<string | null>(null)// D17: a GGUF from anywhere on the drive. The dialog picks it, the import// links it into the LU Engine folder, and the Installed list shows it with@@ -278,6 +308,12 @@ export function ModelManager() {setGgufNote({ ok: false, text: e instanceof Error ? e.message : String(e) })}}+ /** C17: what the uninstall dialog is asked about for this row. */+ const uninstallRequestFor = (model: AIModel): UninstallRequest => {+ if (model.type === 'image' || model.type === 'video') return { kind: 'comfy-file', name: model.name }+ if (luEngineFile(model)) return { kind: 'engine', name: displayModelName(model.name), path: model.path, active: model.name === activeModel }+ return { kind: 'ollama', name: model.name, bytes: model.size ?? 0 }+ }const handleDelete = async (name: string) => {try {const model = models.find((m: AIModel) => m.name === name)@@ -297,20 +333,15 @@ export function ModelManager() {// word.setConfirmDelete(null)useModelStore.getState().removeInventoryModel(name)+ // C41: the note of a file that is gone goes too.+ useLoraNotesStore.getState().forget(name)await refreshComfyModels().catch(() => { /* rescan is best-effort */ })await fetchModels()return}- if (model && luEngineFile(model)) {- // The loaded file is locked on Windows, so the engine is stopped first- // when the row is the active one; the backend refuses otherwise.- if (model.name === activeModel) await stopBundledEngine()- await deleteBundledModel(model.path)- setConfirmDelete(null)- await fetchModels()- return- }- await removeModel(name)+ // Every other row goes through the uninstall dialog (C17), which knows+ // the LU Engine's files and Ollama's models; this confirm is the LoRA+ // lane's, and a LoRA is a ComfyUI file.setConfirmDelete(null)} catch (e) {setDeleteError(e instanceof Error ? e.message : String(e))@@ -325,7 +356,16 @@ export function ModelManager() {// encoders and the rest of the addon folders stay exactly where they were,// since nothing else has a place to go to.const loraModels = models.filter((m: AIModel) => isLoraRow(m))- const loraRows: LoraRow[] = loraModels.map((m) => ({ name: m.name, size: m.size ?? 0 }))+ // C41: the user's names, notes and hidden marks, kept by LU beside the files.+ const loraNotes = useLoraNotesStore((s) => s.notes)+ const showHiddenLoras = usePageMemoryStore((s) => s.lorasShowHidden)+ const loraRows: LoraRow[] = loraModels.map((m) => {+ const n = loraNotes[m.name]+ return { name: m.name, size: m.size ?? 0, ...(n?.label ? { label: n.label } : {}), ...(n?.note ? { note: n.note } : {}), ...(n?.hidden ? { hidden: true } : {}) }+ })+ const hiddenLoraCount = loraRows.filter((r) => r.hidden).length+ const loraMatches = (r: LoraRow, q: string) =>+ installedRowMatchesSearch(r.name, q) || (!!r.label && installedRowMatchesSearch(r.label, q)) || (!!r.note && r.note.toLowerCase().includes(q.trim().toLowerCase()))const filteredModels = models.filter((m: AIModel) => m.type === mode && !isLoraRow(m))const modeMeta = RAIL_ITEMS.find(r => r.key === mode)!/** What the Installed counter and the Installed view are about right now. */@@ -444,6 +484,10 @@ export function ModelManager() {search={searchQuery}searchSubmitToken={searchSubmitToken}onGetNew={() => setTab('discover')}+ onEdit={(name) => {+ const n = useLoraNotesStore.getState().notes[name]+ setLoraEdit({ name, label: n?.label ?? '', note: n?.note ?? '' })+ }}/>)}@@ -494,12 +538,28 @@ export function ModelManager() {)) : rail === 'lora' ? (<skin.LoraManager- rows={searchQuery ? loraRows.filter((r) => installedRowMatchesSearch(r.name, searchQuery)) : loraRows}+ rows={loraRows+ .filter((r) => showHiddenLoras || !r.hidden)+ .filter((r) => !searchQuery || loraMatches(r, searchQuery))}total={loraRows.length}searchQuery={searchQuery}onDelete={(name) => setConfirmDelete(name)}onInfo={(name) => { void handleFileInfo(name) }}onGetNew={() => setTab('discover')}+ onEdit={(name) => {+ const n = useLoraNotesStore.getState().notes[name]+ setLoraEdit({ name, label: n?.label ?? '', note: n?.note ?? '' })+ }}+ onToggleHidden={(name) => {+ const hidden = !!useLoraNotesStore.getState().notes[name]?.hidden+ useLoraNotesStore.getState().setNote(name, { hidden: !hidden })+ }}+ onReveal={(name) => {+ revealComfyModel(name).catch((e) => setLoraNotice(e instanceof Error ? e.message : String(e)))+ }}+ hiddenCount={hiddenLoraCount}+ showHidden={showHiddenLoras}+ onShowHidden={(v) => usePageMemoryStore.getState().setLorasShowHidden(v)}/>) : models.length === 0 ? (<skin.EmptyState@@ -599,7 +659,7 @@ export function ModelManager() {// Zeile: welche davon sie bedient, entscheidet// die Karte selbst.engineStopped={engineRuht}- onDelete={() => setConfirmDelete(model.name)}+ onDelete={() => setUninstall(uninstallRequestFor(model))}onInfo={() => handleInfo(model.name)}// A14: where the file names its original weights// and is not itself a copy the tool made.@@ -675,12 +735,6 @@ export function ModelManager() {Are you sure you want to delete <span className="text-gray-900 dark:text-white font-mono">{confirmDelete ? displayModelName(confirmDelete) : null}</span>?This removes the model file from your disk and frees the space.</p>- {(() => {- const row = models.find((m: AIModel) => m.name === confirmDelete)- return row && luEngineFile(row) ? (- <p className="t-micro font-mono text-gray-500 dark:text-gray-400 mb-3 break-all" data-testid="delete-file-path">{row.path}</p>- ) : null- })()}<ModalActions><ModalButton variant="quiet" onClick={() => setConfirmDelete(null)}>Cancel@@ -691,6 +745,64 @@ export function ModelManager() {</ModalActions></Modal>+ <UninstallDialog+ request={uninstall}+ onClose={() => setUninstall(null)}+ onDone={async () => { await fetchModels() }}+ removeOllamaModel={async (name) => { await removeModel(name) }}+ />++ <Modal open={!!loraEdit} onClose={() => setLoraEdit(null)} title="Rename and note">+ {loraEdit && (+ <form+ className="space-y-3"+ data-testid="lora-edit"+ onSubmit={(e) => {+ e.preventDefault()+ useLoraNotesStore.getState().setNote(loraEdit.name, { label: loraEdit.label, note: loraEdit.note })+ setLoraEdit(null)+ }}+ >+ <p className="t-micro text-gray-500 dark:text-gray-400">+ The name is how LU shows this LoRA, here and in the LoRA stack of Create. The file keeps its own name, <span className="font-mono break-all">{loraEdit.name}</span>, so saved settings and workflows still find it.+ </p>+ <label className="block t-label text-gray-700 dark:text-gray-200">+ Name+ <input+ autoFocus+ value={loraEdit.label}+ onChange={(e) => setLoraEdit({ ...loraEdit, label: e.target.value })}+ placeholder={loraEdit.name.replace(/\.safetensors$/i, '')}+ maxLength={120}+ className="mt-1 w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-sm text-gray-900 dark:text-white"+ data-testid="lora-edit-name"+ />+ </label>+ <label className="block t-label text-gray-700 dark:text-gray-200">+ Note+ <textarea+ value={loraEdit.note}+ onChange={(e) => setLoraEdit({ ...loraEdit, note: e.target.value })}+ placeholder="Trigger words, a strength that works, what it is good for…"+ rows={4}+ maxLength={2000}+ className="mt-1 w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-sm text-gray-900 dark:text-white"+ data-testid="lora-edit-note"+ />+ </label>+ <ModalActions>+ <ModalButton variant="quiet" onClick={() => setLoraEdit(null)}>Cancel</ModalButton>+ <ModalButton variant="primary" type="submit" data-testid="lora-edit-save">Save</ModalButton>+ </ModalActions>+ </form>+ )}+ </Modal>++ <Modal open={!!loraNotice} onClose={() => setLoraNotice(null)} title="Could not open the folder">+ <p className="t-micro text-red-500 dark:text-red-400 mb-3">{loraNotice}</p>+ <ModalActions><ModalButton onClick={() => setLoraNotice(null)}>Close</ModalButton></ModalActions>+ </Modal>+<Modal open={!!deleteError} onClose={() => setDeleteError(null)} title="Delete failed"><p className="text-[0.7rem] text-red-500 dark:text-red-400 mb-3">{deleteError}</p><ModalActions>diff --git a/src/components/models/ModelTiles.tsx b/src/components/models/ModelTiles.tsxindex 05d84b8e..cbc2c091 100644--- a/src/components/models/ModelTiles.tsx+++ b/src/components/models/ModelTiles.tsx@@ -8,7 +8,7 @@ import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'import { isBelowChatMinimum, SMALL_CHAT_MODEL_WARNING } from '../../lib/chat-model-minimum'import {Download, ExternalLink, Info, Check, ChevronDown, Loader2, RefreshCw,- X, Flame, Wrench, Eye, Feather, HardDrive, FileCheck,+ X, Flame, Wrench, Eye, Feather, HardDrive, FileCheck, Trash2,} from 'lucide-react'import type { LucideIcon } from 'lucide-react'import type { DiscoverModel, DownloadProgress, ModelBundle } from '../../api/discover'@@ -689,6 +689,24 @@ export interface BundleTileProps {/** The Create tab this bundle serves, for the LU Cloud line on a bundle* that does not fit (lib/cloud-offer.ts). Absent: no line. */cloudTask?: CloudOfferTask+ /** C17: take the bundle off the disk, all its files, after a dialog that+ * lists them. Absent: no button. */+ onUninstall?: () => void+}++/** C17: the bin beside "Installed" on a bundle tile, the same in both faces. */+export function UninstallButton({ onClick, name, className = TILE_CONTROL }: { onClick: () => void; name: string; className?: string }) {+ return (+ <button+ onClick={onClick}+ className={`${className} lu-control--icon`}+ title="Uninstall: shows every file and the space it frees before anything is deleted"+ aria-label={`Uninstall ${name}`}+ data-testid="bundle-uninstall"+ >+ <Trash2 size={ICON_SM} />+ </button>+ )}/** Whether a bundle tile names LU Cloud: its model does not fit and it is@@ -835,6 +853,7 @@ export function BundleTile(props: BundleTileProps) {{bundleOffersCheck(props, plan.present) && (<CheckFilesButton onClick={props.onCheck!} label={complete} name={bundle.name} />)}+ {complete && props.onUninstall && <UninstallButton onClick={props.onUninstall} name={bundle.name} />}{complete ? (<span className={TILE_STATE}><Check size={ICON_SM} /> Installeddiff --git a/src/components/models/UninstallDialog.tsx b/src/components/models/UninstallDialog.tsxnew file mode 100644index 00000000..54b765dd--- /dev/null+++ b/src/components/models/UninstallDialog.tsx@@ -0,0 +1,244 @@+/**+ * C17: one dialog for every uninstall on the Models page.+ *+ * It opens on a request (a bundle from Get new, a row from Installed), reads+ * the disk, and shows the plan of lib/uninstall-plan.ts: every file that goes+ * with its size and place, every file that stays with the reason, and the+ * space that is freed. Only "Uninstall" deletes, and only the files in the+ * list marked to go. "Move to Trash" keeps a way back.+ */+import { useEffect, useState } from 'react'+import { Loader2, Trash2 } from 'lucide-react'+import { Modal } from '../ui/Modal'+import { ModalActions, ModalButton } from '../ui/ModalActions'+import { formatBytes } from '../../lib/formatters'+import {+ getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, getUpscaleBundles,+ checkBundlesOnDisk, comfyModelInfo, deleteComfyModelFile, type ModelBundle,+} from '../../api/discover'+import { bundledModelDeletePlan, deleteBundledModel, stopBundledEngine } from '../../api/engine'+import { refreshComfyModels } from '../../api/comfyui'+import { useDownloadStore } from '../../stores/downloadStore'+import { useModelStore } from '../../stores/modelStore'+import {+ bundleUninstallPlan, bundlesWithFile, engineUninstallPlan, installedFileUninstallPlan, ollamaUninstallPlan,+ type FileOnDisk, type UninstallPlan,+} from '../../lib/uninstall-plan'++export type UninstallRequest =+ | { kind: 'bundle'; bundle: ModelBundle }+ | { kind: 'comfy-file'; name: string }+ | { kind: 'engine'; name: string; path: string; active: boolean }+ | { kind: 'ollama'; name: string; bytes: number }++interface Props {+ request: UninstallRequest | null+ onClose: () => void+ /** After the files are gone: the lists read the disk again. */+ onDone: () => Promise<void> | void+ /** Deletes an Ollama model through the model store. */+ removeOllamaModel?: (name: string) => Promise<void>+}++function allBundles(): ModelBundle[] {+ return [...getImageBundles(), ...getVideoBundles(), ...getAudioBundles(), ...getLipsyncBundles(), ...getMotionBundles(), ...getUpscaleBundles()]+}++/** What the disk says about each file of the given bundles. */+async function filesOnDisk(names: readonly string[]): Promise<Map<string, FileOnDisk | null>> {+ const out = new Map<string, FileOnDisk | null>()+ await Promise.all([...new Set(names)].map(async (n) => {+ try {+ const f = await comfyModelInfo(n)+ out.set(n, { path: f.path, bytes: f.bytes, ownFolder: f.ownFolder, copies: f.copies })+ } catch {+ out.set(n, null)+ }+ }))+ return out+}++export async function buildUninstallPlan(request: UninstallRequest): Promise<UninstallPlan> {+ if (request.kind === 'engine') {+ const { files } = await bundledModelDeletePlan(request.path)+ return engineUninstallPlan(request.name, files)+ }+ if (request.kind === 'ollama') return ollamaUninstallPlan(request.name, request.bytes)+ const bundles = allBundles()+ const { installed } = await checkBundlesOnDisk(bundles)+ if (request.kind === 'bundle') {+ const disk = await filesOnDisk(request.bundle.files.map((f) => f.filename ?? '').filter(Boolean))+ return bundleUninstallPlan(request.bundle, bundles, installed, disk)+ }+ const owners = bundlesWithFile(request.name, bundles)+ const names = [request.name, ...owners.flatMap((b) => b.files.map((f) => f.filename ?? ''))].filter(Boolean)+ const disk = await filesOnDisk(names)+ return installedFileUninstallPlan(request.name, bundles, installed, disk)+}++type Phase =+ | { at: 'reading' }+ | { at: 'plan'; plan: UninstallPlan }+ | { at: 'working'; plan: UninstallPlan }+ | { at: 'done'; plan: UninstallPlan; freed: number; failed: string[]; trashed: boolean }+ | { at: 'error'; message: string }++/** One key per request object, so a new request starts the dialog's inner+ * part from scratch (reading the disk again) without a reset in an effect. */+const requestKeys = new WeakMap<object, number>()+let nextKey = 1+function keyOf(request: UninstallRequest): number {+ let k = requestKeys.get(request)+ if (!k) { k = nextKey++; requestKeys.set(request, k) }+ return k+}++export function UninstallDialog(props: Props) {+ const { request } = props+ return request ? <UninstallBody key={keyOf(request)} {...props} request={request} /> : null+}++function UninstallBody({ request, onClose, onDone, removeOllamaModel }: Props & { request: UninstallRequest }) {+ const [phase, setPhase] = useState<Phase>({ at: 'reading' })+ const [toTrash, setToTrash] = useState(false)++ useEffect(() => {+ let live = true+ buildUninstallPlan(request)+ .then((plan) => { if (live) setPhase({ at: 'plan', plan }) })+ .catch((e) => { if (live) setPhase({ at: 'error', message: e instanceof Error ? e.message : String(e) }) })+ return () => { live = false }+ }, [request])++ const run = async (plan: UninstallPlan) => {+ setPhase({ at: 'working', plan })+ const failed: string[] = []+ let freed = 0+ const going = plan.files.filter((f) => f.action === 'delete')+ if (plan.kind === 'engine' && request.kind === 'engine') {+ try {+ // The loaded file is locked on Windows: the engine lets go of it first.+ if (request.active) await stopBundledEngine()+ const res = await deleteBundledModel(request.path, { trash: toTrash })+ freed = res.bytes+ } catch (e) {+ failed.push(e instanceof Error ? e.message : String(e))+ }+ } else if (plan.kind === 'ollama' && removeOllamaModel) {+ try {+ await removeOllamaModel(plan.title)+ freed = plan.freeBytes+ } catch (e) {+ failed.push(e instanceof Error ? e.message : String(e))+ }+ } else {+ for (const f of going) {+ try {+ const res = await deleteComfyModelFile(f.ref, { trash: toTrash })+ freed += res.bytes || f.bytes+ // Its row in the download list would claim the file is still there.+ useDownloadStore.getState().dismiss(f.ref)+ useModelStore.getState().removeInventoryModel(f.ref)+ } catch (e) {+ failed.push(`${f.label}: ${e instanceof Error ? e.message : String(e)}`)+ }+ }+ await refreshComfyModels().catch(() => { /* the rescan is best effort */ })+ // The bundle cards of Get new ask the disk again on this event.+ window.dispatchEvent(new CustomEvent('comfyui-model-downloaded'))+ }+ await Promise.resolve(onDone()).catch(() => {})+ setPhase({ at: 'done', plan, freed, failed, trashed: toTrash })+ }++ const title = phase.at === 'plan' || phase.at === 'working' || phase.at === 'done' ? `Uninstall ${phase.plan.title}` : 'Uninstall'++ return (+ <Modal open onClose={() => { if (phase.at !== 'working') onClose() }} title={title} maxWidth="max-w-xl">+ <div data-testid="uninstall-dialog">+ {phase.at === 'reading' && (+ <p className="t-body text-gray-500 dark:text-gray-400 flex items-center gap-2"><Loader2 size={14} className="animate-spin" /> Looking for the files of this model…</p>+ )}+ {phase.at === 'error' && (+ <>+ <p role="alert" className="t-body text-red-500 dark:text-red-400">{phase.message}</p>+ <ModalActions><ModalButton onClick={onClose}>Close</ModalButton></ModalActions>+ </>+ )}+ {(phase.at === 'plan' || phase.at === 'working') && (() => {+ const { plan } = phase+ const going = plan.files.filter((f) => f.action === 'delete')+ const kept = plan.files.filter((f) => f.action === 'keep')+ return (+ <>+ {going.length === 0 ? (+ <p className="t-body text-gray-700 dark:text-gray-200">Nothing of this model can be removed here.{kept.length === 0 ? ' Its files are not on this disk.' : ''}</p>+ ) : (+ <p className="t-body text-gray-700 dark:text-gray-200" data-testid="uninstall-summary">+ {going.length === 1 ? 'This file goes' : `These ${going.length} files go`}, and <span className="font-semibold text-gray-900 dark:text-white tabular-nums">{formatBytes(plan.freeBytes)}</span> {toTrash ? 'move to the Trash' : 'are freed'}:+ </p>+ )}+ <ul className="mt-2 space-y-1 max-h-60 overflow-y-auto scrollbar-thin pr-1" data-testid="uninstall-files">+ {going.map((f) => (+ <li key={f.ref} className="flex items-start gap-2 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-white/10" data-testid="uninstall-file-delete">+ <Trash2 size={12} className="mt-0.5 shrink-0 text-gray-400" />+ <span className="flex-1 min-w-0">+ <span className="block text-xs text-gray-900 dark:text-gray-100 truncate">{f.label}</span>+ {f.path && <span className="block t-micro font-mono text-gray-500 dark:text-gray-400 break-all">{f.path}</span>}+ </span>+ {f.bytes > 0 && <span className="t-micro tabular-nums text-gray-500 dark:text-gray-400 shrink-0">{formatBytes(f.bytes)}</span>}+ </li>+ ))}+ </ul>+ {kept.length > 0 && (+ <>+ <p className="t-micro text-gray-500 dark:text-gray-400 mt-3 mb-1">Stays on the disk:</p>+ <ul className="space-y-1" data-testid="uninstall-files-kept">+ {kept.map((f) => (+ <li key={f.ref} className="px-2.5 py-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.03]" data-testid="uninstall-file-keep">+ <span className="block text-xs text-gray-700 dark:text-gray-300 truncate">{f.label}{f.bytes > 0 ? ` · ${formatBytes(f.bytes)}` : ''}</span>+ <span className="block t-micro text-gray-500 dark:text-gray-400">{f.reason}</span>+ </li>+ ))}+ </ul>+ </>+ )}+ {plan.note && <p className="t-micro text-gray-600 dark:text-gray-300 mt-3">{plan.note}</p>}+ {plan.kind !== 'ollama' && going.length > 0 && (+ <label className="flex items-center gap-2 mt-3 t-micro text-gray-700 dark:text-gray-200">+ <input type="checkbox" checked={toTrash} onChange={(e) => setToTrash(e.target.checked)} disabled={phase.at === 'working'} data-testid="uninstall-to-trash" />+ Move to the Trash instead, so they can be put back. The space is freed when the Trash is emptied.+ </label>+ )}+ <ModalActions>+ <ModalButton variant="quiet" onClick={onClose} disabled={phase.at === 'working'}>Cancel</ModalButton>+ {going.length > 0 && (+ <ModalButton variant="danger" onClick={() => { void run(plan) }} disabled={phase.at === 'working'} data-testid="uninstall-confirm">+ {phase.at === 'working' ? 'Uninstalling…' : `Uninstall (${formatBytes(plan.freeBytes)})`}+ </ModalButton>+ )}+ </ModalActions>+ </>+ )+ })()}+ {phase.at === 'done' && (+ <>+ {phase.failed.length === 0 ? (+ <p className="t-body text-gray-700 dark:text-gray-200" data-testid="uninstall-done">+ {phase.plan.title} is uninstalled. {formatBytes(phase.freed)} {phase.trashed ? 'moved to the Trash.' : 'freed.'}+ </p>+ ) : (+ <>+ <p className="t-body text-gray-700 dark:text-gray-200">{phase.freed > 0 ? `${formatBytes(phase.freed)} ${phase.trashed ? 'moved to the Trash' : 'freed'}, but not everything could go:` : 'Nothing could be removed:'}</p>+ <ul className="mt-2 space-y-1">+ {phase.failed.map((m) => <li key={m} role="alert" className="t-micro text-red-500 dark:text-red-400 break-words">{m}</li>)}+ </ul>+ </>+ )}+ <ModalActions><ModalButton onClick={onClose}>Close</ModalButton></ModalActions>+ </>+ )}+ </div>+ </Modal>+ )+}diff --git a/src/components/models/__tests__/die-lu-engine-zeile-hat-einen-eimer.test.ts b/src/components/models/__tests__/die-lu-engine-zeile-hat-einen-eimer.test.tsindex 54f87ed0..f33ee853 100644--- a/src/components/models/__tests__/die-lu-engine-zeile-hat-einen-eimer.test.ts+++ b/src/components/models/__tests__/die-lu-engine-zeile-hat-einen-eimer.test.ts@@ -28,18 +28,32 @@ describe('an LU Engine row can be deleted', () => {expect(canDelete).toContain('|| luEngineFile(model)')})+ // C17 (3.1.0): the bin opens the uninstall dialog, which reads the files+ // of the model from the backend and deletes them there.+ const DIALOG = fs.readFileSync(path.join(__dirname, '..', 'UninstallDialog.tsx'), 'utf8')++ it('the row asks the uninstall dialog about its file, and whether it is loaded', () => {+ const req = slice(MANAGER, 'const uninstallRequestFor', 'const handleDelete')+ expect(req).toContain("if (luEngineFile(model)) return { kind: 'engine', name: displayModelName(model.name), path: model.path, active: model.name === activeModel }")+ })+it('the loaded model is stopped before its file goes, and the list is re-read after', () => {- const branch = slice(MANAGER, 'if (model && luEngineFile(model)) {\n // The loaded file', 'await removeModel(name)')- const stop = branch.indexOf('if (model.name === activeModel) await stopBundledEngine()')- const del = branch.indexOf('await deleteBundledModel(model.path)')- const reread = branch.indexOf('await fetchModels()')+ const branch = slice(DIALOG, "if (plan.kind === 'engine'", "} else if (plan.kind === 'ollama'")+ const stop = branch.indexOf('if (request.active) await stopBundledEngine()')+ const del = branch.indexOf('await deleteBundledModel(request.path, { trash: toTrash })')expect(stop).toBeGreaterThan(0)expect(del).toBeGreaterThan(stop)- expect(reread).toBeGreaterThan(del)+ const after = slice(DIALOG, "if (plan.kind === 'engine'", "setPhase({ at: 'done'")+ expect(after).toContain('await Promise.resolve(onDone())')+ expect(MANAGER).toContain('onDone={async () => { await fetchModels() }}')})- it('the confirm dialog names the file that goes', () => {- expect(MANAGER).toContain('data-testid="delete-file-path"')+ it('the dialog names every file that goes, from the same plan the delete acts on', () => {+ expect(DIALOG).toContain('const { files } = await bundledModelDeletePlan(request.path)')+ expect(DIALOG).toContain('data-testid="uninstall-file-delete"')+ expect(DIALOG).toContain('{f.path && <span')+ const plan = slice(RUST, 'pub async fn bundled_model_delete_plan', 'pub async fn delete_bundled_model')+ expect(plan).toContain('gguf_delete_plan(Path::new(&path), &roots)?')})it('Details on an LU Engine row is the file, not a question to Ollama', () => {@@ -57,6 +71,9 @@ describe('an LU Engine row can be deleted', () => {it('the backend refuses the loaded model and judges the path after canonicalize', () => {const cmd = slice(RUST, 'pub async fn delete_bundled_model', 'fn list_bundled_models_blocking')+ // C17: the plan command reads, it deletes nothing.+ const readOnly = slice(RUST, 'pub async fn bundled_model_delete_plan', 'pub async fn delete_bundled_model')+ expect(readOnly).not.toContain('remove_file')expect(cmd).toContain('This model is loaded in the LU Engine right now.')expect(cmd).toContain('gguf_delete_plan(Path::new(&path), &roots)?')const plan = slice(RUST, 'pub(crate) fn gguf_delete_plan', 'pub async fn delete_bundled_model')diff --git a/src/components/models/__tests__/models-komfort-310.test.tsx b/src/components/models/__tests__/models-komfort-310.test.tsxnew file mode 100644index 00000000..d1d8096f--- /dev/null+++ b/src/components/models/__tests__/models-komfort-310.test.tsx@@ -0,0 +1,174 @@+/**+ * @vitest-environment jsdom+ *+ * 3.1.0, Models comfort (Discord feature requests), on the rendered+ * page:+ * - "Better Categories": the chips filter Get new by what a model is for.+ * - C22: the filters of a lane survive leaving the page and coming back.+ * - C17: a bundle's bin opens a dialog that lists every file and the space,+ * keeps a file another installed model needs, and deletes only on Uninstall.+ *+ * Lauf: npx vitest run src/components/models/__tests__/models-komfort-310.test.tsx+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, cleanup, waitFor, fireEvent, within } from '@testing-library/react'++const backendCall = vi.hoisted(() => vi.fn(async (_cmd: string, _args?: unknown): Promise<unknown> => []))++vi.mock('../../../api/backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/backend')>()),+ backendCall,+ openExternal: vi.fn(),+ isTauri: () => false,+ isMacOS: () => false,+}))+vi.mock('../../../api/comfyui', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../api/comfyui')>()),+ getSystemVRAM: vi.fn(async () => 24),+ readComfyFolderLists: vi.fn(async () => ({})),+ refreshComfyModels: vi.fn(async () => {}),+}))+vi.mock('../../../hooks/useModels', () => ({+ useModels: () => ({ pullModel: vi.fn(), models: [], fetchModels: async () => {}, setActiveModel: vi.fn() }),+}))+vi.mock('../../../lib/hardware', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../lib/hardware')>()),+ getMaxVramGb: vi.fn(async () => 24),+ getTotalRamGb: vi.fn(async () => 64),+}))+vi.mock('../CivitaiSearchPanel', () => ({ CivitaiSearchPanel: () => null }))+vi.mock('../../chat/LuEngineSwitchBar', () => ({ LuEngineSwitchBar: () => null }))++// The disk of the test: which bundle files exist, and how big.+const onDisk = vi.hoisted(() => new Map<string, number>())+vi.mock('../../../api/discover', async (importOriginal) => {+ const real = await importOriginal<typeof import('../../../api/discover')>()+ return {+ ...real,+ checkBundlesOnDisk: vi.fn(async (bundles: import('../../../api/discover').ModelBundle[]) => {+ const installed: Record<string, boolean> = {}+ const files = new Set<string>()+ for (const b of bundles) {+ const fs = b.files.filter((f) => f.filename)+ for (const f of fs) if (onDisk.has(f.filename!)) files.add(f.filename!)+ installed[b.name] = fs.length > 0 && fs.every((f) => onDisk.has(f.filename!))+ }+ return { installed, files }+ }),+ comfyModelInfo: vi.fn(async (name: string) => {+ if (!onDisk.has(name)) throw new Error('not found')+ return { path: `/test-models/${name}`, folder: '/test-models', bytes: onDisk.get(name)!, modified: null, ownFolder: false, copies: 1 }+ }),+ deleteComfyModelFile: vi.fn(async (name: string) => {+ const bytes = onDisk.get(name) ?? 0+ onDisk.delete(name)+ return { bytes }+ }),+ }+})++import { DiscoverModels } from '../DiscoverModels'+import * as discover from '../../../api/discover'+import { getVideoBundles } from '../../../api/discover'++beforeEach(() => {+ onDisk.clear()+ backendCall.mockClear()+ vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} })+})+afterEach(() => { cleanup(); vi.unstubAllGlobals() })++// The page opens on Mainstream; a bundle marked uncensored is under Unfiltered.+const MAINSTREAM_VIDEO = getVideoBundles().find((b) => !b.uncensored && !b.i2v && b.tags.includes('Quality'))!.name++describe('Better Categories', () => {+ it('the Video tab filters to Music and back to All', async () => {+ render(<DiscoverModels category="video" />)+ const music = await screen.findByTestId('discover-category-music')+ expect(music.textContent).toMatch(/Music\s*\d+/)+ fireEvent.click(music)+ expect(music.getAttribute('aria-pressed')).toBe('true')+ await waitFor(() => {+ const text = document.body.textContent ?? ''+ expect(text).toContain('ACE Step 1.5')+ // A video model is filtered away.+ expect(text).not.toContain(MAINSTREAM_VIDEO)+ })+ fireEvent.click(screen.getByTestId('discover-category-all'))+ await waitFor(() => expect(document.body.textContent).toContain(MAINSTREAM_VIDEO))+ })++ it('C22: the category of a lane is still picked after leaving and coming back', async () => {+ const first = render(<DiscoverModels category="video" />)+ fireEvent.click(await screen.findByTestId('discover-category-music'))+ fireEvent.change(screen.getByTestId('discover-sort'), { target: { value: 'smallest' } })+ first.unmount()+ render(<DiscoverModels category="video" />)+ expect((await screen.findByTestId('discover-category-music')).getAttribute('aria-pressed')).toBe('true')+ expect((screen.getByTestId('discover-sort') as HTMLSelectElement).value).toBe('smallest')+ })++ it('GEGENPROBE: each lane keeps its own filter', async () => {+ const first = render(<DiscoverModels category="video" />)+ fireEvent.click(await screen.findByTestId('discover-category-music'))+ first.unmount()+ render(<DiscoverModels category="image" />)+ expect((await screen.findByTestId('discover-category-all')).getAttribute('aria-pressed')).toBe('true')+ })+})++describe('C17: uninstall a bundle with all its files', () => {+ // Two installed bundles that share their text encoder and VAE.+ const pick = () => {+ const all = getVideoBundles().filter((b) => !b.uncensored)+ const byFile = new Map<string, string[]>()+ for (const b of all) for (const f of b.files) if (f.filename) byFile.set(f.filename, [...(byFile.get(f.filename) ?? []), b.name])+ const a = all.find((b) => b.files.some((f) => f.filename && (byFile.get(f.filename)?.length ?? 0) > 1) && b.files.some((f) => f.filename && byFile.get(f.filename)?.length === 1))!+ const shared = a.files.find((f) => f.filename && (byFile.get(f.filename)?.length ?? 0) > 1)!+ const other = all.find((b) => b.name !== a.name && b.files.some((f) => f.filename === shared.filename))!+ return { a, other, shared }+ }++ it('lists the files, keeps the shared one, frees only what is the model\'s own', async () => {+ const { a, other, shared } = pick()+ for (const f of [...a.files, ...other.files]) if (f.filename) onDisk.set(f.filename, 1_000_000)+ render(<DiscoverModels category="video" />)+ const tile = await waitFor(() => {+ const bins = screen.getAllByTestId('bundle-uninstall')+ const bin = bins.find((b) => b.getAttribute('aria-label') === `Uninstall ${a.name}`)+ if (!bin) throw new Error('no bin yet')+ return bin+ })+ fireEvent.click(tile)+ const dialog = await screen.findByTestId('uninstall-dialog')+ await within(dialog).findByTestId('uninstall-summary')+ const kept = within(dialog).getAllByTestId('uninstall-file-keep').map((e) => e.textContent ?? '')+ expect(kept.some((t) => t.includes(other.name))).toBe(true)+ const going = within(dialog).getAllByTestId('uninstall-file-delete')+ expect(going.length).toBeGreaterThan(0)+ // Nothing is deleted before the click.+ expect(discover.deleteComfyModelFile).not.toHaveBeenCalled()+ fireEvent.click(within(dialog).getByTestId('uninstall-confirm'))+ await within(dialog).findByTestId('uninstall-done')+ const deleted = vi.mocked(discover.deleteComfyModelFile).mock.calls.map((c) => c[0])+ expect(deleted).not.toContain(shared.filename)+ expect(onDisk.has(shared.filename!)).toBe(true)+ })++ it('GEGENPROBE: Cancel deletes nothing', async () => {+ const { a } = pick()+ for (const f of a.files) if (f.filename) onDisk.set(f.filename, 5)+ vi.mocked(discover.deleteComfyModelFile).mockClear()+ render(<DiscoverModels category="video" />)+ const bin = await waitFor(() => {+ const b = screen.getAllByTestId('bundle-uninstall').find((x) => x.getAttribute('aria-label') === `Uninstall ${a.name}`)+ if (!b) throw new Error('no bin yet')+ return b+ })+ fireEvent.click(bin)+ const dialog = await screen.findByTestId('uninstall-dialog')+ await within(dialog).findByTestId('uninstall-summary')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))+ expect(discover.deleteComfyModelFile).not.toHaveBeenCalled()+ })+})diff --git a/src/components/models/__tests__/vier-glyphen-ein-chip-ein-schatten.test.ts b/src/components/models/__tests__/vier-glyphen-ein-chip-ein-schatten.test.tsindex aa4792d6..7047db1a 100644--- a/src/components/models/__tests__/vier-glyphen-ein-chip-ein-schatten.test.ts+++ b/src/components/models/__tests__/vier-glyphen-ein-chip-ein-schatten.test.ts@@ -373,19 +373,23 @@ describe('D-S25 · zwei Segmented-Sprachen 47px uebereinander', () => {expect(rows).toContain('aria-label="Size"')})+ // Seit 3.1.0 (Better Categories, Discord 09.11.2026) gibt es eine dritte+ // Reihe, die Kategorien. Sie spricht dieselbe Sprache: dieselbe Spur,+ // dasselbe Segment, Zustand aus aria-pressed. Die Sortierung daneben ist+ // ein `select` mit demselben Rezept.it('beide Reihen stehen in derselben Spur', () => {- expect((rows.match(/className=\{SEGMENT_TRACK\}/g) ?? []).length).toBe(2)+ expect((rows.match(/className=\{SEGMENT_TRACK\}/g) ?? []).length).toBe(3)expect(SCREEN).toMatch(/const SEGMENT_TRACK\s*=/)})it('beide Reihen benutzen dasselbe Segment-Rezept', () => {// Vier Mainstream-/Unfiltered- plus sechs Groessen-Segmente, alle// `className="lu-control"` ohne Zusatz.- expect((rows.match(/className="lu-control"/g) ?? []).length).toBe(3)+ expect((rows.match(/className="lu-control"/g) ?? []).length).toBe(5)})it('kein Segment faerbt sich mehr selbst — der Zustand kommt aus aria-pressed', () => {- expect((rows.match(/aria-pressed=/g) ?? []).length).toBe(3)+ expect((rows.match(/aria-pressed=/g) ?? []).length).toBe(4)expect(rows).not.toMatch(/subTab === '(mainstream|uncensored)'\s*\n?\s*\?\s*'bg-/)expect(rows).not.toMatch(/vramTier === tier\.key\s*\n?[^\n]*\n?\s*\?\s*'bg-/)})diff --git a/src/components/models/skin/ClassicLoraManager.tsx b/src/components/models/skin/ClassicLoraManager.tsxindex 75fc6e27..0b80b9fa 100644--- a/src/components/models/skin/ClassicLoraManager.tsx+++ b/src/components/models/skin/ClassicLoraManager.tsx@@ -6,9 +6,9 @@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'+import { LORA_USE_HINT, LoraRowActions, LoraRowDetails, LoraRowName, ShowHiddenLoras, type LoraManagerProps } from '../LoraManager'-export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNew }: LoraManagerProps) {+export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo, onGetNew, onEdit, onToggleHidden, onReveal, hiddenCount, showHidden, onShowHidden }: LoraManagerProps) {if (total === 0) {return (<div className="flex flex-col items-center justify-center text-center py-16 px-6 gap-3">@@ -38,6 +38,7 @@ export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo,<h2 className="t-micro font-semibold uppercase tracking-[0.12em] text-gray-700 dark:text-gray-300">LoRAs</h2><span className="text-[0.55rem] text-gray-500 dark:text-gray-400 tabular-nums">{rows.length}</span><div className="flex-1 h-px bg-gray-200 dark:bg-white/[0.07]" />+ <ShowHiddenLoras count={hiddenCount} show={showHidden} onShow={onShowHidden} className="t-micro text-gray-500 dark:text-gray-400" /></div><p className="px-1 text-[0.55rem] text-gray-500 dark:text-gray-400">{LORA_USE_HINT}</p><div className="space-y-1.5">@@ -51,7 +52,7 @@ export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo,><div className="min-w-0 flex-1"><div className="flex items-center gap-2">- <span className="truncate t-control text-gray-900 dark:text-gray-100">{row.name}</span>+ <LoraRowName row={row} nameClass="t-control text-gray-900 dark:text-gray-100" />{character && (<span className="shrink-0 px-1.5 py-0.5 rounded t-micro border border-lu-accent/30 bg-lu-accent-soft text-lu-accent-ink dark:text-lu-accent">Character@@ -62,7 +63,16 @@ export function ClassicLoraManager({ rows, total, searchQuery, onDelete, onInfo,{row.size > 0 && <span className="tabular-nums">{formatBytes(row.size)}</span>}{character && <span className="font-mono">Trigger word: {character.trigger}</span>}</div>+ <LoraRowDetails row={row} /></div>+ <LoraRowActions+ row={row}+ onEdit={onEdit}+ onToggleHidden={onToggleHidden}+ onReveal={onReveal}+ buttonClass="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"+ iconSize={13}+ />{onInfo && (<buttononClick={() => onInfo(row.name)}diff --git a/src/components/models/skin/ClassicTiles.tsx b/src/components/models/skin/ClassicTiles.tsxindex d3a48d14..874cda04 100644--- a/src/components/models/skin/ClassicTiles.tsx+++ b/src/components/models/skin/ClassicTiles.tsx@@ -18,7 +18,7 @@ import { tierMarks } from '../../../lib/render/model-tier'import { ICON_SM } from '../../ui/icon-size'import {FIT_META, FitHint, CapIcons, HotMark, computeFit, shortBlurb, variantLabel,- useModelTile, bundleTileFacts, bundleOffersCloud, bundleOffersCheck, CheckFilesButton,+ useModelTile, bundleTileFacts, bundleOffersCloud, bundleOffersCheck, CheckFilesButton, UninstallButton,type ModelTileProps, type BundleTileProps,} from '../ModelTiles'import { CloudOfferLine } from '../../cloud/CloudOffer'@@ -318,6 +318,7 @@ export function ClassicBundleTile(props: BundleTileProps) {{bundleOffersCheck(props, plan.present) && (<CheckFilesButton onClick={props.onCheck!} label={complete} name={bundle.name} className={TILE_CONTROL} />)}+ {complete && props.onUninstall && <UninstallButton onClick={props.onUninstall} name={bundle.name} className={TILE_CONTROL} />}{complete ? (<span className={TILE_STATE}><Check size={ICON_SM} /> Installeddiff --git a/src/components/models/skin/classic.tsx b/src/components/models/skin/classic.tsxindex 5421c3d2..0982f0ea 100644--- a/src/components/models/skin/classic.tsx+++ b/src/components/models/skin/classic.tsx@@ -297,7 +297,7 @@ function ClassicHead({ place, title, Icon, count, note }: HeadProps) {/** Two rows: which catalogue with the hardware chip beside it, then how big.* All four pieces are children of the page's spaced column, as they were. */-function ClassicFilterBar({ catalogue, sizes, hardware, switchBar, legend }: FilterBarProps) {+function ClassicFilterBar({ catalogue, sizes, categories, hardware, switchBar, legend }: FilterBarProps) {return (<><div className="flex items-center gap-2 flex-wrap">@@ -310,6 +310,8 @@ function ClassicFilterBar({ catalogue, sizes, hardware, switchBar, legend }: Fil{sizes}+ {categories}+{switchBar}{legend && <CapLegend sharedMemory={hardware.sharedMemory} ink={CLASSIC_CAP_LEGEND} />}diff --git a/src/components/models/skin/mac.tsx b/src/components/models/skin/mac.tsxindex 5d63a8e5..8d8aeb93 100644--- a/src/components/models/skin/mac.tsx+++ b/src/components/models/skin/mac.tsx@@ -288,7 +288,7 @@ function MacHead({ place, title, Icon, count, note }: HeadProps) {/** One row since 08.10.2026: which catalogue, then how big. They stood in two* rows with the hardware chip floating beside the first one. Narrow windows* break the row between the two groups. */-function MacFilterBar({ catalogue, sizes, hardware, switchBar, legend }: FilterBarProps) {+function MacFilterBar({ catalogue, sizes, categories, hardware, switchBar, legend }: FilterBarProps) {return (<div><div className="flex items-center gap-2 flex-wrap">@@ -300,6 +300,8 @@ function MacFilterBar({ catalogue, sizes, hardware, switchBar, legend }: FilterB</div></div>+ {categories && <div className="mt-2">{categories}</div>}+{/* The box of the switch line is always in the tree (it is a liveregion), so it gets its distance only while it holds a sentence. As achild of the spaced column it left a gap of two row distances underdiff --git a/src/components/models/skin/types.ts b/src/components/models/skin/types.tsindex b5ccd1c4..0e4e4dd5 100644--- a/src/components/models/skin/types.ts+++ b/src/components/models/skin/types.ts@@ -74,6 +74,10 @@ export interface FilterBarProps {catalogue: ReactNode/** The size filter, or nothing where the lane has none. */sizes: ReactNode+ /** What the models are for (Agent, Coding, Edit, Music, …) and how they are+ * sorted ("Better Categories", Discord 09.11.2026). Its own row in both+ * faces: it is the widest of the controls and wraps on its own. */+ categories?: ReactNodehardware: { vramGb: number | null; ramGb: number | null; sharedMemory: boolean }/** The line that says a pick moved the chat backend. Always in the tree. */switchBar: ReactNodediff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 09736816..178aa856 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef, type ReactNode, type ChangeEvent } from 'react'+import { useState, useEffect, useLayoutEffect, useRef, type ReactNode, type ChangeEvent } from 'react'import { withDetail } from '../../lib/error-text'// `X` steht hier weiterhin, obwohl der Sprachabschnitt mit seinen Symbolen// nach ./SpeechSettings.tsx gezogen ist: der Dismiss-Knopf der ComfyUI-Notiz@@ -92,6 +92,7 @@ import { TEMPERATURE_MAX, TEMPERATURE_HELP, TEMPERATURE_HELP_LABEL } from '../..import { HighTemperatureWarning } from '../chat/HighTemperatureWarning'import { BoundedNumberInput } from './BoundedNumberInput'import { CONTEXT_WINDOW_MAX, MAX_TOKENS_MAX, SUB_AGENT_LIMIT_MAX } from '../../lib/number-limits'+import { usePageMemoryStore } from '../../stores/pageMemoryStore'// ── User profile picture (Appearance) ───────────────────────────// Self-contained like HfDownloadPathSetting. Stores the picture as a@@ -176,7 +177,13 @@ function HowtoRow({ topic }: { topic: string }) {}function Section({ title, children, defaultOpen = false }: { title: string; children: ReactNode; defaultOpen?: boolean }) {- const [open, setOpen] = useState(defaultOpen)+ // C22: a section the user opened or closed stays so on the next visit of+ // this session, instead of folding back each time Chat was looked at.+ const [open, setOpenState] = useState(() => usePageMemoryStore.getState().settingsSections[title] ?? defaultOpen)+ const setOpen = (v: boolean) => {+ setOpenState(v)+ usePageMemoryStore.getState().setSettingsSection(title, v)+ }const [animating, setAnimating] = useState(false)return (// D-S27: `id` + `scroll-mt` machen die Sektion zum Sprungziel der Rail.@@ -203,7 +210,10 @@ function Section({ title, children, defaultOpen = false }: { title: string; chil</span><ChevronRight size={12} className={`text-gray-400 transition-transform duration-200 ${open ? 'rotate-90' : ''}`} /></button>- <AnimatePresence>+ {/* initial={false}: a section that is open when the page mounts (its+ default, or remembered from the last visit, C22) is simply there,+ so the scroll position can be put back at once. */}+ <AnimatePresence initial={false}>{open && (<motion.divid={`${sectionAnchorId(title)}-body`}@@ -1753,6 +1763,29 @@ export function SettingsPage() {// initial value, so a focus that vanished from the store on the next render// would fold the section straight back up (Nebenbefund 3, R8 re-measure).const [entryFocus] = useState(() => useUIStore.getState().settingsFocus)+ // C22: a button that sends the user to a section opens it, whatever the+ // memory of this session says about it. Once, before the sections mount.+ useState(() => {+ const titles: Record<string, string> = { comfyui: 'ComfyUI (Image & Video)', 'comfyui-nodes': 'ComfyUI node packs' }+ const title = entryFocus?.section ? titles[entryFocus.section] : undefined+ if (title) usePageMemoryStore.getState().forgetSettingsSection(title)+ return null+ })+ // C22: where the page was scrolled to, put back on the next visit of the+ // session. Not when a button sent the user to a section: that one scrolls.+ const scrollRef = useRef<HTMLDivElement>(null)+ useLayoutEffect(() => {+ const el = scrollRef.current+ if (!el) return+ if (!entryFocus) {+ const top = usePageMemoryStore.getState().settingsScroll+ if (top > 0) el.scrollTop = top+ }+ const save = () => usePageMemoryStore.getState().setSettingsScroll(el.scrollTop)+ el.addEventListener('scroll', save, { passive: true })+ return () => el.removeEventListener('scroll', save)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])useEffect(() => { useUIStore.getState().clearSettingsFocus() }, [])// The node pack section sits below the long ComfyUI section, so a button// that sends the user there (the workflow import) also scrolls to it.@@ -1796,7 +1829,7 @@ export function SettingsPage() {}return (- <div className="h-full overflow-y-auto scrollbar-thin">+ <div ref={scrollRef} className="h-full overflow-y-auto scrollbar-thin">{/* D-S27 / D-S48: vorher `max-w-lg mx-auto`, eine 552px-Spalte, die inder Fenstermitte schwebte und bei 1600px links und rechts je ~524pxLeere stehen liess. Die Zeilenlaenge war richtig, die Aufhaengungdiff --git a/src/lib/__tests__/discover-categories.test.ts b/src/lib/__tests__/discover-categories.test.tsnew file mode 100644index 00000000..b35b8233--- /dev/null+++ b/src/lib/__tests__/discover-categories.test.ts@@ -0,0 +1,101 @@+// "Better Categories" (Discord 09.11.2026): Get new sorts and+// filters by what a model is for, the lanes of Create. Held against the real+// catalog, so a new entry that falls through every category shows up here.+import { describe, it, expect } from 'vitest'+import {+ TEXT_CATEGORIES, IMAGE_CATEGORIES, VIDEO_CATEGORIES,+ filterByCategory, categoryCounts, sortItems, isAddonBundle,+} from '../discover-categories'+import {+ getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles,+ getUncensoredTextModels, getMainstreamTextModels, type DiscoverModel,+} from '../../api/discover'++const lanes = new Map<string, string>([+ ...getAudioBundles().map((b) => [b.name, 'Music'] as const),+ ...getLipsyncBundles().map((b) => [b.name, 'Lip sync'] as const),+ ...getMotionBundles().map((b) => [b.name, 'Motion'] as const),+])+const videoItems = [...getVideoBundles(), ...getAudioBundles(), ...getLipsyncBundles(), ...getMotionBundles()]+ .map((bundle) => ({ bundle, lane: lanes.get(bundle.name) }))++describe('every catalog entry has a place', () => {+ it('each image bundle is in at least one category', () => {+ const lost = getImageBundles().filter((b) => !IMAGE_CATEGORIES.some((c) => c.match(b)))+ expect(lost.map((b) => b.name)).toEqual([])+ })++ it('each bundle of the Video tab is in at least one category', () => {+ const lost = videoItems.filter((v) => !VIDEO_CATEGORIES.some((c) => c.match(v)))+ expect(lost.map((v) => v.bundle.name)).toEqual([])+ })++ it('the lanes of Create are their own categories on the Video tab', () => {+ const music = filterByCategory(videoItems, VIDEO_CATEGORIES, 'music').map((v) => v.bundle.name)+ expect(music.length).toBe(getAudioBundles().length)+ expect(filterByCategory(videoItems, VIDEO_CATEGORIES, 'lipsync').length).toBe(getLipsyncBundles().length)+ expect(filterByCategory(videoItems, VIDEO_CATEGORIES, 'motion').length).toBe(getMotionBundles().length)+ // GEGENPROBE: a song model is no text-to-video model.+ const t2v = filterByCategory(videoItems, VIDEO_CATEGORIES, 't2v').map((v) => v.bundle.name)+ for (const m of music) expect(t2v).not.toContain(m)+ })++ it('an image-to-video model is filed under Image to video', () => {+ const i2v = filterByCategory(videoItems, VIDEO_CATEGORIES, 'i2v').map((v) => v.bundle)+ expect(i2v.length).toBeGreaterThan(0)+ expect(i2v.every((b) => b.i2v || b.tags.includes('I2V'))).toBe(true)+ })++ it('add-ons (LoRAs, VAEs, companion files) are no text-to-image model', () => {+ const addons = getImageBundles().filter(isAddonBundle)+ expect(addons.length).toBeGreaterThan(0)+ const generate = filterByCategory(getImageBundles(), IMAGE_CATEGORIES, 'generate')+ for (const a of addons) expect(generate).not.toContain(a)+ })++ it('the edit models are found under Edit', () => {+ const edit = filterByCategory(getImageBundles(), IMAGE_CATEGORIES, 'edit').map((b) => b.name)+ expect(edit.some((n) => /Qwen-Image 2\.1/.test(n))).toBe(true)+ })++ it('the chat catalog has agents, vision and coding models', () => {+ const all = [...getUncensoredTextModels(), ...getMainstreamTextModels()]+ const counts = categoryCounts(all, TEXT_CATEGORIES)+ expect(counts.agent).toBeGreaterThan(0)+ expect(counts.vision).toBeGreaterThan(0)+ expect(counts.coding).toBeGreaterThan(0)+ expect(counts.small).toBeGreaterThan(0)+ })+})++describe('filter and sort', () => {+ const m = (name: string, extra: Partial<DiscoverModel> = {}): DiscoverModel =>+ ({ name, description: '', pulls: '', tags: [], updated: '', ...extra })++ it('All and an unknown id keep everything, in order', () => {+ const list = [m('a'), m('b')]+ expect(filterByCategory(list, TEXT_CATEGORIES, 'all')).toEqual(list)+ // A remembered id a later catalog no longer has never empties the page.+ expect(filterByCategory(list, TEXT_CATEGORIES, 'gone-since')).toEqual(list)+ })++ it('sorts by size, missing sizes last, stable', () => {+ const list = [m('big', { sizeGB: 20 }), m('none'), m('small', { sizeGB: 2 }), m('small2', { sizeGB: 2 })]+ const key = { size: (x: DiscoverModel) => x.sizeGB, name: (x: DiscoverModel) => x.name, released: (x: DiscoverModel) => x.released }+ expect(sortItems(list, 'smallest', key).map((x) => x.name)).toEqual(['small', 'small2', 'big', 'none'])+ expect(sortItems(list, 'largest', key).map((x) => x.name)).toEqual(['big', 'small', 'small2', 'none'])+ expect(sortItems(list, 'recommended', key)).toEqual(list)+ })++ it('newest first by release month, undated last', () => {+ const list = [m('old', { released: '2025-01' }), m('undated'), m('new', { released: '2026-10' })]+ const key = { size: () => undefined, name: (x: DiscoverModel) => x.name, released: (x: DiscoverModel) => x.released }+ expect(sortItems(list, 'newest', key).map((x) => x.name)).toEqual(['new', 'old', 'undated'])+ })++ it('by name, numbers in their order', () => {+ const list = [m('Qwen 30B'), m('qwen 4B'), m('Gemma')]+ const key = { size: () => undefined, name: (x: DiscoverModel) => x.name }+ expect(sortItems(list, 'name', key).map((x) => x.name)).toEqual(['Gemma', 'qwen 4B', 'Qwen 30B'])+ })+})diff --git a/src/lib/__tests__/uninstall-plan.test.ts b/src/lib/__tests__/uninstall-plan.test.tsnew file mode 100644index 00000000..efeb8289--- /dev/null+++ b/src/lib/__tests__/uninstall-plan.test.ts@@ -0,0 +1,106 @@+// C17: one click uninstalls a model with all its files, and the dialog says+// before anything goes which files go, which stay and why.+import { describe, it, expect } from 'vitest'+import {+ bundleUninstallPlan, installedFileUninstallPlan, engineUninstallPlan, ollamaUninstallPlan,+ bundlesWithFile, type FileOnDisk,+} from '../uninstall-plan'+import type { ModelBundle, DiscoverModel } from '../../api/model-bundles'++const file = (filename: string, subfolder = 'diffusion_models'): DiscoverModel =>+ ({ name: filename, description: '', pulls: '', tags: [], updated: '', filename, subfolder, downloadUrl: `https://x/${filename}` })+const bundle = (name: string, files: DiscoverModel[]): ModelBundle => ({+ name, description: '', tags: [], totalSizeGB: 1, vramRequired: '', vramMinGB: null, vramComfortGB: null,+ workflow: 'wan', tier: 'standard', files,+})+const disk = (bytes: number, extra: Partial<FileOnDisk> = {}): FileOnDisk =>+ ({ path: `/test/models/${bytes}`, bytes, ownFolder: false, copies: 1, ...extra })++const WAN = bundle('Wan Test', [file('wan_model.safetensors'), file('umt5.safetensors', 'text_encoders'), file('wan_vae.safetensors', 'vae')])+const WAN_FAST = bundle('Wan Test Fast', [file('wan_fast.gguf'), file('umt5.safetensors', 'text_encoders'), file('wan_vae.safetensors', 'vae')])+const ALL = [WAN, WAN_FAST]++describe('a bundle goes with all its files', () => {+ it('every file on the disk goes, and the freed space is their sum', () => {+ const onDisk = new Map([['wan_model.safetensors', disk(1000)], ['umt5.safetensors', disk(200)], ['wan_vae.safetensors', disk(30)]])+ const plan = bundleUninstallPlan(WAN, ALL, { 'Wan Test': true }, onDisk)+ expect(plan.files.map((f) => [f.ref, f.action])).toEqual([+ ['wan_model.safetensors', 'delete'], ['umt5.safetensors', 'delete'], ['wan_vae.safetensors', 'delete'],+ ])+ expect(plan.freeBytes).toBe(1230)+ })++ it('THE RULE: a file another installed model needs stays, and says which', () => {+ const onDisk = new Map([['wan_model.safetensors', disk(1000)], ['umt5.safetensors', disk(200)], ['wan_vae.safetensors', disk(30)]])+ const plan = bundleUninstallPlan(WAN, ALL, { 'Wan Test': true, 'Wan Test Fast': true }, onDisk)+ const kept = plan.files.filter((f) => f.action === 'keep')+ expect(kept.map((f) => f.ref)).toEqual(['umt5.safetensors', 'wan_vae.safetensors'])+ expect(kept[0].reason).toContain('Wan Test Fast')+ expect(plan.freeBytes).toBe(1000)+ })++ it('GEGENPROBE: a model that is not installed keeps nothing alive', () => {+ const onDisk = new Map([['umt5.safetensors', disk(200)]])+ const plan = bundleUninstallPlan(WAN, ALL, { 'Wan Test': true, 'Wan Test Fast': false }, onDisk)+ expect(plan.files.every((f) => f.action === 'delete')).toBe(true)+ })++ it('a file in the user\'s own folder (Storage) is never deleted', () => {+ const onDisk = new Map([['wan_model.safetensors', disk(1000, { ownFolder: true })]])+ const plan = bundleUninstallPlan(WAN, ALL, {}, onDisk)+ expect(plan.files[0].action).toBe('keep')+ expect(plan.files[0].reason).toMatch(/own model folder/)+ expect(plan.freeBytes).toBe(0)+ })++ it('a file with two copies is left to the user', () => {+ const onDisk = new Map([['wan_model.safetensors', disk(1000, { copies: 2 })]])+ expect(bundleUninstallPlan(WAN, ALL, {}, onDisk).files[0].action).toBe('keep')+ })++ it('a file that is not on the disk is not listed', () => {+ const onDisk = new Map<string, FileOnDisk | null>([['wan_model.safetensors', disk(1000)], ['umt5.safetensors', null]])+ expect(bundleUninstallPlan(WAN, ALL, {}, onDisk).files.map((f) => f.ref)).toEqual(['wan_model.safetensors'])+ })+})++describe('the bin of an Installed row', () => {+ it('the model file of one bundle takes its companions along', () => {+ const onDisk = new Map([['wan_model.safetensors', disk(1000)], ['umt5.safetensors', disk(200)], ['wan_vae.safetensors', disk(30)]])+ const plan = installedFileUninstallPlan('wan_model.safetensors', ALL, { 'Wan Test': true }, onDisk)+ expect(plan.title).toBe('Wan Test')+ expect(plan.files).toHaveLength(3)+ })++ it('a shared file is only itself, and the note names who needs it', () => {+ const onDisk = new Map([['umt5.safetensors', disk(200)]])+ const plan = installedFileUninstallPlan('umt5.safetensors', ALL, { 'Wan Test': true, 'Wan Test Fast': true }, onDisk)+ expect(plan.files.map((f) => f.ref)).toEqual(['umt5.safetensors'])+ expect(plan.note).toContain('Wan Test Fast')+ })++ it('a file of no bundle (a CivitAI checkpoint) is only itself', () => {+ const onDisk = new Map([['my_model.safetensors', disk(5000)]])+ const plan = installedFileUninstallPlan('my_model.safetensors', ALL, {}, onDisk)+ expect(plan.files).toEqual([expect.objectContaining({ ref: 'my_model.safetensors', action: 'delete', bytes: 5000 })])+ })++ it('a row with a subfolder finds its bundle by the file name', () => {+ expect(bundlesWithFile('wan/wan_model.safetensors', ALL).map((b) => b.name)).toEqual(['Wan Test'])+ expect(bundlesWithFile('sub\\wan_fast.gguf', ALL).map((b) => b.name)).toEqual(['Wan Test Fast'])+ })+})++describe('LU Engine and Ollama', () => {+ it('an LU Engine model lists every part and the image part', () => {+ const plan = engineUninstallPlan('Qwen', [{ path: '/m/q-00001-of-00002.gguf', bytes: 10 }, { path: '/m/q-00002-of-00002.gguf', bytes: 10 }, { path: '/m/q.mmproj.gguf', bytes: 3 }])+ expect(plan.files.map((f) => f.label)).toEqual(['q-00001-of-00002.gguf', 'q-00002-of-00002.gguf', 'q.mmproj.gguf'])+ expect(plan.freeBytes).toBe(23)+ })++ it('an Ollama model says that shared layers may stay', () => {+ const plan = ollamaUninstallPlan('llama3:8b', 4_000)+ expect(plan.kind).toBe('ollama')+ expect(plan.note).toMatch(/Layers/)+ })+})diff --git a/src/lib/discover-categories.ts b/src/lib/discover-categories.tsnew file mode 100644index 00000000..6a284c1f--- /dev/null+++ b/src/lib/discover-categories.ts@@ -0,0 +1,211 @@+/**+ * "Better Categories" (Discord feature-requests, 09.11.2026):+ * sort and filter the models of Get new by what they are for, the way Create+ * sorts its work into Image, Edit, Video, Music, Lip sync and Motion.+ *+ * Pure, and read only from what the catalog already says about an entry+ * (its tags, flags and name), so no entry needs a new field and a test can+ * hold every catalog entry against the rules. A category is a filter, never+ * a hiding place: "All" is always there and is the default.+ */+import type { DiscoverModel, ModelBundle } from '../api/model-bundles'++export interface CategoryDef<T> {+ id: string+ label: string+ /** The tooltip of the chip. */+ hint: string+ match: (item: T) => boolean+}++const hasTag = (tags: readonly string[] | undefined, ...wanted: string[]) =>+ !!tags?.some((t) => wanted.some((w) => t.toLowerCase() === w.toLowerCase()))++const text = (m: { name: string; description?: string }) => `${m.name} ${m.description ?? ''}`++// ── Chat ────────────────────────────────────────────────────────────++/** Small enough for a laptop or an 8 GB card, in GB of file. */+export const SMALL_CHAT_GB = 5++export const TEXT_CATEGORIES: CategoryDef<DiscoverModel>[] = [+ {+ id: 'agent', label: 'Agent & tools', hint: 'Can call tools: Agent mode, web search, files, computer control',+ match: (m) => !!m.agent || hasTag(m.tags, 'Tools', 'Computer control'),+ },+ {+ id: 'vision', label: 'Sees images', hint: 'Can look at pictures and the screen',+ match: (m) => hasTag(m.tags, 'Vision') || !!m.mmprojUrl,+ },+ {+ id: 'coding', label: 'Coding', hint: 'Made or tuned for writing code',+ match: (m) => hasTag(m.tags, 'Coding') || /\b(coder|codestral|devstral|code)\b/i.test(m.name),+ },+ {+ id: 'reasoning', label: 'Reasoning', hint: 'Thinks before it answers',+ match: (m) => hasTag(m.tags, 'Reasoning') || /\b(thinking|reasoning|qwq|r1)\b/i.test(m.name),+ },+ {+ id: 'roleplay', label: 'Roleplay & stories', hint: 'Tuned for characters, roleplay and creative writing',+ match: (m) => hasTag(m.tags, 'RP') || /\b(roleplay|role-play|storytelling|creative writing|rp)\b/i.test(text(m)),+ },+ {+ id: 'small', label: 'Small & fast', hint: `Runs on modest hardware: ${SMALL_CHAT_GB} GB or less, or tested on a CPU`,+ match: (m) => !!m.lightweight || (typeof m.sizeGB === 'number' && m.sizeGB > 0 && m.sizeGB <= SMALL_CHAT_GB),+ },+]++// ── Image and Video (the lanes of Create) ───────────────────────────++/** A bundle that is no model on its own: a LoRA, a VAE, a prompt helper, the+ * companion files of a checkpoint from elsewhere. */+export function isAddonBundle(b: ModelBundle): boolean {+ return !!b.addonFor+ || hasTag(b.tags, 'Addon', 'Companion Files')+ || (b.files.length > 0 && b.files.every((f) => f.subfolder === 'loras'))+}++const isFast = (b: ModelBundle) => hasTag(b.tags, 'Fast', 'Turbo', 'Lightning') || /\b(turbo|schnell|lightning|fast)\b/i.test(b.name)++export const IMAGE_CATEGORIES: CategoryDef<ModelBundle>[] = [+ {+ id: 'generate', label: 'Text to image', hint: 'Makes a picture from a prompt (Create, Image)',+ match: (b) => !isAddonBundle(b) && b.workflow !== 'upscale',+ },+ {+ id: 'edit', label: 'Edit', hint: 'Changes a picture you give it (Create, Edit / Image to Image)',+ match: (b) => !isAddonBundle(b) && (hasTag(b.tags, 'Edit') || /\bedit\b/i.test(b.name)),+ },+ {+ id: 'photo', label: 'Photorealistic', hint: 'Looks like a photo',+ match: (b) => hasTag(b.tags, 'Photorealistic') || /\bphoto(real|realistic)?\b/i.test(b.name),+ },+ {+ id: 'stylized', label: 'Anime & style', hint: 'Anime, illustration and other styles',+ match: (b) => hasTag(b.tags, 'Anime', 'Stylized', 'Style'),+ },+ {+ id: 'fast', label: 'Fast', hint: 'Few steps, quick results',+ match: (b) => !isAddonBundle(b) && isFast(b),+ },+ {+ id: 'enhance', label: 'Enhance', hint: 'Sharpens and enlarges a picture (Create, Enhance)',+ match: (b) => b.workflow === 'upscale' || hasTag(b.tags, 'Upscale', 'Enhance'),+ },+ {+ id: 'addons', label: 'Add-ons', hint: 'LoRAs, VAEs, prompt helpers and companion files for a model you have',+ match: isAddonBundle,+ },+]++/** The Video tab also carries Music, Lip sync and Motion (DiscoverModels'+ * `laneOf`), so its categories take that lane as a second argument. */+export type VideoItem = { bundle: ModelBundle; lane?: string }++const isVideoModel = (v: VideoItem) => !v.lane && !isAddonBundle(v.bundle)++export const VIDEO_CATEGORIES: CategoryDef<VideoItem>[] = [+ {+ id: 't2v', label: 'Text to video', hint: 'Makes a clip from a prompt (Create, Video)',+ match: (v) => isVideoModel(v) && (hasTag(v.bundle.tags, 'T2V') || !(v.bundle.i2v || hasTag(v.bundle.tags, 'I2V'))),+ },+ {+ id: 'i2v', label: 'Image to video', hint: 'Brings a picture you give it to life (Create, Image to Video)',+ match: (v) => isVideoModel(v) && (!!v.bundle.i2v || hasTag(v.bundle.tags, 'I2V')),+ },+ {+ id: 'sound', label: 'With sound', hint: 'The clip comes with its own audio',+ match: (v) => isVideoModel(v) && hasTag(v.bundle.tags, 'Audio'),+ },+ {+ id: 'music', label: 'Music', hint: 'Songs with vocals (Create, Music)',+ match: (v) => v.lane === 'Music',+ },+ {+ id: 'lipsync', label: 'Lip sync', hint: 'A portrait speaks or sings a voice (Create, Lip sync)',+ match: (v) => v.lane === 'Lip sync',+ },+ {+ id: 'motion', label: 'Motion', hint: 'A character copies the moves of a video (Create, Motion)',+ match: (v) => v.lane === 'Motion',+ },+ {+ id: 'fast', label: 'Fast', hint: 'Few steps or a light model',+ match: (v) => !isAddonBundle(v.bundle) && (isFast(v.bundle) || hasTag(v.bundle.tags, 'Light', 'Low VRAM')),+ },+ {+ id: 'addons', label: 'Add-ons', hint: 'Speed LoRAs and other files for a model you have',+ match: (v) => isAddonBundle(v.bundle),+ },+]++/** Keep the items of one category; 'all' or an unknown id keeps everything,+ * so a remembered id that a later catalog no longer has never empties the+ * page. */+export function filterByCategory<T>(items: readonly T[], defs: readonly CategoryDef<T>[], id: string): T[] {+ const def = defs.find((d) => d.id === id)+ return def ? items.filter(def.match) : [...items]+}++/** How many items each category holds, for the counts on the chips. */+export function categoryCounts<T>(items: readonly T[], defs: readonly CategoryDef<T>[]): Record<string, number> {+ const out: Record<string, number> = { all: items.length }+ for (const d of defs) out[d.id] = items.filter(d.match).length+ return out+}++// ── Sorting ─────────────────────────────────────────────────────────++export type SortId = 'recommended' | 'newest' | 'smallest' | 'largest' | 'name'++export const SORTS: { id: SortId; label: string; textOnly?: true }[] = [+ { id: 'recommended', label: 'Recommended' },+ // Only the chat catalog carries a release month.+ { id: 'newest', label: 'Newest', textOnly: true },+ { id: 'smallest', label: 'Smallest' },+ { id: 'largest', label: 'Largest' },+ { id: 'name', label: 'Name' },+]++export function isSortId(v: string): v is SortId {+ return SORTS.some((s) => s.id === v)+}++/**+ * Stable sort by one key. 'recommended' returns the order it was given, which+ * is the hand-made order of the catalog and the tier rule on top of it.+ * Items without the key (no size, no date) go last, in their old order.+ */+export function sortItems<T>(+ items: readonly T[],+ sort: string,+ key: { size: (t: T) => number | undefined; released?: (t: T) => string | undefined; name: (t: T) => string },+): T[] {+ const indexed = items.map((item, i) => ({ item, i }))+ const missingLast = (a: number | string | undefined, b: number | string | undefined) =>+ (a === undefined ? 1 : 0) - (b === undefined ? 1 : 0)+ const cmp = (fn: (a: { item: T; i: number }, b: { item: T; i: number }) => number) =>+ indexed.sort((a, b) => fn(a, b) || a.i - b.i).map(({ item }) => item)+ switch (sort) {+ case 'smallest':+ case 'largest': {+ const sign = sort === 'smallest' ? 1 : -1+ return cmp((a, b) => {+ const x = key.size(a.item), y = key.size(b.item)+ return missingLast(x, y) || (x !== undefined && y !== undefined ? sign * (x - y) : 0)+ })+ }+ case 'newest': {+ if (!key.released) return [...items]+ const rel = key.released+ return cmp((a, b) => {+ const x = rel(a.item), y = rel(b.item)+ return missingLast(x, y) || (x && y ? y.localeCompare(x) : 0)+ })+ }+ case 'name':+ return cmp((a, b) => key.name(a.item).localeCompare(key.name(b.item), undefined, { sensitivity: 'base', numeric: true }))+ default:+ return [...items]+ }+}diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex aac15859..deddc9b7 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -63,6 +63,8 @@ export const STORE_KEYS = [// 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',+ // C41: the names, notes and hidden marks the user gave the LoRAs.+ 'lu-lora-notes',// 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 desdiff --git a/src/lib/uninstall-plan.ts b/src/lib/uninstall-plan.tsnew file mode 100644index 00000000..bf803fcc--- /dev/null+++ b/src/lib/uninstall-plan.ts@@ -0,0 +1,157 @@+/**+ * C17 (Discord feature-requests 30.10.2026): uninstall a model+ * with one click, all its files, instead of hunting the text encoder and the+ * VAE of a 30 GB video model down one by one under Installed.+ *+ * What goes is decided here, pure, from three things the caller asks the disk+ * and the catalog: which bundle the file belongs to, which of the bundle's+ * files are on the disk (and where), and which other bundles are installed.+ * The dialog shows exactly this list before anything is deleted, so a file+ * that is kept says why it is kept.+ *+ * Nothing outside LU's own folders goes: a file in the user's own model+ * folder (Storage) and a file another installed model still needs are kept,+ * and both are named.+ */+import type { ModelBundle } from '../api/model-bundles'++export type UninstallKind = 'comfy' | 'engine' | 'ollama'++export interface UninstallFile {+ /** What the dialog shows. */+ label: string+ /** What the delete is called with: the ComfyUI file name, or the GGUF path. */+ ref: string+ /** Where it lies on the disk, when that is known. */+ path?: string+ bytes: number+ action: 'delete' | 'keep'+ /** Why a kept file stays. */+ reason?: string+}++export interface UninstallPlan {+ kind: UninstallKind+ /** The model the dialog is about. */+ title: string+ files: UninstallFile[]+ /** The sum of the files that go. */+ freeBytes: number+ /** One more sentence where one is due (a file that more than one model+ * shares, a model Ollama manages). */+ note?: string+}++/** What `comfy_model_info` said about a file, or null when it is not there. */+export interface FileOnDisk { path: string; bytes: number; ownFolder: boolean; copies: number }++const leaf = (name: string) => name.split(/[\\/]/).pop() ?? name++/** The bundles of the catalog one ComfyUI file belongs to, by its file name. */+export function bundlesWithFile(file: string, bundles: readonly ModelBundle[]): ModelBundle[] {+ const want = leaf(file).toLowerCase()+ return bundles.filter((b) => b.files.some((f) => f.filename && leaf(f.filename).toLowerCase() === want))+}++function total(files: UninstallFile[]): number {+ return files.filter((f) => f.action === 'delete').reduce((s, f) => s + f.bytes, 0)+}++/** Why a file found on the disk stays, or undefined when it may go. */+function keepReason(found: FileOnDisk, usedBy: string[]): string | undefined {+ if (found.ownFolder) return 'In your own model folder (Storage). LU does not delete there.'+ if (found.copies > 1) return 'There is more than one copy in the model folders. Remove the right one in the ComfyUI folder.'+ if (usedBy.length) return `Still needed by ${usedBy.join(', ')}.`+ return undefined+}++/**+ * The plan for a whole bundle: every file of it that is on the disk.+ * `installed` names the bundles whose files are all there; a file one of+ * those (other than this one) also lists stays.+ */+export function bundleUninstallPlan(+ bundle: ModelBundle,+ allBundles: readonly ModelBundle[],+ installed: Readonly<Record<string, boolean>>,+ onDisk: ReadonlyMap<string, FileOnDisk | null>,+): UninstallPlan {+ const others = allBundles.filter((b) => b.name !== bundle.name && installed[b.name])+ const seen = new Set<string>()+ const files: UninstallFile[] = []+ for (const f of bundle.files) {+ if (!f.filename || seen.has(f.filename)) continue+ seen.add(f.filename)+ const found = onDisk.get(f.filename)+ if (!found) continue+ const usedBy = bundlesWithFile(f.filename, others).map((b) => b.name)+ const reason = keepReason(found, usedBy)+ files.push({+ label: f.name || f.filename,+ ref: f.filename,+ path: found.path,+ bytes: found.bytes,+ action: reason ? 'keep' : 'delete',+ ...(reason ? { reason } : {}),+ })+ }+ return { kind: 'comfy', title: bundle.name, files, freeBytes: total(files) }+}++/**+ * The plan for one row of Installed (image or video). A file that belongs to+ * exactly one bundle takes that bundle's other files along: that is the+ * one-click uninstall. A file several bundles share (a VAE, a text encoder)+ * is only itself, and the sentence says which models will miss it.+ */+export function installedFileUninstallPlan(+ name: string,+ allBundles: readonly ModelBundle[],+ installed: Readonly<Record<string, boolean>>,+ onDisk: ReadonlyMap<string, FileOnDisk | null>,+): UninstallPlan {+ const owners = bundlesWithFile(name, allBundles)+ if (owners.length === 1) {+ const plan = bundleUninstallPlan(owners[0], allBundles, installed, onDisk)+ // The row the user clicked is in it, whatever the catalog spells it.+ if (plan.files.some((f) => leaf(f.ref).toLowerCase() === leaf(name).toLowerCase())) return plan+ }+ const found = onDisk.get(name) ?? onDisk.get(leaf(name)) ?? null+ const files: UninstallFile[] = []+ if (found) {+ const reason = keepReason(found, [])+ files.push({ label: leaf(name), ref: name, path: found.path, bytes: found.bytes, action: reason ? 'keep' : 'delete', ...(reason ? { reason } : {}) })+ }+ const needing = owners.filter((b) => installed[b.name]).map((b) => b.name)+ return {+ kind: 'comfy',+ title: leaf(name),+ files,+ freeBytes: total(files),+ ...(needing.length > 1 ? { note: `This file is shared: ${needing.join(', ')} need it and stop working without it.` } : {}),+ }+}++/** The plan for an LU Engine row, from the files the backend says go. */+export function engineUninstallPlan(title: string, files: readonly { path: string; bytes: number }[]): UninstallPlan {+ const rows: UninstallFile[] = files.map((f) => ({+ label: leaf(f.path),+ ref: f.path,+ path: f.path,+ bytes: f.bytes,+ action: 'delete',+ }))+ return { kind: 'engine', title, files: rows, freeBytes: total(rows) }+}++/** The plan for an Ollama model. Ollama keeps its files as shared layers,+ * so LU can name the model's size and not the files. */+export function ollamaUninstallPlan(name: string, bytes: number): UninstallPlan {+ return {+ kind: 'ollama',+ title: name,+ files: [{ label: name, ref: name, bytes, action: 'delete' }],+ freeBytes: bytes,+ note: 'Ollama removes this model. Layers another Ollama model shares stay, so the space freed can be smaller.',+ }+}diff --git a/src/mobile/boot/__tests__/settings-durable.test.ts b/src/mobile/boot/__tests__/settings-durable.test.tsindex 993644d2..75882d9e 100644--- a/src/mobile/boot/__tests__/settings-durable.test.ts+++ b/src/mobile/boot/__tests__/settings-durable.test.ts@@ -92,6 +92,7 @@ describe('which keys are kept', () => {'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-lora-notes': 'names, notes and hidden marks of the desktop LoRAs (C41); the phone has no LoRA list','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/__tests__/delete-inventory-lag.test.ts b/src/stores/__tests__/delete-inventory-lag.test.tsindex 38d934c4..61544f69 100644--- a/src/stores/__tests__/delete-inventory-lag.test.ts+++ b/src/stores/__tests__/delete-inventory-lag.test.ts@@ -145,7 +145,9 @@ describe('ModelManager delete path', () => {// an active chat model from the store by hand would leave the picker// pointing at a dead name until the refetch landed, which is a new bug in// place of an old delay.- expect(body).toMatch(/await removeModel\(name\)/)+ // C17 (3.1.0): the Ollama row's bin goes through the uninstall dialog,+ // which hands the name to the same removeModel.+ expect(src).toMatch(/removeOllamaModel=\{async \(name\) => \{ await removeModel\(name\) \}\}/)expect(body.match(/removeInventoryModel/g)?.length).toBe(1)})})diff --git a/src/stores/__tests__/discover-query-handoff.test.ts b/src/stores/__tests__/discover-query-handoff.test.tsindex a9db0611..68e28fc1 100644--- a/src/stores/__tests__/discover-query-handoff.test.ts+++ b/src/stores/__tests__/discover-query-handoff.test.ts@@ -36,7 +36,9 @@ describe('Discover search hand-off', () => {const kept = store.slice(store.indexOf('partialize:'))expect(kept.slice(0, kept.indexOf('}),'))).not.toMatch(/discoverQuery/)const page = readFileSync(resolve(__dirname, '../../components/models/ModelManager.tsx'), 'utf8')- expect(page).toMatch(/useState\(\(\) => useUIStore\.getState\(\)\.discoverQuery \?\? ''\)/)+ // C22 (3.1.0): without a handed-over search the field opens with the one+ // of the last visit in this session (stores/pageMemoryStore.ts).+ expect(page).toMatch(/useState\(\(\) => useUIStore\.getState\(\)\.discoverQuery \?\? usePageMemoryStore\.getState\(\)\.modelsSearch\)/)expect(page).toMatch(/clearDiscoverQuery\(\)/)// The original search reaches Discover, which sorts only while the field holds it.expect(page).toMatch(/originalFor=\{originalFor\}/)diff --git a/src/stores/__tests__/lora-notes-c41.test.ts b/src/stores/__tests__/lora-notes-c41.test.tsnew file mode 100644index 00000000..7461270d--- /dev/null+++ b/src/stores/__tests__/lora-notes-c41.test.ts@@ -0,0 +1,70 @@+// C41: LoRAs get a name of the user's own, a note, and can be hidden from the+// LoRA stack. The file is never renamed: saved settings still find it.+import { describe, it, expect, beforeEach } from 'vitest'+import { useLoraNotesStore, applyLoraNotes } from '../loraNotesStore'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++beforeEach(() => useLoraNotesStore.setState({ notes: {} }))++describe('the notes', () => {+ it('a name and a note are kept, trimmed', () => {+ useLoraNotesStore.getState().setNote('styles/pixel.safetensors', { label: ' Pixel art ', note: 'trigger: pxl' })+ expect(useLoraNotesStore.getState().notes['styles/pixel.safetensors']).toEqual({ label: 'Pixel art', note: 'trigger: pxl' })+ })++ it('a note emptied again is removed, not kept empty', () => {+ const s = useLoraNotesStore.getState()+ s.setNote('a.safetensors', { label: 'A' })+ s.setNote('a.safetensors', { label: '' })+ expect(useLoraNotesStore.getState().notes).toEqual({})+ })++ it('hiding keeps the name, showing again keeps it too', () => {+ const s = useLoraNotesStore.getState()+ s.setNote('a.safetensors', { label: 'A', hidden: true })+ s.setNote('a.safetensors', { hidden: false })+ expect(useLoraNotesStore.getState().notes['a.safetensors']).toEqual({ label: 'A' })+ })++ it('a deleted file takes its note along', () => {+ const s = useLoraNotesStore.getState()+ s.setNote('a.safetensors', { note: 'x' })+ s.forget('a.safetensors')+ expect(useLoraNotesStore.getState().notes).toEqual({})+ })+})++describe('applied to a list (Models and the LoRA stack of Create)', () => {+ const rows = [{ name: 'a.safetensors', label: 'a' }, { name: 'b.safetensors', label: 'b' }]+ const notes = { 'a.safetensors': { label: 'Alpha', note: 'n' }, 'b.safetensors': { hidden: true } }++ it('shows the user\'s name and leaves the hidden one out', () => {+ expect(applyLoraNotes(rows, notes)).toEqual([{ name: 'a.safetensors', label: 'Alpha', note: 'n', hidden: false }])+ })++ it('GEGENPROBE: a hidden LoRA that is ticked stays, so it can be turned off', () => {+ expect(applyLoraNotes(rows, notes, { picked: new Set(['b.safetensors']) }).map((r) => r.name)).toEqual(['a.safetensors', 'b.safetensors'])+ })++ it('Show hidden brings every one back, marked', () => {+ const all = applyLoraNotes(rows, notes, { showHidden: true })+ expect(all.find((r) => r.name === 'b.safetensors')?.hidden).toBe(true)+ })++ it('the name that goes to a run is the file\'s, never the label', () => {+ expect(applyLoraNotes(rows, notes)[0].name).toBe('a.safetensors')+ })+})++describe('kept like the other stores', () => {+ it('is in the backup list, so an update does not lose it', () => {+ const src = readFileSync(resolve(__dirname, '../../lib/store-backup.ts'), 'utf8')+ expect(src).toContain("'lu-lora-notes'")+ })++ it('Create reads the notes for its LoRA stack', () => {+ const src = readFileSync(resolve(__dirname, '../../components/create/experimental/ParamGroups.tsx'), 'utf8')+ expect(src).toMatch(/applyLoraNotes\(loraRows\(/)+ })+})diff --git a/src/stores/loraNotesStore.ts b/src/stores/loraNotesStore.tsnew file mode 100644index 00000000..93dfbaea--- /dev/null+++ b/src/stores/loraNotesStore.ts@@ -0,0 +1,88 @@+/**+ * C41 (Discord 03.11.2026): manage the LoRAs, not only list+ * them. A name of one's own, a note (trigger words, the strength that works),+ * and hiding the ones that are not wanted in the LoRA stack right now.+ *+ * Kept by LU beside the file, never in it: the file keeps its name, so a+ * saved Create setting, a workflow and ComfyUI itself still find it, and a+ * LoRA of the user's own folder is never touched. Keyed by the name ComfyUI+ * lists (with its subfolder), which is what Create sends.+ */+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'++export interface LoraNote {+ /** The name LU shows. Empty or absent: the file name. */+ label?: string+ note?: string+ hidden?: boolean+}++interface LoraNotesState {+ notes: Record<string, LoraNote>+ setNote: (name: string, patch: Partial<LoraNote>) => void+ /** When a LoRA file is deleted its note goes with it. */+ forget: (name: string) => void+}++/** A note without content is no note: it is removed instead of kept empty. */+function clean(n: LoraNote): LoraNote | null {+ const label = n.label?.trim() || undefined+ const note = n.note?.trim() || undefined+ const hidden = n.hidden ? true : undefined+ if (!label && !note && !hidden) return null+ return { ...(label ? { label } : {}), ...(note ? { note } : {}), ...(hidden ? { hidden } : {}) }+}++export const useLoraNotesStore = create<LoraNotesState>()(+ persist(+ (set) => ({+ notes: {},+ setNote: (name, patch) => set((s) => {+ const next = { ...s.notes }+ const merged = clean({ ...s.notes[name], ...patch })+ if (merged) next[name] = merged+ else delete next[name]+ return { notes: next }+ }),+ forget: (name) => set((s) => {+ if (!(name in s.notes)) return s+ const next = { ...s.notes }+ delete next[name]+ return { notes: next }+ }),+ }),+ {+ name: 'lu-lora-notes',+ storage: safeJSONStorage(),+ version: 1,+ partialize: (s) => ({ notes: s.notes }) as LoraNotesState,+ // Version 1 is the first: nothing older to carry over.+ migrate: (persisted) => persisted as LoraNotesState,+ },+ ),+)++/** The name a LoRA is shown by: the user's, else what the caller had. */+export function loraLabel(name: string, fallback: string, notes: Readonly<Record<string, LoraNote>>): string {+ return notes[name]?.label || fallback+}++/**+ * The rows of a LoRA list with the user's names, notes and hidden ones+ * applied. A hidden LoRA that is ticked in the stack stays, so it can be+ * unticked; `showHidden` brings all of them back (the Models list's switch).+ */+export function applyLoraNotes<T extends { name: string; label: string }>(+ rows: readonly T[],+ notes: Readonly<Record<string, LoraNote>>,+ opts: { picked?: ReadonlySet<string>; showHidden?: boolean } = {},+): (T & { note?: string; hidden: boolean })[] {+ return rows+ .filter((r) => opts.showHidden || !notes[r.name]?.hidden || opts.picked?.has(r.name))+ .map((r) => {+ const n = notes[r.name]+ return { ...r, label: n?.label || r.label, ...(n?.note ? { note: n.note } : {}), hidden: !!n?.hidden }+ })+}diff --git a/src/stores/pageMemoryStore.ts b/src/stores/pageMemoryStore.tsnew file mode 100644index 00000000..764b71de--- /dev/null+++ b/src/stores/pageMemoryStore.ts@@ -0,0 +1,124 @@+/**+ * C22 (Discord 31.10.2026): what a page looked like when the+ * user left it, so going to Chat or Create and back finds it as it was.+ *+ * AppShell mounts one view at a time, so every `useState` of Models and+ * Settings started from scratch on each visit: the lane, Installed or Get new,+ * the search, the filters, the hits of a search, the open Settings sections+ * and where the page was scrolled to.+ *+ * Held for the session only, on purpose. A restart opening on the filters of+ * last week is a surprise; coming back from Chat to the page one just left is+ * the expectation. What already outlives a restart (the model category, the+ * Settings tab) stays where it is.+ */+import { create } from 'zustand'+import type { CivitAIModelResult, DiscoverModel } from '../api/discover'++export type ModelsTab = 'installed' | 'discover'+export type ModelsExtraRail = 'lora' | 'music' | null+export type DiscoverSubTab = 'uncensored' | 'mainstream'+export type DiscoverSizeTier = 'all' | 'fit' | 'ultra' | 'light' | 'middle' | 'highend'++/** One Discover lane's filters (Chat, Image, Video each keep their own). */+export interface DiscoverLaneMemory {+ subTab: DiscoverSubTab+ sizeTier: DiscoverSizeTier+ /** A category id from lib/discover-categories, 'all' for none. */+ category: string+ /** A sort id from lib/discover-categories. */+ sort: string+}++export const DEFAULT_DISCOVER_LANE: DiscoverLaneMemory = {+ subTab: 'mainstream',+ sizeTier: 'all',+ category: 'all',+ sort: 'recommended',+}++/** The last Hugging Face search of the Chat lane and its hits. */+export interface HfSearchMemory { query: string; results: DiscoverModel[] }++/** The last CivitAI search of one panel and its hits. */+export interface CivitaiSearchMemory { query: string; results: CivitAIModelResult[] }++interface PageMemoryState {+ modelsTab: ModelsTab+ modelsExtraRail: ModelsExtraRail+ modelsSearch: string+ modelsScroll: Record<string, number>+ discover: Record<string, DiscoverLaneMemory>+ hfSearch: HfSearchMemory | null+ civitai: Record<string, CivitaiSearchMemory>+ /** Settings sections the user opened or closed, by title. */+ settingsSections: Record<string, boolean>+ settingsScroll: number+ /** The LoRA list shows the hidden ones too (C41). */+ lorasShowHidden: boolean++ setModelsTab: (tab: ModelsTab) => void+ setModelsExtraRail: (rail: ModelsExtraRail) => void+ setModelsSearch: (q: string) => void+ setModelsScroll: (key: string, top: number) => void+ setDiscoverLane: (lane: string, patch: Partial<DiscoverLaneMemory>) => void+ setHfSearch: (m: HfSearchMemory | null) => void+ setCivitai: (key: string, m: CivitaiSearchMemory) => void+ setSettingsSection: (title: string, open: boolean) => void+ forgetSettingsSection: (title: string) => void+ setSettingsScroll: (top: number) => void+ setLorasShowHidden: (v: boolean) => void+}++type PageMemoryData = Pick<PageMemoryState,+ 'modelsTab' | 'modelsExtraRail' | 'modelsSearch' | 'modelsScroll' | 'discover' | 'hfSearch' | 'civitai'+ | 'settingsSections' | 'settingsScroll' | 'lorasShowHidden'>++/** A fresh session: nothing remembered yet. */+const FRESH: PageMemoryData = {+ // Get new is where most visits go first; the first visit of a session+ // still opens there, every later one opens where the user was.+ modelsTab: 'discover',+ modelsExtraRail: null,+ modelsSearch: '',+ modelsScroll: {},+ discover: {},+ hfSearch: null,+ civitai: {},+ settingsSections: {},+ settingsScroll: 0,+ lorasShowHidden: false,+}++export const usePageMemoryStore = create<PageMemoryState>()((set) => ({+ ...FRESH,++ setModelsTab: (modelsTab) => set({ modelsTab }),+ setModelsExtraRail: (modelsExtraRail) => set({ modelsExtraRail }),+ setModelsSearch: (modelsSearch) => set({ modelsSearch }),+ setModelsScroll: (key, top) => set((s) => ({ modelsScroll: { ...s.modelsScroll, [key]: top } })),+ setDiscoverLane: (lane, patch) => set((s) => ({+ discover: { ...s.discover, [lane]: { ...(s.discover[lane] ?? DEFAULT_DISCOVER_LANE), ...patch } },+ })),+ setHfSearch: (hfSearch) => set({ hfSearch }),+ setCivitai: (key, m) => set((s) => ({ civitai: { ...s.civitai, [key]: m } })),+ setSettingsSection: (title, open) => set((s) => ({ settingsSections: { ...s.settingsSections, [title]: open } })),+ forgetSettingsSection: (title) => set((s) => {+ if (!(title in s.settingsSections)) return s+ const next = { ...s.settingsSections }+ delete next[title]+ return { settingsSections: next }+ }),+ setSettingsScroll: (settingsScroll) => set({ settingsScroll }),+ setLorasShowHidden: (lorasShowHidden) => set({ lorasShowHidden }),+}))++/** The remembered filters of one Discover lane, or the defaults. */+export function discoverLaneMemory(lane: string): DiscoverLaneMemory {+ return usePageMemoryStore.getState().discover[lane] ?? DEFAULT_DISCOVER_LANE+}++/** Forget everything (a test starts each case as a fresh session). */+export function resetPageMemory(): void {+ usePageMemoryStore.setState(FRESH)+}diff --git a/src/test-setup.ts b/src/test-setup.tsindex bc71edc4..a75d715d 100644--- a/src/test-setup.ts+++ b/src/test-setup.ts@@ -3,7 +3,15 @@// The composer lays its drafts down in a module-level shelf when it unmounts// (lib/chat-drafts.ts). Testing Library unmounts after every test, so without// this the next test would open with the text of the last one.+//+// The page memory (stores/pageMemoryStore.ts, C22) is the same kind of+// shelf for Models and Settings: it outlives an unmount on purpose, so every+// test starts with the state of a fresh session.import { beforeEach } from 'vitest'import { clearChatDrafts } from './lib/chat-drafts'+import { resetPageMemory } from './stores/pageMemoryStore'-beforeEach(() => clearChatDrafts())+beforeEach(() => {+ clearChatDrafts()+ resetPageMemory()+})