Skip to content

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

feat(models): civitai.red mirror support (GH #53)

purple04b0ddb6edb3
diff --git a/src/api/__tests__/civitai-host.test.ts b/src/api/__tests__/civitai-host.test.ts
new file mode 100644
index 00000000..7c66e544
--- /dev/null
+++ b/src/api/__tests__/civitai-host.test.ts
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest'
+import { civitaiHostSwap, CIVITAI_DEFAULT_HOST } from '../discover'
+
+// GitHub #53 — civitai.red mirror support. The CivitAI API hands back absolute
+// civitai.com download URLs even when queried through a mirror, so the host has
+// to be rewritten or the actual file download still hits the blocked origin.
+describe('civitaiHostSwap (#53 mirror download URLs)', () => {
+ it('is a no-op on the default host', () => {
+ const u = 'https://civitai.com/api/download/models/12345'
+ expect(civitaiHostSwap(u, CIVITAI_DEFAULT_HOST)).toBe(u)
+ })
+
+ it('rewrites the host to the mirror', () => {
+ expect(civitaiHostSwap('https://civitai.com/api/download/models/12345', 'civitai.red'))
+ .toBe('https://civitai.red/api/download/models/12345')
+ })
+
+ it('keeps the path, query and token intact', () => {
+ expect(civitaiHostSwap('https://civitai.com/api/download/models/9?type=Model&token=abc', 'civitai.red'))
+ .toBe('https://civitai.red/api/download/models/9?type=Model&token=abc')
+ })
+
+ it('only rewrites the civitai.com origin, not the path', () => {
+ // A stray "civitai.com" later in the URL must not be touched.
+ expect(civitaiHostSwap('https://civitai.com/x/civitai.com/y', 'civitai.red'))
+ .toBe('https://civitai.red/x/civitai.com/y')
+ })
+
+ it('leaves non-civitai and undefined URLs alone', () => {
+ expect(civitaiHostSwap(undefined, 'civitai.red')).toBeUndefined()
+ expect(civitaiHostSwap('https://huggingface.co/x.safetensors', 'civitai.red'))
+ .toBe('https://huggingface.co/x.safetensors')
+ })
+
+ it('treats an empty host as the default (no swap)', () => {
+ const u = 'https://civitai.com/api/download/models/1'
+ expect(civitaiHostSwap(u, '')).toBe(u)
+ })
+})
diff --git a/src/api/discover.ts b/src/api/discover.ts
index 1caa503a..450aa51a 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -1749,10 +1749,25 @@ export interface CivitAIModelResult {
sourceUrl: string
}
+export const CIVITAI_DEFAULT_HOST = 'civitai.com'
+
+/**
+ * Rewrite a civitai.com absolute URL to the chosen mirror host (GitHub #53).
+ * The CivitAI API returns absolute civitai.com download/source URLs even when
+ * it is queried through a mirror, so without this the actual file download
+ * still hits the blocked origin for users on civitai.red. No-op on the default
+ * host. Exported + pure for unit tests.
+ */
+export function civitaiHostSwap(url: string | undefined, host: string): string | undefined {
+ if (!url || !host || host === CIVITAI_DEFAULT_HOST) return url
+ return url.replace(/^(https?:\/\/)civitai\.com/i, `$1${host}`)
+}
+
export async function searchCivitaiModels(
query: string,
type: 'Checkpoint' | 'LORA' | 'VAE' | 'TextualInversion' = 'Checkpoint',
- apiKey?: string
+ apiKey?: string,
+ host: string = CIVITAI_DEFAULT_HOST
): Promise<CivitAIModelResult[]> {
try {
const params = new URLSearchParams({
@@ -1768,7 +1783,7 @@ export async function searchCivitaiModels(
})
// Adding the user's API key as a bearer token unlocks the full catalog and
// lifts the per-IP rate limit. Falls back to anon access if no key is set.
- const url = `https://civitai.com/api/v1/models?${params}${apiKey ? `&token=${encodeURIComponent(apiKey)}` : ''}`
+ const url = `https://${host}/api/v1/models?${params}${apiKey ? `&token=${encodeURIComponent(apiKey)}` : ''}`
const text = await fetchExternal(url)
const data = JSON.parse(text)
const items: any[] = data.items ?? []
@@ -1805,13 +1820,13 @@ export async function searchCivitaiModels(
description: descParts.join(' — '),
type: type,
thumbnailUrl: thumb,
- downloadUrl,
+ downloadUrl: civitaiHostSwap(downloadUrl, host),
filename,
subfolder,
sizeGB: sizeKB > 0 ? Math.round(sizeKB / 1024 / 1024 * 10) / 10 : undefined,
stats: item.stats ? { downloads: item.stats.downloadCount || 0, likes: item.stats.thumbsUpCount || 0 } : undefined,
creator: item.creator?.username,
- sourceUrl: `https://civitai.com/models/${item.id}`,
+ sourceUrl: `https://${host}/models/${item.id}`,
}
})
} catch (err) {
diff --git a/src/api/workflows.ts b/src/api/workflows.ts
index 891046a0..2fecd420 100644
--- a/src/api/workflows.ts
+++ b/src/api/workflows.ts
@@ -393,9 +393,10 @@ function detectModelTypes(workflow: Record<string, any>): ModelType[] {
// ─── Fetch workflow from URL (supports JSON and ZIP) ───
export async function fetchWorkflowFromUrl(url: string, apiKey?: string): Promise<Record<string, any>> {
- // Append CivitAI API key if provided and URL is from CivitAI
+ // 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 && url.includes('civitai.com')) {
+ if (apiKey && /civitai\.(com|red)/i.test(url)) {
const sep = url.includes('?') ? '&' : '?'
finalUrl = `${url}${sep}token=${apiKey}`
}
@@ -596,7 +597,7 @@ interface CivitAIModel {
}>
}
-export async function searchCivitai(query: string): Promise<WorkflowSearchResult[]> {
+export async function searchCivitai(query: string, host: string = 'civitai.com'): Promise<WorkflowSearchResult[]> {
try {
const params = new URLSearchParams({
query,
@@ -604,7 +605,7 @@ export async function searchCivitai(query: string): Promise<WorkflowSearchResult
limit: '20',
sort: 'Most Downloaded',
})
- const text = await fetchExternal(`https://civitai.com/api/v1/models?${params}`)
+ 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')
@@ -615,8 +616,12 @@ export async function searchCivitai(query: string): Promise<WorkflowSearchResult
return items.map((item) => {
const version = item.modelVersions?.[0]
const thumb = version?.images?.[0]?.url
- // Prefer the version downloadUrl, fall back to first file
- const downloadUrl = version?.downloadUrl ?? version?.files?.[0]?.downloadUrl
+ // 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[] = []
@@ -634,7 +639,7 @@ export async function searchCivitai(query: string): Promise<WorkflowSearchResult
name: item.name || `CivitAI #${item.id}`,
description: descParts.join(' — '),
source: 'civitai' as const,
- sourceUrl: `https://civitai.com/models/${item.id}`,
+ sourceUrl: `https://${host}/models/${item.id}`,
thumbnailUrl: thumb,
modelTypes: ['unknown'] as ModelType[],
mode: 'image' as const,
@@ -651,7 +656,8 @@ export async function searchCivitai(query: string): Promise<WorkflowSearchResult
export async function searchWorkflows(
query: string,
- source: 'civitai' | 'templates'
+ source: 'civitai' | 'templates',
+ host: string = 'civitai.com'
): Promise<WorkflowSearchResult[]> {
if (source === 'templates') {
const templates = getBuiltinTemplates()
@@ -663,5 +669,5 @@ export async function searchWorkflows(
t.modelTypes.some(mt => mt.includes(lower))
)
}
- return searchCivitai(query)
+ return searchCivitai(query, host)
}
diff --git a/src/components/create/WorkflowSearchModal.tsx b/src/components/create/WorkflowSearchModal.tsx
index e87d900a..5f907205 100644
--- a/src/components/create/WorkflowSearchModal.tsx
+++ b/src/components/create/WorkflowSearchModal.tsx
@@ -49,7 +49,7 @@ export function WorkflowSearchModal({ open, onClose, modelName, modelType }: Pro
const initialSearchDone = useRef(false)
const templatesCached = useRef<WorkflowSearchResult[] | null>(null)
- const { installedWorkflows, installWorkflow, assignToModelName, civitaiApiKey, setCivitaiApiKey } = useWorkflowStore()
+ const { installedWorkflows, installWorkflow, assignToModelName, civitaiApiKey, setCivitaiApiKey, civitaiHost } = useWorkflowStore()
const [showApiKey, setShowApiKey] = useState(false)
const [showApiKeyInput, setShowApiKeyInput] = useState(false)
const [showApiKeyWarning, setShowApiKeyWarning] = useState(false)
@@ -82,7 +82,7 @@ export function WorkflowSearchModal({ open, onClose, modelName, modelType }: Pro
setError(null)
try {
const searchSource = source === 'discover' ? 'civitai' : 'templates'
- const r = await searchWorkflows(searchQuery, searchSource as any)
+ const r = await searchWorkflows(searchQuery, searchSource as any, civitaiHost)
setResults(r)
if (r.length === 0) setError('No workflows found. Try different search terms.')
} catch (err) {
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index 7066a7cb..fce19599 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -173,6 +173,9 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:
// diimmortalis described — empty list, no console output, looks like the
// button did nothing.
const [civitaiSearched, setCivitaiSearched] = useState(false)
+ // CivitAI mirror host (#53) — civitai.red for regions where .com is blocked.
+ const civitaiHost = useWorkflowStore((s) => s.civitaiHost)
+ const setCivitaiHost = useWorkflowStore((s) => s.setCivitaiHost)
const [loading, setLoading] = useState(false)
const [systemVRAM, setSystemVRAM] = useState<number | null>(null)
const [subTab, setSubTab] = useState<'uncensored' | 'mainstream'>('uncensored')
@@ -406,7 +409,8 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:
// finder. The model search and the workflow finder share the same backend
// credential, so plumbing a separate input here would just confuse users.
const apiKey = useWorkflowStore.getState().civitaiApiKey || undefined
- const results = await searchCivitaiModels(civitaiQuery, 'Checkpoint', apiKey)
+ const host = useWorkflowStore.getState().civitaiHost
+ const results = await searchCivitaiModels(civitaiQuery, 'Checkpoint', apiKey, host)
setCivitaiResults(results)
setCivitaiSearching(false)
}
@@ -821,7 +825,30 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0 }:
{/* CivitAI Search (Image & Video) */}
{(isImage || isVideo) && (
<GlassCard className="p-4 space-y-3">
- <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Search CivitAI</h3>
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Search CivitAI</h3>
+ {/* Mirror toggle (#53) — civitai.red for regions where .com is blocked. */}
+ <div className="flex items-center gap-1 text-[10px]">
+ <span className="text-gray-400 dark:text-gray-500 mr-0.5">mirror</span>
+ {(['civitai.com', 'civitai.red'] as const).map((h) => (
+ <button
+ key={h}
+ onClick={() => setCivitaiHost(h)}
+ title={h === 'civitai.red'
+ ? 'Use the civitai.red mirror — for regions where civitai.com is blocked'
+ : 'Use civitai.com (default)'}
+ className={
+ 'px-1.5 py-0.5 rounded font-mono transition-colors ' +
+ (civitaiHost === h
+ ? 'bg-gray-200 dark:bg-white/15 text-gray-900 dark:text-white'
+ : 'text-gray-400 hover:text-gray-700 dark:hover:text-gray-200')
+ }
+ >
+ {h.replace('civitai', '')}
+ </button>
+ ))}
+ </div>
+ </div>
<div className="flex gap-2 w-1/2 mx-auto">
<input
value={civitaiQuery}
diff --git a/src/stores/workflowStore.ts b/src/stores/workflowStore.ts
index 68c281a0..09b1d97c 100644
--- a/src/stores/workflowStore.ts
+++ b/src/stores/workflowStore.ts
@@ -11,6 +11,9 @@ interface WorkflowState {
modelNameAssignments: Record<string, string>
// CivitAI API key for downloads
civitaiApiKey: string
+ // CivitAI host — civitai.com by default; swappable to a mirror like
+ // civitai.red for regions where civitai.com is blocked (GitHub #53).
+ civitaiHost: string
installWorkflow: (wf: WorkflowTemplate) => void
removeWorkflow: (id: string) => void
@@ -20,6 +23,7 @@ interface WorkflowState {
unassignModelName: (modelName: string) => void
getWorkflowForModel: (modelName: string, modelType: ModelType) => WorkflowTemplate | null
setCivitaiApiKey: (key: string) => void
+ setCivitaiHost: (host: string) => void
}
export const useWorkflowStore = create<WorkflowState>()(
@@ -29,6 +33,7 @@ export const useWorkflowStore = create<WorkflowState>()(
modelTypeAssignments: {},
modelNameAssignments: {},
civitaiApiKey: '',
+ civitaiHost: 'civitai.com',
installWorkflow: (wf) => set((s) => ({
installedWorkflows: [wf, ...s.installedWorkflows.filter(w => w.id !== wf.id)],
@@ -73,6 +78,11 @@ export const useWorkflowStore = create<WorkflowState>()(
setCivitaiApiKey: (key) => set({ civitaiApiKey: key }),
+ // Accept "civitai.red", "https://civitai.red/", etc. — store the bare
+ // host. Empty falls back to the canonical civitai.com (#53).
+ setCivitaiHost: (host) =>
+ set({ civitaiHost: (host || 'civitai.com').trim().replace(/^https?:\/\//i, '').replace(/\/+$/, '') || 'civitai.com' }),
+
getWorkflowForModel: (modelName, modelType) => {
const state = get()
// Priority 1: specific model name assignment