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(models): das CivitAI-Schluesselfeld ist wieder da und der Download nutzt es
purpledb9ce8519d64
diff --git a/src-tauri/src/commands/custom_models.rs b/src-tauri/src/commands/custom_models.rsindex 0201ac7a..cfe0bae5 100644--- a/src-tauri/src/commands/custom_models.rs+++ b/src-tauri/src/commands/custom_models.rs@@ -156,7 +156,9 @@ mod tests {use super::*;fn tmp(name: &str) -> PathBuf {- let dir = std::env::temp_dir().join("lu-custom-models-tests").join(name);+ let dir = std::env::temp_dir()+ .join("lu-custom-models-tests")+ .join(format!("{name}-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);std::fs::create_dir_all(&dir).unwrap();dir@@ -217,7 +219,9 @@ mod tests {/// Negative control: a missing folder is not an error and not a config.#[test]fn a_folder_that_is_not_there_yields_nothing() {- let root = std::env::temp_dir().join("lu-custom-models-tests").join("nope-not-here");+ let root = std::env::temp_dir()+ .join("lu-custom-models-tests")+ .join(format!("nope-not-here-{}", std::process::id()));let _ = std::fs::remove_dir_all(&root);assert!(comfy_shaped_subdirs(&root).is_empty());assert!(build_extra_model_paths_yaml(&root).is_none());diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsindex afe41c7e..3fc56c04 100644--- a/src-tauri/src/commands/download.rs+++ b/src-tauri/src/commands/download.rs@@ -42,6 +42,71 @@ fn safe_subfolder(subfolder: &str) -> Result<(), String> {Ok(())}+#[cfg(test)]+mod civitai_auth_tests {+ use super::{download_http_error, is_civitai_host};++ #[test]+ fn the_key_goes_to_civitai_and_its_mirror_and_nowhere_else() {+ assert!(is_civitai_host("https://civitai.com/api/download/models/12345"));+ assert!(is_civitai_host("https://CIVITAI.COM/api/download/models/1"));+ // GH #53: the mirror LU offers where .com is blocked.+ assert!(is_civitai_host("https://civitai.red/api/download/models/1"));+ assert!(is_civitai_host("https://api.civitai.com/v1/x"));+ }++ /// Negative control, and the reason the check is on the HOST: a URL that+ /// merely mentions civitai must never collect the user's API key.+ #[test]+ fn a_url_that_only_mentions_civitai_gets_no_key() {+ assert!(!is_civitai_host("https://evil.test/?x=civitai.com"));+ assert!(!is_civitai_host("https://civitai.com.evil.test/file"));+ assert!(!is_civitai_host("https://notcivitai.com/file"));+ assert!(!is_civitai_host("https://huggingface.co/repo/resolve/main/m.safetensors"));+ // A userinfo prefix is not a host either.+ assert!(!is_civitai_host("https://[email protected]/file"));+ }++ #[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+ // the field it was asking for was not in the interface at all.+ for status in [400u16, 401, 403] {+ let msg = download_http_error("https://civitai.com/api/download/models/1", status, false);+ assert!(msg.contains(&format!("HTTP {status}")), "{msg}");+ assert!(msg.contains("API key"), "{msg}");+ assert!(msg.contains("Settings > AI Backends > Model Storage"), "{msg}");+ }+ }++ #[test]+ fn a_key_that_was_sent_and_refused_says_so() {+ let msg = download_http_error("https://civitai.com/api/download/models/1", 401, true);+ assert!(msg.contains("was sent and rejected"), "{msg}");+ // and does NOT tell the user to add a key he already has.+ assert!(!msg.contains("Add one under"), "{msg}");+ }++ /// Negative control: every other host and every other status keeps the+ /// short form. A dead HuggingFace link must not send people to the CivitAI+ /// setting.+ #[test]+ fn other_hosts_and_other_statuses_keep_the_short_form() {+ assert_eq!(+ download_http_error("https://huggingface.co/repo/resolve/main/m.gguf", 401, false),+ "HTTP 401",+ );+ assert_eq!(+ download_http_error("https://civitai.com/api/download/models/1", 404, false),+ "HTTP 404",+ );+ assert_eq!(+ download_http_error("https://civitai.com/api/download/models/1", 500, true),+ "HTTP 500",+ );+ }+}+#[cfg(test)]mod download_security_tests {use super::{checked_model_path, safe_subfolder, sanitize_filename};@@ -209,9 +274,14 @@ pub async fn download_model(subfolder: String,filename: String,expectedBytes: Option<u64>,+ // The CivitAI API key, when the caller has one. Sent as a Bearer header+ // and ONLY to a CivitAI host (see do_download). Absent for every other+ // catalog, which is every other download in the app.+ authToken: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {let expected_bytes = expectedBytes;+ let auth_token = authToken;let comfy_path = {let mut p = state.comfy_path.lock().unwrap();if p.is_none() {@@ -288,7 +358,7 @@ pub async fn download_model(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, auth_token.as_deref()).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -442,6 +512,56 @@ fn gib(bytes: u64) -> String {format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))}+/// Is this a CivitAI download URL? `civitai.red` is the mirror LU offers for+/// regions where `.com` is blocked (GH #53), so both count. Matched on the+/// host, never on a substring of the whole URL: `https://evil.test/?x=civitai.com`+/// must not collect the user's API key.+pub(crate) fn is_civitai_host(url: &str) -> bool {+ let rest = match url.split_once("://") {+ Some((_, r)) => r,+ None => url,+ };+ let host = rest+ .split(['/', '?', '#'])+ .next()+ .unwrap_or("")+ .rsplit('@')+ .next()+ .unwrap_or("");+ let host = host.split(':').next().unwrap_or("").to_ascii_lowercase();+ host == "civitai.com"+ || host == "civitai.red"+ || host.ends_with(".civitai.com")+ || host.ends_with(".civitai.red")+}++/// What the user reads when a download comes back refused.+///+/// goonerforporn, Discord #bug-reports 2026-08-28: CivitAI downloads ended in a+/// bare `HTTP 400` with nothing to act on, because the API key field had gone+/// missing from the interface and nobody could tell that a key was the point.+/// A refusal from CivitAI now names the field and the way to it. Every other+/// host and every other status keeps the short form: inventing a CivitAI hint+/// for a dead HuggingFace link would send people to the wrong setting.+pub(crate) fn download_http_error(url: &str, status: u16, sent_token: bool) -> String {+ let refused = matches!(status, 400 | 401 | 403);+ if is_civitai_host(url) && refused {+ return if sent_token {+ format!(+ "CivitAI refused this download (HTTP {status}). Your CivitAI API key was sent and rejected. \+ Check it under Settings > AI Backends > Model Storage, and check that your CivitAI account \+ is allowed to download this model."+ )+ } else {+ format!(+ "CivitAI refused this download (HTTP {status}). Most CivitAI downloads need an API key. \+ Add one under Settings > AI Backends > Model Storage, then start this download again."+ )+ };+ }+ format!("HTTP {status}")+}+async fn do_download(url: &str,dest: &PathBuf,@@ -449,6 +569,7 @@ async fn do_download(id: &str,token: CancellationToken,resume_offset: u64,+ auth_token: Option<&str>,) -> Result<(), String> {// SSRF guard: model downloads come from public catalogs (HuggingFace,// civitai, ollama). Block private/loopback/metadata hosts and re-validate@@ -475,6 +596,19 @@ 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 sent_token = auth_token.filter(|t| !t.trim().is_empty() && civitai);+ if let Some(t) = sent_token {+ request = request.bearer_auth(t.trim());+ }+// Resume support: request only remaining bytesif resume_offset > 0 {request = request.header("Range", format!("bytes={}-", resume_offset));@@ -488,7 +622,7 @@ async fn do_download(let status = response.status();if !status.is_success() && status.as_u16() != 206 {- return Err(format!("HTTP {}", status));+ return Err(download_http_error(url, status.as_u16(), sent_token.is_some()));}let already_on_disk = resumed_bytes(resume_offset, status.as_u16());@@ -706,13 +840,16 @@ pub fn cancel_download(id: String, state: State<'_, AppState>) -> Result<serde_jOk(serde_json::json!({"status": "cancelled"}))}+#[allow(non_snake_case)]#[tauri::command]pub async fn resume_download(id: String,url: String,subfolder: String,+ authToken: Option<String>,state: State<'_, AppState>,) -> Result<serde_json::Value, String> {+ let auth_token = authToken;let comfy_path = {let p = state.comfy_path.lock().unwrap();p.clone()@@ -758,7 +895,7 @@ pub async fn resume_download(let id_clone = id.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, auth_token.as_deref()).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {@@ -981,7 +1118,9 @@ pub async fn download_model_to_path(let filename_clone = filename.clone();tokio::spawn(async move {- match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset).await {+ // No auth token here: download_model_to_path serves the text-model+ // lane (HuggingFace GGUFs into the app models dir), never CivitAI.+ match do_download(&url, &dest_file, &downloads_arc, &id_clone, token, resume_offset, None).await {Ok(_) => {if let Ok(mut dl) = downloads_arc.lock() {if let Some(p) = dl.get_mut(&id_clone) {diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 28ec6113..5148acf7 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -321,6 +321,10 @@ pub(crate) fn split_shard_stem(stem: &str) -> Option<(&str, u32, u32)> {/// "models" that can never load. A set with missing parts is not listed at/// all, so a paused or aborted multi-part download never impersonates an/// installed model (same rule a9ea114 established for MLX downloads).+// Only the tests call this since the listing went multi-root, and they are the+// reason to keep it: every scan rule that predates GH #122 is pinned through+// this one-root door, so a change to the walk still has to survive them.+#[allow(dead_code)]pub(crate) fn scan_gguf_models(dir: &Path) -> Vec<BundledModel> {scan_gguf_roots(&[ScanRoot { dir, max_depth: MAX_SCAN_DEPTH }])}diff --git a/src/api/__tests__/civitai-api-key.test.ts b/src/api/__tests__/civitai-api-key.test.tsnew file mode 100644index 00000000..487d047b--- /dev/null+++ b/src/api/__tests__/civitai-api-key.test.ts@@ -0,0 +1,101 @@+/**+ * goonerforporn, Discord #bug-reports 2026-08-28: "the field for the CivitAI+ * API key is gone from the UI", and downloads from the CivitAI search end in+ * 400s.+ *+ * He was right on both counts and he had searched before writing. The store+ * carried `civitaiApiKey`, `setCivitaiApiKey` was defined, the changelog named+ * the key. And NO component in the app called the setter, so there was no way+ * to enter one. The search read the empty value, the download path did not read+ * it at all, and CivitAI answered a bare number.+ *+ * Proven here: the key goes out with a CivitAI download and with nothing else.+ * The wire side (Bearer header, host gate, the wording of a refusal) is proven+ * in Rust, `src-tauri/src/commands/download.rs`, mod `civitai_auth_tests`.+ *+ * Run: npx vitest run src/api/__tests__/civitai-api-key.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++const backendCall = vi.fn()+vi.mock('../backend', () => ({+ backendCall: (...args: unknown[]) => backendCall(...args),+ fetchExternal: vi.fn(),+ isTauri: () => true,+ isMacOS: () => false,+}))++import { isCivitaiUrl, civitaiAuthToken, startModelDownload, resumeDownload } from '../discover'+import { useWorkflowStore } from '../../stores/workflowStore'++const KEY = 'civitai-key-abcdef'+const CIVITAI = 'https://civitai.com/api/download/models/128713'+const HUGGINGFACE = 'https://huggingface.co/TheDrummer/Cydonia/resolve/main/model.gguf'++beforeEach(() => {+ backendCall.mockReset()+ backendCall.mockResolvedValue({ status: 'started', id: 'x' })+ useWorkflowStore.setState({ civitaiApiKey: KEY })+})++describe('who gets the key', () => {+ it('recognises CivitAI and its mirror by host', () => {+ expect(isCivitaiUrl(CIVITAI)).toBe(true)+ // GH #53: the mirror LU offers where .com is blocked.+ expect(isCivitaiUrl('https://civitai.red/api/download/models/1')).toBe(true)+ expect(civitaiAuthToken(CIVITAI)).toBe(KEY)+ })++ // Negative control, and the reason the check is on the host: a URL that only+ // mentions civitai must never collect the user's key.+ it('gives the key to nobody else', () => {+ expect(isCivitaiUrl(HUGGINGFACE)).toBe(false)+ expect(isCivitaiUrl('https://evil.test/?x=civitai.com')).toBe(false)+ expect(isCivitaiUrl('https://civitai.com.evil.test/file')).toBe(false)+ expect(isCivitaiUrl('not a url')).toBe(false)+ expect(civitaiAuthToken(HUGGINGFACE)).toBeNull()+ expect(civitaiAuthToken('https://evil.test/?x=civitai.com')).toBeNull()+ })++ it('sends nothing when no key is stored', () => {+ useWorkflowStore.setState({ civitaiApiKey: '' })+ expect(civitaiAuthToken(CIVITAI)).toBeNull()+ useWorkflowStore.setState({ civitaiApiKey: ' ' })+ expect(civitaiAuthToken(CIVITAI)).toBeNull()+ })+})++describe('the download carries it', () => {+ it('hands the key to a CivitAI download', async () => {+ await startModelDownload(CIVITAI, 'checkpoints', 'pony.safetensors')+ expect(backendCall).toHaveBeenCalledWith('download_model', {+ url: CIVITAI,+ subfolder: 'checkpoints',+ filename: 'pony.safetensors',+ expectedBytes: null,+ authToken: KEY,+ })+ })++ it('hands it to a resume too, so a paused CivitAI file can finish', async () => {+ await resumeDownload('pony.safetensors', CIVITAI, 'checkpoints')+ expect(backendCall).toHaveBeenCalledWith('resume_download', {+ id: 'pony.safetensors',+ url: CIVITAI,+ subfolder: 'checkpoints',+ authToken: KEY,+ })+ })++ // Negative control: every other catalog download goes out exactly as before.+ it('sends no token on a HuggingFace download', async () => {+ await startModelDownload(HUGGINGFACE, 'checkpoints', 'model.gguf', 42)+ expect(backendCall).toHaveBeenCalledWith('download_model', {+ url: HUGGINGFACE,+ subfolder: 'checkpoints',+ filename: 'model.gguf',+ expectedBytes: 42,+ authToken: null,+ })+ })+})diff --git a/src/api/discover.ts b/src/api/discover.tsindex 84655264..bbf4c143 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -2,6 +2,7 @@ import { backendCall, fetchExternal } from "./backend"import { getCheckpoints, getDiffusionModels, getVAEModels, getCLIPModels, getGgufUnetModels, getAnimateDiffModels, getLoraModels, filterPartialFiles, refreshComfyModels } from "./comfyui"import type { ProviderId } from "./providers/types"import { log } from "../lib/logger"+import { useWorkflowStore } from "../stores/workflowStore"export interface DiscoverModel {name: string@@ -58,8 +59,45 @@ export interface DownloadProgress {// ─── Download API ───+/**+ * Is this URL served by CivitAI? Host comparison, never a substring of the+ * whole URL: `https://evil.test/?x=civitai.com` must not collect the user's+ * API key. Mirrors `is_civitai_host` in `src-tauri/src/commands/download.rs`,+ * which gates the same key a second time on its way onto the wire.+ */+const CIVITAI_HOSTS = ['civitai.com', 'civitai.red']++export function isCivitaiUrl(url: string): boolean {+ let host: string+ try {+ host = new URL(url).hostname.toLowerCase()+ } catch {+ return false+ }+ return CIVITAI_HOSTS.some((h) => host === h || host.endsWith(`.${h}`))+}++/**+ * The user's CivitAI API key, for a CivitAI URL and no other.+ *+ * goonerforporn (Discord #bug-reports, 2026-08-28): downloads from the CivitAI+ * search died in 400s because they went out anonymous. The key was in the store+ * and read by the search, and by nothing on the download path.+ */+export function civitaiAuthToken(url: string): string | null {+ if (!isCivitaiUrl(url)) return null+ const key = useWorkflowStore.getState().civitaiApiKey?.trim()+ return key ? key : null+}+export async function startModelDownload(url: string, subfolder: string, filename: string, expectedBytes?: number): Promise<{ status: string; id: string; error?: string }> {- return backendCall("download_model", { url, subfolder, filename, expectedBytes: expectedBytes ?? null })+ return backendCall("download_model", {+ url,+ subfolder,+ filename,+ expectedBytes: expectedBytes ?? null,+ authToken: civitaiAuthToken(url),+ })}export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {@@ -79,7 +117,7 @@ export async function cancelDownload(id: string): Promise<void> {}export async function resumeDownload(id: string, url: string, subfolder: string): Promise<void> {- await backendCall("resume_download", { id, url, subfolder })+ await backendCall("resume_download", { id, url, subfolder, authToken: civitaiAuthToken(url) })}// ─── Custom Node Installation ───diff --git a/src/components/layout/DownloadBadge.tsx b/src/components/layout/DownloadBadge.tsxindex 796c5bef..52cf9136 100644--- a/src/components/layout/DownloadBadge.tsx+++ b/src/components/layout/DownloadBadge.tsx@@ -200,6 +200,11 @@ export function DownloadBadge() {const bundleProg = totalBytes > 0 ? (doneBytes / totalBytes) * 100 : 0const bundleSpeed = files.reduce((s, f) => s + (f.d.status === 'downloading' ? (f.d.speed || 0) : 0), 0)const isBundle = files.length > 1+ // The reason a download stopped, in words. A refused transfer+ // used to show a Retry button and nothing else, so the CivitAI+ // 400 that only ever needed an API key looked like a dead link+ // (goonerforporn, Discord #bug-reports 2026-08-28).+ const failure = files.find(f => f.d.status === 'error')?.d.errorreturn (<div key={bundleName} className="px-3 py-2 border-t border-gray-100 dark:border-white/[0.04] first:border-t-0">@@ -241,6 +246,11 @@ export function DownloadBadge() {</button>)}</div>+ {failure && (+ <p className="mt-1 text-[0.55rem] text-red-400 leading-relaxed break-words whitespace-pre-line">+ {failure}+ </p>+ )}{/* Individual file rows */}{isBundle && (<div className="mt-1.5 space-y-0.5">diff --git a/src/components/layout/__tests__/download-failure-is-readable.test.ts b/src/components/layout/__tests__/download-failure-is-readable.test.tsnew file mode 100644index 00000000..93b14bc5--- /dev/null+++ b/src/components/layout/__tests__/download-failure-is-readable.test.ts@@ -0,0 +1,96 @@+/**+ * @vitest-environment jsdom+ *+ * A refused download says why.+ *+ * goonerforporn, Discord #bug-reports 2026-08-28: a CivitAI download that only+ * ever needed an API key ended in "a 400" and the download panel showed a Retry+ * button and nothing else. The reason came back from Rust, was written into the+ * store, and was rendered only into the `title` of a per-file row that a+ * single-file download never draws. So the one sentence that would have solved+ * it reached nobody.+ *+ * Run: npx vitest run src/components/layout/__tests__/download-failure-is-readable.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { createElement } from 'react'+import { render, screen, fireEvent, cleanup } from '@testing-library/react'++vi.mock('../../../hooks/useModels', () => ({+ useModels: () => ({ activePulls: {}, pullModel: vi.fn(), pausePull: vi.fn(), dismissPull: vi.fn() }),+}))+vi.mock(import('../../../api/mlx-image'), async (importOriginal) => ({+ ...(await importOriginal()),+ isMlxImageHost: () => false,+}))++import { DownloadBadge } from '../DownloadBadge'+import { useDownloadStore } from '../../../stores/downloadStore'++/** What Rust hands back for a CivitAI refusal, verbatim (download.rs). */+const CIVITAI_REFUSAL =+ 'CivitAI refused this download (HTTP 401). Most CivitAI downloads need an API key. ' ++ 'Add one under Settings > AI Backends > Model Storage, then start this download again.'++function seedFailure(error: string | undefined) {+ useDownloadStore.setState({+ downloads: {+ 'pony.safetensors': {+ id: 'pony.safetensors',+ filename: 'pony.safetensors',+ progress: 0,+ total: 0,+ speed: 0,+ status: 'error',+ error,+ },+ },+ bundleMap: {},+ } as never)+}++function openPanel() {+ render(createElement(DownloadBadge))+ // The tray opens itself while something is actively downloading; the trigger+ // is queried by title because the badge count changes its accessible name.+ if (!screen.queryByText(/^Downloads/)) fireEvent.click(screen.getByTitle('Downloads'))+}++beforeEach(() => { seedFailure(undefined) })+afterEach(cleanup)++describe('a failed single-file download', () => {+ it('shows the reason as text, not only in a tooltip', () => {+ seedFailure(CIVITAI_REFUSAL)+ openPanel()+ // The whole sentence, including where to go.+ expect(screen.getByText(CIVITAI_REFUSAL)).toBeTruthy()+ expect(document.body.textContent).toContain('Settings > AI Backends > Model Storage')+ })++ // Negative control: a failure that carries no reason must not draw an empty+ // red line. The Retry way out stays either way.+ it('draws nothing extra when there is no reason to show', () => {+ seedFailure(undefined)+ openPanel()+ expect(document.body.textContent).not.toContain('CivitAI refused')+ expect(screen.getByText('Retry failed')).toBeTruthy()+ })++ // Negative control: a download that is merely running says nothing about a+ // failure.+ it('says nothing while the download is still going', () => {+ useDownloadStore.setState({+ downloads: {+ 'pony.safetensors': {+ id: 'pony.safetensors', filename: 'pony.safetensors',+ progress: 10, total: 100, speed: 5, status: 'downloading',+ },+ },+ bundleMap: {},+ } as never)+ openPanel()+ expect(screen.queryByText('Retry failed')).toBeNull()+ expect(document.body.textContent).not.toContain('CivitAI refused')+ })+})diff --git a/src/components/settings/CivitaiApiKeySetting.tsx b/src/components/settings/CivitaiApiKeySetting.tsxnew file mode 100644index 00000000..59386235--- /dev/null+++ b/src/components/settings/CivitaiApiKeySetting.tsx@@ -0,0 +1,85 @@+/**+ * The CivitAI API key field.+ *+ * goonerforporn, Discord #bug-reports 2026-08-28: "the field for the CivitAI+ * API key is gone from the UI". He was right, and he had already checked+ * Settings, Models/Discover and the workflow finder before writing. The store+ * held `civitaiApiKey`, `setCivitaiApiKey` existed, the changelog mentioned the+ * key. And no component in the app ever called the setter, so there was no way+ * to put a key in. Search read the value (empty), downloads read it (empty),+ * and CivitAI answered with a bare 400 nobody could act on.+ *+ * Masked on purpose: this is a credential, and a settings page is a screen+ * people share in support threads.+ */+import { useEffect, useState } from 'react'+import { KeyRound, Check } from 'lucide-react'+import { useWorkflowStore } from '../../stores/workflowStore'+import { openExternal } from '../../api/backend'++/** Where CivitAI issues the key. Account page, API Keys section. */+export const CIVITAI_KEY_PAGE = 'https://civitai.com/user/account'++export function CivitaiApiKeySetting() {+ const apiKey = useWorkflowStore((s) => s.civitaiApiKey)+ const setApiKey = useWorkflowStore((s) => s.setCivitaiApiKey)+ const [draft, setDraft] = useState(apiKey)+ const [saved, setSaved] = useState(false)+ useEffect(() => { setDraft(apiKey) }, [apiKey])++ function save() {+ const next = draft.trim()+ setApiKey(next)+ setDraft(next)+ setSaved(true)+ }++ return (+ <div className="space-y-2 py-1">+ <div className="flex items-center gap-1.5">+ <KeyRound size={12} className="text-gray-500" />+ <span className="text-[0.7rem] text-gray-800 dark:text-gray-200">CivitAI API key</span>+ </div>+ <div className="text-[0.6rem] text-gray-500 leading-relaxed">+ Used for the CivitAI search on the Models page and for the downloads it starts. Most CivitAI+ downloads are refused without a key, which is the HTTP 400 or 401 you see on a download that+ never begins. Create one on your CivitAI account page under API Keys. It is stored on this+ machine and sent to CivitAI only.+ </div>+ <div className="flex items-center gap-2">+ <input+ type="password"+ value={draft}+ onChange={(e) => { setDraft(e.target.value); setSaved(false) }}+ onBlur={save}+ placeholder="(none)"+ spellCheck={false}+ autoComplete="off"+ aria-label="CivitAI API key"+ className="flex-1 min-w-0 px-2 py-1 rounded bg-transparent border border-white/8 text-[0.65rem] text-gray-700 dark:text-gray-300 font-mono focus:outline-none focus:border-white/20"+ />+ <button+ onClick={save}+ className="px-2.5 py-1 rounded-md text-[0.6rem] font-medium inline-flex items-center gap-1 bg-white dark:bg-white/10 text-gray-800 dark:text-white hover:bg-gray-100 dark:hover:bg-white/15 border border-gray-200 dark:border-white/15 transition-colors"+ >+ {saved && <Check size={11} />}+ {saved ? 'Saved' : 'Save'}+ </button>+ {apiKey && (+ <button+ onClick={() => { setDraft(''); setApiKey(''); setSaved(false) }}+ className="px-2.5 py-1 rounded-md text-[0.6rem] text-gray-500 hover:text-red-400 transition-colors"+ >+ Remove+ </button>+ )}+ </div>+ <button+ onClick={() => { void openExternal(CIVITAI_KEY_PAGE) }}+ className="text-[0.6rem] text-purple-500 hover:text-purple-400 transition-colors"+ >+ Get a CivitAI API key+ </button>+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 0ba86715..b3ea8a79 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -64,6 +64,7 @@ import { ArrowUpCircle, KeyRound, RefreshCw } from 'lucide-react'import { CLOUD_BASE } from '../../api/cloud/config'import { formatBytes } from '../../lib/formatters'import { syncCustomModelDir } from '../../lib/custom-model-dir'+import { CivitaiApiKeySetting } from './CivitaiApiKeySetting'// ── User profile picture (Appearance) ───────────────────────────// Self-contained like HfDownloadPathSetting. Stores the picture as a@@ -1535,6 +1536,11 @@ export function SettingsPage() {<Section title="Model Storage"><HfDownloadPathSetting /><ImportLocalModels />+ {/* goonerforporn (Discord #bug-reports, 2026-08-28): the store knew+ the key, the changelog named it, and no component ever set it.+ It sits with the other credential-shaped model settings, which+ is also the place the refused-download message points at. */}+ <CivitaiApiKeySetting /></Section>{builtinManaged && (diff --git a/src/components/settings/__tests__/civitai-key-field-renders.test.ts b/src/components/settings/__tests__/civitai-key-field-renders.test.tsnew file mode 100644index 00000000..2a911ed8--- /dev/null+++ b/src/components/settings/__tests__/civitai-key-field-renders.test.ts@@ -0,0 +1,91 @@+/**+ * @vitest-environment jsdom+ *+ * The CivitAI API key field, rendered for real.+ *+ * goonerforporn's report (Discord #bug-reports, 2026-08-28) is precisely the+ * kind a source-text test cannot answer: the store had the value and the setter,+ * the changelog named the key, and the field was not in the interface. So this+ * one mounts the component, types a key, and reads the store back.+ *+ * Run: npx vitest run src/components/settings/__tests__/civitai-key-field-renders.test.ts+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { createElement } from 'react'+import { render, screen, fireEvent, cleanup } from '@testing-library/react'++const openExternal = vi.fn()+vi.mock('../../../api/backend', () => ({+ openExternal: (...args: unknown[]) => openExternal(...args),+ backendCall: vi.fn(),+ isTauri: () => true,+ isMacOS: () => false,+}))++import { CivitaiApiKeySetting, CIVITAI_KEY_PAGE } from '../CivitaiApiKeySetting'+import { useWorkflowStore } from '../../../stores/workflowStore'++beforeEach(() => {+ openExternal.mockReset()+ useWorkflowStore.setState({ civitaiApiKey: '' })+})+afterEach(cleanup)++function show() {+ render(createElement(CivitaiApiKeySetting))+ return screen.getByLabelText('CivitAI API key') as HTMLInputElement+}++describe('the field exists and writes to the store', () => {+ it('is there, and is masked', () => {+ const input = show()+ // A settings page is a screen people paste into support threads.+ expect(input.type).toBe('password')+ })++ it('writes what the user typed into the store', () => {+ const input = show()+ fireEvent.change(input, { target: { value: ' my-civitai-key ' } })+ // Nothing is stored until the field is committed.+ expect(useWorkflowStore.getState().civitaiApiKey).toBe('')+ fireEvent.click(screen.getByText('Save'))+ expect(useWorkflowStore.getState().civitaiApiKey).toBe('my-civitai-key')+ expect(screen.getByText('Saved')).toBeTruthy()+ })++ it('commits on blur as well, because that is how the other fields behave', () => {+ const input = show()+ fireEvent.change(input, { target: { value: 'typed-then-clicked-away' } })+ fireEvent.blur(input)+ expect(useWorkflowStore.getState().civitaiApiKey).toBe('typed-then-clicked-away')+ })++ it('shows an existing key back and can remove it', () => {+ useWorkflowStore.setState({ civitaiApiKey: 'already-set' })+ const input = show()+ expect(input.value).toBe('already-set')+ fireEvent.click(screen.getByText('Remove'))+ expect(useWorkflowStore.getState().civitaiApiKey).toBe('')+ })++ it('points at the page that issues the key', () => {+ show()+ fireEvent.click(screen.getByText('Get a CivitAI API key'))+ expect(openExternal).toHaveBeenCalledWith(CIVITAI_KEY_PAGE)+ expect(CIVITAI_KEY_PAGE).toMatch(/^https:\/\/civitai\.com\//)+ })++ // Negative control: with no key stored there is nothing to remove, so the+ // button that would clear it is not offered.+ it('offers no Remove button when there is no key', () => {+ show()+ expect(screen.queryByText('Remove')).toBeNull()+ })++ it('explains in English why the key matters', () => {+ show()+ const text = document.body.textContent ?? ''+ expect(text).toMatch(/Most CivitAI downloads are refused without a key/)+ expect(text).toMatch(/HTTP 400 or 401/)+ })+})