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
fix(civitai): die Meldung schickt zum Abschnitt, in dem das Schluesselfeld wirklich steht
purple9c48d3fceab3
diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex f7ca338a..6f715c63 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -284,6 +284,65 @@ mod civitai_auth_tests {);}+ /// The request as it goes out, not as we hope it goes out.+ ///+ /// Built exactly the way `do_download` builds it and read back off the+ /// finished request, because the half that was missing in the report was+ /// never the store or the field: it was whether anything put the key on the+ /// wire. No network — `build()` hands back the request without sending it.+ #[test]+ fn the_key_is_on_the_wire_as_a_bearer_header_and_only_for_civitai() {+ use super::outgoing_token;+ const KEY: &str = "civitai-key-abcdef";+ let build = |url: &str, key: Option<&str>| {+ let client = reqwest::Client::new();+ let mut req = client.get(url);+ if let Some(t) = outgoing_token(url, key, None) {+ req = req.bearer_auth(t);+ }+ req.build().unwrap()+ };++ let civitai = build("https://civitai.com/api/download/models/128713", Some(KEY));+ assert_eq!(+ civitai.headers().get("authorization").map(|v| v.to_str().unwrap()),+ Some(format!("Bearer {KEY}").as_str()),+ );+ // The key is on the header and NOT in the address: the address is what+ // a log line and an error message quote.+ assert!(!civitai.url().as_str().contains(KEY), "{}", civitai.url());+ assert!(!civitai.url().as_str().contains("token="), "{}", civitai.url());++ // No key stored: the same download goes out anonymous, as it always did.+ let anonymous = build("https://civitai.com/api/download/models/128713", None);+ assert!(anonymous.headers().get("authorization").is_none());+ let blank = build("https://civitai.com/api/download/models/128713", Some(" "));+ assert!(blank.headers().get("authorization").is_none());++ // Negative control: every other catalog address carries nothing, even+ // with a key stored. This is the rule the whole host gate exists for.+ let hf = build("https://huggingface.co/TheDrummer/Cydonia/resolve/main/m.gguf", Some(KEY));+ assert!(hf.headers().get("authorization").is_none());+ let smuggled = build("https://evil.test\\.civitai.com/x", Some(KEY));+ assert!(smuggled.headers().get("authorization").is_none());+ }++ /// The hub token takes the same route to its own host and to no other.+ #[test]+ fn the_hub_token_is_host_gated_the_same_way() {+ use super::outgoing_token;+ assert_eq!(+ outgoing_token("https://huggingface.co/a/b/resolve/main/m.gguf", None, Some("hf_x")),+ Some("hf_x".to_string()),+ );+ // A CivitAI URL never carries the hub token, even when one is stored.+ assert_eq!(+ outgoing_token("https://civitai.com/api/download/models/1", None, Some("hf_x")),+ None,+ );+ assert_eq!(outgoing_token("https://example.test/m.gguf", Some("k"), Some("hf_x")), None);+ }+#[test]fn a_refused_civitai_download_names_the_field_instead_of_a_bare_number() {// goonerforporn, 2026-08-28: the download died on a bare HTTP 400 and@@ -297,7 +356,7 @@ mod civitai_auth_tests {);assert!(msg.contains(&format!("HTTP {status}")), "{msg}");assert!(msg.contains("API key"), "{msg}");- assert!(msg.contains("Settings > AI Backends > Model Storage"), "{msg}");+ assert!(msg.contains("Settings > AI Backends > CivitAI API key"), "{msg}");// A key the user can go and add is not a dead address: the// `(HTTP nnn)` shape would hide the Retry button he needs.assert!(!msg.contains(&format!("(HTTP {status})")), "{msg}");@@ -370,7 +429,7 @@ mod civitai_auth_tests {let msg = download_http_error(url, status, sent, "m.gguf");assert_eq!(msg, http_error_message(status, "m.gguf"), "{msg}");assert!(!msg.contains("API key"), "{msg}");- assert!(!msg.contains("Model Storage"), "{msg}");+ assert!(!msg.contains("Settings >"), "{msg}");}}}@@ -1032,7 +1091,15 @@ pub(crate) fn is_huggingface_host(url: &str) -> bool {/// A refusal from CivitAI names the field and the way to it. Everything else/// goes to `http_error_message`: inventing a CivitAI hint for a dead/// HuggingFace link would send people to the wrong setting.-+///+/// The section name is part of the message and it has to be the section that+/// really holds the field. It did not: the key moved out of Model Storage into+/// a section of its own (the A14 review found a tester saving a folder path as+/// his API key, because the two fields sat under each other), and this text+/// kept sending people to the folder settings — where the field they were+/// looking for is not. `src/components/settings/__tests__/+/// die-meldung-zeigt-auf-den-abschnitt-den-es-gibt.test.ts` holds every+/// `Settings > …` path in this file against the sections the app really has.////// The CivitAI text carries its status WITHOUT the `(HTTP nnn)` brackets on/// purpose. That shape is the contract `isPermanentDownloadError` reads in@@ -1064,19 +1131,47 @@ pub(crate) fn download_http_error(url: &str, status: u16, sent_token: bool, filereturn if sent_token {format!("CivitAI refused this download with HTTP {status}. Your CivitAI API key was sent and rejected. \- Check it under Settings > AI Backends > Model Storage, and check that your CivitAI account \+ Check it under Settings > AI Backends > CivitAI API key, and check that your CivitAI account \is allowed to download this model.")} else {format!("CivitAI refused this download with HTTP {status}. Most CivitAI downloads need an API key. \- Add one under Settings > AI Backends > Model Storage, then start this download again."+ Add one under Settings > AI Backends > CivitAI API key, then start this download again.")};}http_error_message(status, filename)}+/// Which credential, if any, rides on this request.+///+/// goonerforporn, Discord #bug-reports 2026-08-28: CivitAI downloads died in+/// 400s because they went out anonymous. The key was in the store, read by the+/// search and by nothing on the download path.+///+/// A Bearer header rather than a `?token=` query parameter, which CivitAI+/// documents as well: a key in the URL is written into the download meta the+/// app persists, printed in every log line that quotes the address, and kept in+/// the browser history of the web build. reqwest strips Authorization itself+/// when a redirect leaves the host, which is exactly right here — CivitAI hands+/// the file to a signed CDN URL that must not see the key.+///+/// Host-gated both ways IN HERE, not only in the caller: the CivitAI key goes+/// to CivitAI, the Hugging Face token to the hub, and a URL that is neither+/// carries nothing. A blank key is no key. The caller still decides whether to+/// read the hub token out of the vault at all, which is a different question+/// from whether it may be sent.+fn outgoing_token(url: &str, civitai_key: Option<&str>, hf_token: Option<&str>) -> Option<String> {+ let civitai = civitai_key+ .map(str::trim)+ .filter(|t| !t.is_empty() && is_civitai_host(url));+ let hub = hf_token+ .map(str::trim)+ .filter(|t| !t.is_empty() && is_huggingface_host(url));+ civitai.or(hub).map(|t| t.to_string())+}+/// One reqwest client, built the same way for every request this module makes.////// The SSRF guard is not optional and not a per-call decision: model downloads@@ -1205,24 +1300,15 @@ async fn do_download(let mut request = client.get(url);- // The CivitAI API key, as a Bearer header rather than a `?token=` query- // parameter: a key in the URL is written into the download meta the app- // persists, printed in the log line above and kept in the browser history- // of the web build. Only for a CivitAI host, so an HF or catalog URL never- // carries it. reqwest strips Authorization itself when a redirect leaves- // the host, which is exactly right: CivitAI hands the file to a signed CDN- // URL that must not see the key.- let civitai = is_civitai_host(url);- let civitai_key = auth_token.as_deref().filter(|t| !t.trim().is_empty() && civitai);// The Hugging Face token from Settings goes to the hub and to no other// host: gated repos answer 401 without it, and anonymous hub traffic is- // throttled. Same redirect rule as above, the signed CDN URL never sees it.+ // throttled.let hf_token = if is_huggingface_host(url) { crate::commands::mlx::hf_token() } else { None };// Kept as a value: weiter unten fragt die Fehlermeldung noch einmal, ob// ein Schluessel mitgegangen ist.- let sent_token: Option<String> = civitai_key.map(|t| t.trim().to_string()).or(hf_token);+ let sent_token: Option<String> = outgoing_token(url, auth_token.as_deref(), hf_token.as_deref());if let Some(t) = sent_token.as_deref() {- request = request.bearer_auth(t.trim());+ request = request.bearer_auth(t);}// Resume support: request only remaining bytesdiff --git a/src/api/workflows.ts b/src/api/workflows.tsindex 002df9b6..decad363 100644--- a/src/api/workflows.ts+++ b/src/api/workflows.ts@@ -1,8 +1,6 @@-import JSZip from 'jszip'import type { ModelType } from './comfyui'import type { GenerateParams, VideoParams } from './comfyui'import { findMatchingVAE, findMatchingCLIP } from './comfyui'-import { fetchExternal, fetchExternalBytes } from './backend'import { log } from '../lib/logger'import { resolveRunSeed } from '../lib/run-seed'import type {@@ -13,14 +11,11 @@ import type {} from '../types/workflows'import type {ComfyApiGraph, ComfyApiNode, ComfyInputValue, ComfyNodeInputs,- ComfyWebGraph, ComfyWebNode,} from '../types/comfy-graph'import {- apiNodes, isComfyApiGraph, isComfyWebGraph, isComfyWebNode,+ apiNodes, isComfyApiGraph, isComfyWebGraph,inputNumber, linkTarget,} from '../types/comfy-graph'-import { prop } from '../types/json-guards'-import { formatCount } from '../lib/formatters'// ─── Validation ───//@@ -30,8 +25,14 @@ import { formatCount } from '../lib/formatters'/*** Accepts either ComfyUI graph format. Kept as a predicate over the API shape- * because that is what every caller goes on to build; a web-format file passes- * here and is converted by `resolveWorkflowJson` before it is used.+ * because that is what every caller goes on to build.+ *+ * A web-format file passes here and is stored as it came: the converter that+ * used to stand beside this went with the CivitAI workflow fetcher it was the+ * only caller of (3.0.0). Nothing in the app ever called it — the Import button+ * in WorkflowsModal hands this JSON straight to `parseImportedWorkflow` — so+ * removing it changed no behaviour, and the modal already says what to do:+ * "Export it from ComfyUI using Save (API Format)".*/export function validateWorkflowJson(json: unknown): json is ComfyApiGraph {if (!json || typeof json !== 'object' || Array.isArray(json)) return false@@ -41,154 +42,6 @@ export function validateWorkflowJson(json: unknown): json is ComfyApiGraph {return isComfyWebGraph(json)}-// Convert ComfyUI web/UI format to API format-function convertWebToApiFormat(webWorkflow: ComfyWebGraph): ComfyApiGraph {- const links: unknown[] = Array.isArray(webWorkflow.links) ? webWorkflow.links : []- const apiWorkflow: ComfyApiGraph = {}-- // Build link lookup: linkId -> { sourceNodeId, sourceSlot }- const linkMap: Record<number, { sourceNodeId: number; sourceSlot: number }> = {}- for (const link of links) {- // link format: [linkId, sourceNodeId, sourceSlot, targetNodeId, targetSlot, type]- if (Array.isArray(link) && link.length >= 4) {- const [id, sourceNodeId, sourceSlot] = link- if (typeof id === 'number' && typeof sourceNodeId === 'number' && typeof sourceSlot === 'number') {- linkMap[id] = { sourceNodeId, sourceSlot }- }- }- }-- for (const raw of webWorkflow.nodes) {- // A canvas graph can hold a malformed entry; the rest still converts.- if (!isComfyWebNode(raw) || !raw.type) continue- const node: ComfyWebNode = raw- const inputs: Record<string, ComfyInputValue> = {}-- // Process connected inputs (from links - these are reliable)- if (Array.isArray(node.inputs)) {- for (const input of node.inputs) {- if (!input || typeof input.name !== 'string') continue- const linkId = input.link- if (linkId != null && linkMap[linkId]) {- const { sourceNodeId, sourceSlot } = linkMap[linkId]- inputs[input.name] = [String(sourceNodeId), sourceSlot]- }- }- }-- // Map widget_values using ComfyUI's object_info-based approach:- // We map ONLY for node types we understand well. For unknown nodes,- // we skip widget values and let injectParameters handle the important ones.- const ct = node.type- const widgetValues = Array.isArray(node.widgets_values) ? node.widgets_values : []- mapWidgetValues(ct, widgetValues, inputs, node)-- apiWorkflow[String(node.id)] = {- class_type: ct,- inputs,- }- }-- return apiWorkflow-}--// Map widget_values to named inputs. Conservative: only map what we're sure about.-// injectParameters will override model/prompt/seed/steps/cfg/etc. anyway.-function mapWidgetValues(- classType: string,- values: ComfyInputValue[],- inputs: Record<string, ComfyInputValue>,- node?: ComfyWebNode,-) {- if (!values || values.length === 0) return-- // For nodes where widget order is well-known and stable:- switch (classType) {- case 'CheckpointLoaderSimple':- if (values[0] != null) inputs.ckpt_name = values[0]- break- case 'UNETLoader':- if (values[0] != null) inputs.unet_name = values[0]- if (values[1] != null) inputs.weight_dtype = values[1]- break- case 'CLIPLoader':- if (values[0] != null) inputs.clip_name = values[0]- if (values[1] != null) inputs.type = values[1]- if (values[2] != null) inputs.device = values[2]- break- case 'VAELoader':- if (values[0] != null) inputs.vae_name = values[0]- break- case 'CLIPTextEncode':- if (values[0] != null) inputs.text = values[0]- break- case 'KSampler':- // Widget order: seed, control_after_generate, steps, cfg, sampler_name, scheduler, denoise- if (values[0] != null) inputs.seed = values[0]- // values[1] = control_after_generate (skip - not an API input)- if (values[2] != null) inputs.steps = values[2]- if (values[3] != null) inputs.cfg = values[3]- if (values[4] != null) inputs.sampler_name = values[4]- if (values[5] != null) inputs.scheduler = values[5]- if (values[6] != null) inputs.denoise = values[6]- break- case 'KSamplerAdvanced':- // add_noise, noise_seed, control_after_generate, steps, cfg, sampler_name, scheduler, start_at_step, end_at_step, return_with_leftover_noise- if (values[0] != null) inputs.add_noise = values[0]- if (values[1] != null) inputs.noise_seed = values[1]- if (values[3] != null) inputs.steps = values[3]- if (values[4] != null) inputs.cfg = values[4]- if (values[5] != null) inputs.sampler_name = values[5]- if (values[6] != null) inputs.scheduler = values[6]- if (values[7] != null) inputs.start_at_step = values[7]- if (values[8] != null) inputs.end_at_step = values[8]- if (values[9] != null) inputs.return_with_leftover_noise = values[9]- break- case 'EmptyLatentImage':- case 'EmptySD3LatentImage':- if (values[0] != null) inputs.width = values[0]- if (values[1] != null) inputs.height = values[1]- if (values[2] != null) inputs.batch_size = values[2]- break- case 'EmptyHunyuanLatentVideo':- if (values[0] != null) inputs.width = values[0]- if (values[1] != null) inputs.height = values[1]- if (values[2] != null) inputs.length = values[2]- if (values[3] != null) inputs.batch_size = values[3]- break- case 'SaveImage':- if (values[0] != null) inputs.filename_prefix = values[0]- break- case 'SaveAnimatedWEBP':- if (values[0] != null) inputs.filename_prefix = values[0]- if (values[1] != null) inputs.fps = values[1]- if (values[2] != null) inputs.lossless = values[2]- if (values[3] != null) inputs.quality = values[3]- if (values[4] != null) inputs.method = values[4]- break- case 'VHS_VideoCombine':- if (values[0] != null) inputs.frame_rate = values[0]- if (values[1] != null) inputs.loop_count = values[1]- if (values[2] != null) inputs.filename_prefix = values[2]- if (values[3] != null) inputs.format = values[3]- break- default:- // For unknown node types: try to use node.widgets if available- // to map by name, otherwise skip widget values entirely.- // injectParameters handles the critical params.- if (Array.isArray(node?.widgets)) {- for (let i = 0; i < Math.min(values.length, node.widgets.length); i++) {- const widgetName = node.widgets[i]?.name- const value = values[i]- if (widgetName && value != null) {- inputs[widgetName] = value- }- }- }- break- }-}-// ─── Smart Search Terms ───export function extractSearchTerms(modelName: string, modelType: ModelType): string {@@ -510,98 +363,6 @@ function detectModelTypes(workflow: ComfyApiGraph): ModelType[] {return types.length > 0 ? types : ['unknown']}-// ─── Fetch workflow from URL (supports JSON and ZIP) ───--export async function fetchWorkflowFromUrl(url: string, apiKey?: string): Promise<ComfyApiGraph> {- // Append CivitAI API key if provided and URL is from CivitAI (any host —- // civitai.com or a mirror like civitai.red, GitHub #53).- let finalUrl = url- if (apiKey && /civitai\.(com|red)/i.test(url)) {- const sep = url.includes('?') ? '&' : '?'- finalUrl = `${url}${sep}token=${apiKey}`- }- // Route through backend proxy (works in both Tauri and dev mode)- let buffer: ArrayBuffer- try {- buffer = await fetchExternalBytes(finalUrl)- } catch (err) {- throw new Error(`Failed to fetch workflow: ${err instanceof Error ? err.message : String(err)}`)- }-- // Detect content type from URL or try parsing- const isLikelyZip = url.endsWith('.zip') || finalUrl.includes('/download/')-- // Handle ZIP archives (CivitAI downloads workflows as .zip)- if (isLikelyZip) {- try {- const zip = await JSZip.loadAsync(buffer)- // Try all files in the ZIP that could contain workflow JSON- const jsonFiles = Object.entries(zip.files).filter(([name, f]) => !f.dir && (name.endsWith('.json') || name.endsWith('.txt')))- // Sort: prefer .json files first- jsonFiles.sort(([a], [b]) => (a.endsWith('.json') ? -1 : 1) - (b.endsWith('.json') ? -1 : 1))-- for (const [, file] of jsonFiles) {- try {- const text = await file.async('text')- const json = JSON.parse(text)- const resolved = resolveWorkflowJson(json)- if (resolved) return resolved- } catch { /* skip unparseable files */ }- }- // List files in ZIP for debugging- const fileList = Object.keys(zip.files).join(', ')- throw new Error(`No valid workflow found in ZIP. Files: ${fileList}`)- } catch (err) {- if (err instanceof Error && err.message.includes('No valid workflow')) throw err- // Not actually a ZIP — try parsing as JSON- const text = new TextDecoder().decode(buffer)- try {- const json = JSON.parse(text)- const resolved = resolveWorkflowJson(json)- if (resolved) return resolved- } catch { /* not JSON either */ }- throw new Error('Could not parse downloaded file as workflow.')- }- }-- // Try parsing as JSON- try {- const text = new TextDecoder().decode(buffer)- const json = JSON.parse(text)- const resolved = resolveWorkflowJson(json)- if (resolved) return resolved- } catch { /* not JSON */ }-- throw new Error('Invalid workflow format. Expected ComfyUI API or web format.')-}--/**- * Try to extract a valid API-format workflow from the various JSON structures- * a downloaded or exported ComfyUI file can be wrapped in. `json` is whatever- * `JSON.parse` produced, so every branch narrows before it reads.- */-function resolveWorkflowJson(json: unknown): ComfyApiGraph | null {- if (!json || typeof json !== 'object' || Array.isArray(json)) return null-- // Direct API format- if (isComfyApiGraph(json)) return json-- // Web/UI format → convert- if (isComfyWebGraph(json)) return convertWebToApiFormat(json)-- // Wrapped in "prompt" / "workflow" / "output". The ComfyUI export wrapper- // `{ extra: {...}, prompt: {...} }` is the same 'prompt' branch — it used to- // have its own line that additionally demanded `extra`, i.e. a strict subset.- for (const key of ['prompt', 'workflow', 'output']) {- const inner = prop(json, key)- if (!inner) continue- if (isComfyApiGraph(inner)) return inner- if (isComfyWebGraph(inner)) return convertWebToApiFormat(inner)- }-- return null-}-// ─── Parse imported workflow into a template ───export function parseImportedWorkflow(@@ -687,98 +448,3 @@ export function getBuiltinTemplates(): WorkflowSearchResult[] {},]}--// ─── CivitAI Search ───--interface CivitAIModel {- id: number- name: string- description?: string- type: string- stats?: { downloadCount?: number; thumbsUpCount?: number; thumbsDownCount?: number }- creator?: { username?: string }- tags?: string[]- modelVersions?: Array<{- id: number- name: string- description?: string- downloadUrl?: string- images?: Array<{ url: string }>- files?: Array<{ name: string; downloadUrl: string; type: string }>- }>-}--export async function searchCivitai(query: string, host: string = 'civitai.com'): Promise<WorkflowSearchResult[]> {- try {- const params = new URLSearchParams({- query,- types: 'Workflows',- limit: '20',- sort: 'Most Downloaded',- })- const text = await fetchExternal(`https://${host}/api/v1/models?${params}`)- const data = JSON.parse(text)- if (!data.items) {- log.warn('[workflows] CivitAI returned no items')- return []- }- const items: CivitAIModel[] = data.items ?? []-- return items.map((item) => {- const version = item.modelVersions?.[0]- const thumb = version?.images?.[0]?.url- // Prefer the version downloadUrl, fall back to first file. Rewrite the- // host so a mirror (civitai.red) serves the actual file too (#53).- const rawDownloadUrl = version?.downloadUrl ?? version?.files?.[0]?.downloadUrl- const downloadUrl = host === 'civitai.com'- ? rawDownloadUrl- : rawDownloadUrl?.replace(/^(https?:\/\/)civitai\.com/i, `$1${host}`)-- // Build description with stats- const descParts: string[] = []- const rawDesc = (item.description ?? '').replace(/<[^>]*>/g, '').trim()- if (rawDesc) descParts.push(rawDesc.slice(0, 150))- if (item.stats) {- const stats: string[] = []- if (item.stats.downloadCount) stats.push(`${formatCount(item.stats.downloadCount)} Downloads`)- if (item.stats.thumbsUpCount) stats.push(`${formatCount(item.stats.thumbsUpCount)} Likes`)- if (stats.length > 0) descParts.push(stats.join(' | '))- }- if (item.creator?.username) descParts.push(`by ${item.creator.username}`)-- return {- name: item.name || `CivitAI #${item.id}`,- description: descParts.join(', '),- source: 'civitai' as const,- sourceUrl: `https://${host}/models/${item.id}`,- thumbnailUrl: thumb,- modelTypes: ['unknown'] as ModelType[],- mode: 'image' as const,- downloadUrl,- }- })- } catch (err) {- log.warn('[workflows] CivitAI search failed', { err })- return []- }-}--// ─── Unified Search ───--export async function searchWorkflows(- query: string,- source: 'civitai' | 'templates',- host: string = 'civitai.com'-): Promise<WorkflowSearchResult[]> {- if (source === 'templates') {- const templates = getBuiltinTemplates()- if (!query.trim()) return templates- const lower = query.toLowerCase()- return templates.filter(t =>- t.name.toLowerCase().includes(lower) ||- t.description.toLowerCase().includes(lower) ||- t.modelTypes.some(mt => mt.includes(lower))- )- }- return searchCivitai(query, host)-}diff --git a/src/components/settings/__tests__/die-meldung-zeigt-auf-den-abschnitt-den-es-gibt.test.ts b/src/components/settings/__tests__/die-meldung-zeigt-auf-den-abschnitt-den-es-gibt.test.tsnew file mode 100644index 00000000..e0a85eec--- /dev/null+++ b/src/components/settings/__tests__/die-meldung-zeigt-auf-den-abschnitt-den-es-gibt.test.ts@@ -0,0 +1,93 @@+/**+ * Every "Settings > …" a download failure prints has to be a place that exists.+ *+ * goonerforporn, Discord #bug-reports 2026-08-28: "the field for the CivitAI+ * API key is gone from the UI". The field came back (CivitaiApiKeySetting), and+ * then it MOVED: the A14 Windows review found a tester saving a folder path as+ * his API key, because the key sat directly under the Model Storage folder+ * field, two bare text boxes in a row. A credential and a folder do not belong+ * in one list, so the key got a section of its own.+ *+ * The message a refused CivitAI download prints did not move with it. It kept+ * saying "Settings > AI Backends > Model Storage" — the folder settings, where+ * the key field is not. The one sentence a user gets at the moment he needs the+ * field sent him to the wrong section, which is the same complaint as the+ * original report, one turn later.+ *+ * So the message is held against the app's own section list rather than against+ * a copy of it. Both sides are read from source: the paths out of+ * `download_http_error` in Rust, the section titles out of settings-nav.ts,+ * which itself is pinned to the rendered `<Section title="…">` literals by+ * settings-rail-und-rang.test.ts.+ *+ * Run: npx vitest run src/components/settings/__tests__/die-meldung-zeigt-auf-den-abschnitt-den-es-gibt.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++import { sectionsFor, type SettingsSectionFlags } from '../settings-nav'++const here = dirname(fileURLToPath(import.meta.url))+const downloadRs = readFileSync(resolve(here, '../../../../src-tauri/src/commands/download.rs'), 'utf8')++/** Every section title the app can show, under any platform and any flag. */+function everySectionTitle(): Set<string> {+ const combos: SettingsSectionFlags[] = []+ for (const gpuPicker of [true, false]) {+ for (const builtinExpert of [true, false]) {+ for (const comfyui of [true, false]) {+ combos.push({+ gpuPicker, builtinExpert, comfyui,+ agentMode: true, agentWorkflows: true, mediaTimeouts: true,+ } as SettingsSectionFlags)+ }+ }+ }+ const out = new Set<string>()+ for (const flags of combos) {+ for (const tab of ['general', 'backends', 'agent', 'voice-remote'] as const) {+ for (const title of sectionsFor(tab, flags)) out.add(title)+ }+ }+ return out+}++/** The `Settings > A > B` paths a message PRINTS. Comment lines are dropped+ * first — a doc comment that talks about the rule is not a message — and only+ * the leaf matters: that is the section the user goes looking for. */+function settingsPathsIn(src: string): string[] {+ const code = src.split('\n').filter((l) => !l.trim().startsWith('//')).join('\n')+ // A path ends where the sentence goes on: a full stop, a comma or the line.+ return [...code.matchAll(/Settings > ([^.,"\\\n]+)/g)].map((m) => m[1].trim())+}++describe('a download failure points at a section the app really has', () => {+ it('THE FIX: every Settings path in download.rs ends in a real section', () => {+ const titles = everySectionTitle()+ const paths = settingsPathsIn(downloadRs)+ // A message that names no path at all would pass an "every" silently.+ expect(paths.length).toBeGreaterThanOrEqual(2)+ for (const path of paths) {+ const leaf = path.split('>').pop()!.trim()+ expect(titles, `"Settings > ${path}" · no section is called "${leaf}"`).toContain(leaf)+ }+ })++ it('and the CivitAI refusal names the section the key field is in', () => {+ // Both halves of the message: the key was never entered, and the key was+ // entered and rejected. The second one is the one a user with a wrong key+ // reads, and it has to send him to the field he has to correct.+ const civitai = downloadRs.slice(+ downloadRs.indexOf('if is_civitai_host(url) && refused {'),+ downloadRs.indexOf('http_error_message(status, filename)\n}'),+ )+ expect(civitai).toContain('Settings > AI Backends > CivitAI API key')+ expect(civitai).not.toContain('Settings > AI Backends > Model Storage')+ expect(sectionsFor('backends', {+ gpuPicker: true, builtinExpert: true, comfyui: true,+ agentMode: true, agentWorkflows: true, mediaTimeouts: true,+ } as SettingsSectionFlags)).toContain('CivitAI API key')+ })+})