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(workflows): Tags & Workflows Menu, add tags and model workflow matching

Kizerfluid324fb9691bfa
diff --git a/src/components/create/WorkflowFinder.tsx b/src/components/create/WorkflowFinder.tsx
index d5e4d09a..c2159e21 100644
--- a/src/components/create/WorkflowFinder.tsx
+++ b/src/components/create/WorkflowFinder.tsx
@@ -1,71 +1,137 @@
-import { useState } from 'react'
-import { X, Workflow } from 'lucide-react'
+import { Workflow } from 'lucide-react'
+import { isVideoModelType, type ModelType, } from '../../api/comfyui'
import { useWorkflowStore } from '../../stores/workflowStore'
-import { WorkflowSearchModal } from './WorkflowSearchModal'
-import type { ModelType } from '../../api/comfyui'
+import { Select } from './ui/Select'
interface Props {
modelName: string
modelType: ModelType
}
-export function WorkflowFinder({ modelName, modelType }: Props) {
- const [modalOpen, setModalOpen] = useState(false)
+export function WorkflowFinder({
+ modelName,
+ modelType,
+}: Props) {
const {
+ workflowTags,
getWorkflowForModel,
+ getMatchingWorkflows,
assignToModelName,
unassignModelName,
unassignModelType,
} = useWorkflowStore()
- const activeWorkflow = getWorkflowForModel(modelName, modelType)
+ const mode = isVideoModelType(modelType)
+ ? 'video'
+ : 'image'
- return (
- <>
- <div>
- <label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-1.5 flex items-center gap-1.5">
- <Workflow size={12} />
- Workflow
- </label>
+ const matchingWorkflows = getMatchingWorkflows(
+ modelName,
+ mode,
+ )
+
+ const activeWorkflow = getWorkflowForModel(
+ modelName,
+ modelType,
+ )
+
+ const selectedWorkflow =
+ activeWorkflow &&
+ matchingWorkflows.some(
+ (workflow) => workflow.id === activeWorkflow.id,
+ )
+ ? activeWorkflow
+ : null
- {/* Load Workflow button - opens the finder modal */}
- <button
- onClick={() => setModalOpen(true)}
- className="w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-gray-900 dark:text-white text-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors text-left"
- >
- {activeWorkflow ? activeWorkflow.name : 'Auto'}
- </button>
+ const handleSelection = (
+ workflowId: string,
+ ) => {
+ if (!workflowId) {
+ unassignModelName(modelName)
+ unassignModelType(modelType)
+ return
+ }
- {/* Active workflow info badge + clear */}
- {activeWorkflow && (
- <div className="mt-1 flex items-center gap-1.5">
- <span className="inline-block px-1.5 py-0.5 rounded text-[10px] font-medium bg-emerald-500/20 text-emerald-300">
- {activeWorkflow.source}
- </span>
- <span className="text-[10px] text-gray-500 truncate">
- {activeWorkflow.mode === 'video' ? 'Video' : activeWorkflow.mode === 'both' ? 'Image+Video' : 'Image'}
- </span>
- <button
- onClick={(e) => {
- e.stopPropagation()
- unassignModelName(modelName)
- unassignModelType(modelType)
- }}
- className="ml-auto text-gray-500 hover:text-red-400 transition-colors"
- title="Reset to Auto"
- >
- <X size={12} />
- </button>
- </div>
- )}
- </div>
+ // A specific model selection should take priority over any legacy
+ // model-type-wide assignment.
+ unassignModelType(modelType)
+ assignToModelName(modelName, workflowId)
+ }
- <WorkflowSearchModal
- open={modalOpen}
- onClose={() => setModalOpen(false)}
- modelName={modelName}
- modelType={modelType}
- />
- </>
+ return (
+ <div>
+ <label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">
+ <Workflow size={12} />
+ Workflow
+ </label>
+
+ {matchingWorkflows.length > 0 ? (
+ <Select
+ value={selectedWorkflow?.id ?? ''}
+ onChange={handleSelection}
+ placeholder="Auto"
+ maxHeight={240}
+ options={[
+ {
+ value: '',
+ label: 'Auto',
+ sublabel: 'Use the built-in workflow',
+ },
+ ...matchingWorkflows.map((workflow) => ({
+ value: workflow.id,
+ label: workflow.name,
+ sublabel:
+ workflow.mode === 'both'
+ ? 'Image + Video'
+ : workflow.mode === 'video'
+ ? 'Video'
+ : 'Image',
+ badge: {
+ label: workflow.mode.toUpperCase(),
+ color:
+ 'bg-violet-500/15 text-violet-300',
+ },
+ })),
+ ]}
+ />
+ ) : (
+ <div className="flex h-[var(--control-h-md)] w-full items-center rounded-[var(--radius-control)] border border-white/[0.08] bg-white/[0.04] px-2.5 text-sm text-gray-500">
+ No tagged workflows available
+ </div>
+ )}
+
+ {matchingWorkflows.length === 0 ? (
+ <p className="mt-1.5 text-[10px] leading-relaxed text-gray-500">
+ Assign matching tags to this model and a workflow in Tags &amp; Workflows.
+ </p>
+ ) : selectedWorkflow ? (
+ <div className="mt-1.5 flex flex-wrap items-center gap-1">
+ {(workflowTags[selectedWorkflow.id] ?? []).map(
+ (tagId) => (
+ <span
+ key={tagId}
+ className="rounded bg-violet-500/15 px-1.5 py-0.5 text-[10px] text-violet-600 dark:text-violet-300"
+ >
+ {
+ useWorkflowStore
+ .getState()
+ .tags.find(
+ (tag) => tag.id === tagId,
+ )?.name
+ }
+ </span>
+ ),
+ )}
+ </div>
+ ) : (
+ <p className="mt-1.5 text-[10px] text-gray-500">
+ {matchingWorkflows.length} compatible{' '}
+ {matchingWorkflows.length === 1
+ ? 'workflow'
+ : 'workflows'}{' '}
+ available
+ </p>
+ )}
+ </div>
)
-}
+}
\ No newline at end of file
diff --git a/src/components/create/experimental/AdvancedDrawer.tsx b/src/components/create/experimental/AdvancedDrawer.tsx
index 1ef66dd0..bff2818f 100644
--- a/src/components/create/experimental/AdvancedDrawer.tsx
+++ b/src/components/create/experimental/AdvancedDrawer.tsx
@@ -1,7 +1,11 @@
import { Drawer } from '../ui/Drawer'
import { WorkflowFinder } from '../WorkflowFinder'
import { useCreateStore } from '../../../stores/createStore'
-import { classifyModel } from '../../../api/comfyui'
+import {
+ classifyModel,
+ isI2VModel,
+ isT2VCapable,
+} from '../../../api/comfyui'
import { ParamGroups } from './ParamGroups'
export function AdvancedDrawer({
@@ -13,10 +17,53 @@ export function AdvancedDrawer({
}) {
const mode = useCreateStore((state) => state.mode)
const backend = useCreateStore((state) => state.backend)
- const imageModel = useCreateStore((state) => state.imageModel)
- const videoModel = useCreateStore((state) => state.videoModel)
+ const intent = useCreateStore((state) => state.intent())
+
+ const imageModel = useCreateStore(
+ (state) => state.imageModel,
+ )
+
+ const videoModel = useCreateStore(
+ (state) => state.videoModel,
+ )
+
+ const videoModels = useCreateStore(
+ (state) => state.videoModelList,
+ )
+
+ // Match the model coercion used by the visible picker and generation path.
+ // Animate/Extend require I2V-capable models; ordinary Video requires T2V.
+ let effectiveVideoModel = videoModel
+
+ if (videoModels.length > 0) {
+ const compatibleModels =
+ intent === 'animate' || intent === 'extend'
+ ? videoModels.filter((model) =>
+ isI2VModel(model.name),
+ )
+ : videoModels.filter((model) =>
+ isT2VCapable(model.name),
+ )
+
+ const storedModelIsCompatible =
+ compatibleModels.some(
+ (model) => model.name === videoModel,
+ )
+
+ if (
+ compatibleModels.length > 0 &&
+ !storedModelIsCompatible
+ ) {
+ effectiveVideoModel =
+ compatibleModels[0].name
+ }
+ }
+
+ const modelName =
+ mode === 'image'
+ ? imageModel
+ : effectiveVideoModel
- const modelName = mode === 'image' ? imageModel : videoModel
const modelType = classifyModel(modelName)
return (
diff --git a/src/components/create/ui/Tooltip.tsx b/src/components/create/ui/Tooltip.tsx
index 017adfa6..32f72f60 100644
--- a/src/components/create/ui/Tooltip.tsx
+++ b/src/components/create/ui/Tooltip.tsx
@@ -15,16 +15,48 @@ export function Tooltip({ content, children, side = 'top', delay = 400, classNam
const [show, setShow] = useState(false)
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
- const open = () => { timer.current = setTimeout(() => setShow(true), delay) }
- const close = () => { if (timer.current) clearTimeout(timer.current); setShow(false) }
+const open = () => {
+ if (timer.current) {
+ clearTimeout(timer.current)
+ }
+
+ timer.current = setTimeout(() => {
+ setShow(true)
+ timer.current = null
+ }, delay)
+}
+
+const close = () => {
+ if (timer.current) {
+ clearTimeout(timer.current)
+ timer.current = null
+ }
+
+ setShow(false)
+}
+
+const handleFocus = (
+ event: React.FocusEvent<HTMLSpanElement>,
+) => {
+ const target = event.target as HTMLElement
+
+ // Show focus tooltips for keyboard navigation, but not when a mouse
+ // click leaves the wrapped button focused.
+ if (target.matches(':focus-visible')) {
+ open()
+ }
+}
+
useEffect(() => () => { if (timer.current) clearTimeout(timer.current) }, [])
return (
- <span
+ <span
className={cn('relative inline-flex', className)}
onMouseEnter={open}
onMouseLeave={close}
- onFocus={open}
+ onPointerDown={close}
+ onClick={close}
+ onFocus={handleFocus}
onBlur={close}
>
{children}
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index 3203d5d6..48d1601a 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -34,6 +34,7 @@ import { CloudExampleModal } from '../cloud/CloudExampleModal'
import { ShortcutsModal } from './ShortcutsModal'
import { CreditsExhaustedModal } from './CreditsExhaustedModal'
import { Titlebar } from './Titlebar'
+import { TagsAndWorkflowsPage } from '../workflows/TagsAndWorkflowsPage'
// The backup triad must never write %APPDATA%/store_backup.json before the
// restore decision — on a post-NSIS boot the first doBackup would otherwise
@@ -794,9 +795,16 @@ export function AppShell() {
<StorageQuotaToast />
<div className="flex-1 flex overflow-hidden gap-2 p-2">
{!isComparing && <Sidebar />}
- <main className={`overflow-hidden rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] ${currentView === 'models' ? 'flex-none w-[85%] mx-auto' : 'flex-1'}`}>
+ <main
+ className={`overflow-hidden rounded-xl bg-white dark:bg-[#1e1e1e] ring-1 ring-black/[0.04] dark:ring-white/[0.05] ${
+ currentView === 'models' || currentView === 'workflows'
+ ? 'flex-none w-[85%] mx-auto'
+ : 'flex-1'
+ }`}
+ >
{currentView === 'chat' && <ErrorBoundary><ChatView /></ErrorBoundary>}
{currentView === 'models' && <ErrorBoundary><ModelManager /></ErrorBoundary>}
+ {currentView === 'workflows' && <ErrorBoundary><TagsAndWorkflowsPage /></ErrorBoundary>}
{currentView === 'benchmark' && <ErrorBoundary><BenchmarkView /></ErrorBoundary>}
{currentView === 'settings' && <ErrorBoundary><SettingsPage /></ErrorBoundary>}
{currentView === 'create' && <ErrorBoundary><CreateExperimental /></ErrorBoundary>}
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx
index 2a72f4c0..615c862c 100644
--- a/src/components/layout/Header.tsx
+++ b/src/components/layout/Header.tsx
@@ -275,6 +275,7 @@ export function Header() {
}>
{textNav('chat', 'Chat')}
{textNav('create', 'Create')}
+ {textNav('workflows', 'Tags & Workflows')}
<button
onClick={() => {
@@ -316,6 +317,7 @@ export function Header() {
{dropdownNav('chat', 'Chat')}
{dropdownNav('create', 'Create')}
+ {dropdownNav('workflows', 'Tags & Workflows')}
<button
onClick={() => {
diff --git a/src/components/workflows/TagPicker.tsx b/src/components/workflows/TagPicker.tsx
new file mode 100644
index 00000000..37c08884
--- /dev/null
+++ b/src/components/workflows/TagPicker.tsx
@@ -0,0 +1,57 @@
+import type { WorkflowTag } from '../../types/workflows'
+
+interface Props {
+ tags: WorkflowTag[]
+ selectedIds: string[]
+ onChange: (tagIds: string[]) => void
+ emptyLabel?: string
+}
+
+export function TagPicker({
+ tags,
+ selectedIds,
+ onChange,
+ emptyLabel = 'Create a tag first',
+}: Props) {
+ const selected = new Set(selectedIds)
+
+ const toggleTag = (tagId: string) => {
+ if (selected.has(tagId)) {
+ onChange(selectedIds.filter((id) => id !== tagId))
+ return
+ }
+
+ onChange([...selectedIds, tagId])
+ }
+
+ if (tags.length === 0) {
+ return (
+ <p className="text-xs text-gray-500 dark:text-gray-500">
+ {emptyLabel}
+ </p>
+ )
+ }
+
+ return (
+ <div className="flex flex-wrap gap-1.5">
+ {tags.map((tag) => {
+ const active = selected.has(tag.id)
+
+ return (
+ <button
+ key={tag.id}
+ type="button"
+ onClick={() => toggleTag(tag.id)}
+ className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
+ active
+ ? 'border-violet-500/50 bg-violet-500/20 text-violet-700 dark:text-violet-200'
+ : 'border-gray-200 bg-gray-50 text-gray-500 hover:border-gray-300 hover:text-gray-800 dark:border-white/10 dark:bg-white/5 dark:text-gray-400 dark:hover:border-white/20 dark:hover:text-white'
+ }`}
+ >
+ {tag.name}
+ </button>
+ )
+ })}
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/src/components/workflows/TagsAndWorkflowsPage.tsx b/src/components/workflows/TagsAndWorkflowsPage.tsx
new file mode 100644
index 00000000..9ffa9661
--- /dev/null
+++ b/src/components/workflows/TagsAndWorkflowsPage.tsx
@@ -0,0 +1,659 @@
+import { useMemo, useRef, useState } from 'react'
+import {
+ Check,
+ FileJson,
+ Pencil,
+ Plus,
+ RefreshCw,
+ Search,
+ Tags,
+ Trash2,
+ Upload,
+ Workflow,
+ X,
+} from 'lucide-react'
+import { v4 as uuid } from 'uuid'
+import { parseImportedWorkflow, validateWorkflowJson } from '../../api/workflows'
+import { useModels } from '../../hooks/useModels'
+import {
+ useWorkflowStore,
+ workflowModelKey,
+ type WorkflowTagMode,
+} from '../../stores/workflowStore'
+import { TagPicker } from './TagPicker'
+
+type PageTab = 'workflows' | 'models' | 'tags'
+type ModelFilter = 'all' | WorkflowTagMode
+
+const tabs: Array<{
+ id: PageTab
+ label: string
+}> = [
+ { id: 'workflows', label: 'Workflows' },
+ { id: 'models', label: 'Models' },
+ { id: 'tags', label: 'Tags' },
+]
+
+export function TagsAndWorkflowsPage() {
+ const [activeTab, setActiveTab] = useState<PageTab>('workflows')
+
+ const {
+ installedWorkflows,
+ tags,
+ workflowTags,
+ modelTags,
+ installWorkflow,
+ removeWorkflow,
+ createTag,
+ renameTag,
+ deleteTag,
+ setWorkflowTags,
+ setModelTags,
+ } = useWorkflowStore()
+
+ const {
+ models,
+ fetchModels,
+ } = useModels()
+
+ const [importName, setImportName] = useState('')
+ const [importJson, setImportJson] = useState('')
+ const [importError, setImportError] = useState<string | null>(null)
+ const [importSuccess, setImportSuccess] = useState<string | null>(null)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+
+ const [newTagName, setNewTagName] = useState('')
+ const [editingTagId, setEditingTagId] = useState<string | null>(null)
+ const [editingTagName, setEditingTagName] = useState('')
+
+ const [modelSearch, setModelSearch] = useState('')
+ const [modelFilter, setModelFilter] = useState<ModelFilter>('all')
+
+ const comfyModels = useMemo(() => {
+ const query = modelSearch.trim().toLowerCase()
+
+ return models
+ .filter((model) => {
+ if (model.type !== 'image' && model.type !== 'video') {
+ return false
+ }
+
+ if (model.providerName !== 'ComfyUI') {
+ return false
+ }
+
+ if (modelFilter !== 'all' && model.type !== modelFilter) {
+ return false
+ }
+
+ if (query && !model.name.toLowerCase().includes(query)) {
+ return false
+ }
+
+ return true
+ })
+ .sort((left, right) => {
+ if (left.type !== right.type) {
+ return left.type.localeCompare(right.type)
+ }
+
+ return left.name.localeCompare(right.name)
+ })
+ }, [models, modelFilter, modelSearch])
+
+ const importWorkflowJson = (
+ rawText: string,
+ suggestedName?: string,
+ ) => {
+ setImportError(null)
+ setImportSuccess(null)
+
+ try {
+ const json = JSON.parse(rawText)
+
+ if (!validateWorkflowJson(json)) {
+ setImportError(
+ 'Invalid workflow. Export it from ComfyUI using Save (API Format).',
+ )
+ return
+ }
+
+ const name =
+ importName.trim() ||
+ suggestedName?.trim() ||
+ 'Imported Workflow'
+
+ const parsed = parseImportedWorkflow(
+ name,
+ json,
+ 'manual',
+ )
+
+ // Re-importing a workflow with the same name updates it in place. Keeping
+ // the existing ID also keeps any tags already assigned to that workflow.
+ const existing = installedWorkflows.find(
+ (workflow) =>
+ workflow.source === 'manual' &&
+ workflow.name.toLowerCase() === name.toLowerCase(),
+ )
+
+ installWorkflow({
+ ...parsed,
+ id: existing?.id ?? uuid(),
+ installedAt: existing?.installedAt ?? Date.now(),
+ })
+
+ setImportName('')
+ setImportJson('')
+ setImportSuccess(
+ existing
+ ? `Updated "${name}".`
+ : `Installed "${name}".`,
+ )
+ } catch (error) {
+ setImportError(
+ error instanceof SyntaxError
+ ? 'The selected file does not contain valid JSON.'
+ : `Import failed: ${
+ error instanceof Error
+ ? error.message
+ : String(error)
+ }`,
+ )
+ }
+ }
+
+ const handleFileImport = async (
+ event: React.ChangeEvent<HTMLInputElement>,
+ ) => {
+ const file = event.target.files?.[0]
+
+ if (!file) {
+ return
+ }
+
+ try {
+ const text = await file.text()
+ const suggestedName = file.name.replace(/\.json$/i, '')
+
+ importWorkflowJson(text, suggestedName)
+ } catch (error) {
+ setImportError(
+ `Could not read file: ${
+ error instanceof Error
+ ? error.message
+ : String(error)
+ }`,
+ )
+ } finally {
+ event.target.value = ''
+ }
+ }
+
+ const handleCreateTag = () => {
+ const id = createTag(newTagName)
+
+ if (id) {
+ setNewTagName('')
+ }
+ }
+
+ const beginRenameTag = (
+ tagId: string,
+ currentName: string,
+ ) => {
+ setEditingTagId(tagId)
+ setEditingTagName(currentName)
+ }
+
+ const finishRenameTag = () => {
+ if (!editingTagId) {
+ return
+ }
+
+ renameTag(editingTagId, editingTagName)
+ setEditingTagId(null)
+ setEditingTagName('')
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="border-b border-gray-200 px-6 py-5 dark:border-white/10">
+ <div className="flex items-center gap-3">
+ <div className="rounded-xl bg-violet-500/10 p-2.5 text-violet-600 dark:text-violet-300">
+ <Tags size={22} />
+ </div>
+
+ <div>
+ <h1 className="text-xl font-semibold text-gray-900 dark:text-white">
+ Tags &amp; Workflows
+ </h1>
+
+ <p className="mt-0.5 text-sm text-gray-500 dark:text-gray-400">
+ Install ComfyUI workflows and match them to models using reusable tags.
+ </p>
+ </div>
+ </div>
+
+ <div className="mt-5 flex gap-1 rounded-xl bg-gray-100 p-1 dark:bg-white/5">
+ {tabs.map((tab) => (
+ <button
+ key={tab.id}
+ type="button"
+ onClick={() => setActiveTab(tab.id)}
+ className={`flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
+ activeTab === tab.id
+ ? 'bg-white text-gray-900 shadow-sm dark:bg-white/10 dark:text-white'
+ : 'text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white'
+ }`}
+ >
+ {tab.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto p-6">
+ {activeTab === 'workflows' && (
+ <div className="mx-auto max-w-5xl space-y-6">
+ <section className="rounded-2xl border border-gray-200 bg-gray-50 p-5 dark:border-white/10 dark:bg-white/[0.025]">
+ <div className="flex items-center gap-2">
+ <Upload size={17} className="text-violet-500" />
+ <h2 className="font-semibold text-gray-900 dark:text-white">
+ Install workflow
+ </h2>
+ </div>
+
+ <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
+ Import a ComfyUI API-format JSON file. Editable graph exports are not supported.
+ </p>
+
+ <div className="mt-4 grid gap-3 md:grid-cols-[1fr_auto]">
+ <input
+ value={importName}
+ onChange={(event) => setImportName(event.target.value)}
+ placeholder="Workflow name (optional)"
+ className="rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 outline-none focus:border-violet-400 dark:border-white/10 dark:bg-white/5 dark:text-white"
+ />
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".json,application/json"
+ onChange={handleFileImport}
+ className="hidden"
+ />
+
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ className="flex items-center justify-center gap-2 rounded-lg bg-violet-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-violet-500"
+ >
+ <FileJson size={16} />
+ Choose API JSON
+ </button>
+ </div>
+
+ <div className="mt-3">
+ <textarea
+ value={importJson}
+ onChange={(event) => setImportJson(event.target.value)}
+ placeholder='Or paste API JSON here: {"1":{"class_type":"KSampler",...}}'
+ className="h-32 w-full resize-y rounded-lg border border-gray-200 bg-white px-3 py-2 font-mono text-xs text-gray-900 outline-none focus:border-violet-400 dark:border-white/10 dark:bg-white/5 dark:text-white"
+ />
+
+ <button
+ type="button"
+ disabled={!importJson.trim()}
+ onClick={() => importWorkflowJson(importJson)}
+ className="mt-2 rounded-lg bg-gray-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-40 dark:bg-white dark:text-gray-900 dark:hover:bg-gray-200"
+ >
+ Install pasted workflow
+ </button>
+ </div>
+
+ {importError && (
+ <div className="mt-3 rounded-lg border border-red-500/20 bg-red-500/10 px-3 py-2 text-xs text-red-600 dark:text-red-300">
+ {importError}
+ </div>
+ )}
+
+ {importSuccess && (
+ <div className="mt-3 rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-3 py-2 text-xs text-emerald-700 dark:text-emerald-300">
+ {importSuccess}
+ </div>
+ )}
+ </section>
+
+ <section>
+ <div className="mb-3 flex items-center gap-2">
+ <Workflow size={17} />
+ <h2 className="font-semibold text-gray-900 dark:text-white">
+ Installed workflows
+ </h2>
+
+ <span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-500 dark:bg-white/5 dark:text-gray-400">
+ {installedWorkflows.length}
+ </span>
+ </div>
+
+ {installedWorkflows.length === 0 ? (
+ <div className="rounded-2xl border border-dashed border-gray-300 px-6 py-12 text-center dark:border-white/15">
+ <Workflow
+ size={28}
+ className="mx-auto text-gray-400"
+ />
+
+ <p className="mt-3 text-sm text-gray-500">
+ No workflows are installed yet.
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3">
+ {installedWorkflows.map((workflow) => (
+ <article
+ key={workflow.id}
+ className="rounded-2xl border border-gray-200 bg-white p-4 dark:border-white/10 dark:bg-white/[0.025]"
+ >
+ <div className="flex gap-4">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="truncate font-medium text-gray-900 dark:text-white">
+ {workflow.name}
+ </h3>
+
+ <span className="rounded bg-gray-100 px-1.5 py-0.5 text-[10px] uppercase text-gray-500 dark:bg-white/5 dark:text-gray-400">
+ {workflow.mode}
+ </span>
+
+ <span className="rounded bg-gray-100 px-1.5 py-0.5 text-[10px] uppercase text-gray-500 dark:bg-white/5 dark:text-gray-400">
+ {workflow.source}
+ </span>
+ </div>
+
+ {workflow.description && (
+ <p className="mt-1 line-clamp-2 text-xs text-gray-500 dark:text-gray-400">
+ {workflow.description}
+ </p>
+ )}
+
+ <div className="mt-3">
+ <p className="mb-1.5 text-[10px] font-medium uppercase tracking-wider text-gray-500">
+ Compatibility tags
+ </p>
+
+ <TagPicker
+ tags={tags}
+ selectedIds={workflowTags[workflow.id] ?? []}
+ onChange={(tagIds) =>
+ setWorkflowTags(
+ workflow.id,
+ tagIds,
+ )
+ }
+ />
+ </div>
+ </div>
+
+ <button
+ type="button"
+ title="Remove workflow"
+ onClick={() => {
+ const confirmed = window.confirm(
+ `Remove "${workflow.name}"?`,
+ )
+
+ if (confirmed) {
+ removeWorkflow(workflow.id)
+ }
+ }}
+ className="self-start rounded-lg p-2 text-gray-400 transition-colors hover:bg-red-500/10 hover:text-red-500"
+ >
+ <Trash2 size={16} />
+ </button>
+ </div>
+ </article>
+ ))}
+ </div>
+ )}
+ </section>
+ </div>
+ )}
+
+ {activeTab === 'models' && (
+ <div className="mx-auto max-w-5xl space-y-4">
+ <div className="flex flex-col gap-3 md:flex-row">
+ <div className="relative flex-1">
+ <Search
+ size={15}
+ className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
+ />
+
+ <input
+ value={modelSearch}
+ onChange={(event) =>
+ setModelSearch(event.target.value)
+ }
+ placeholder="Search installed models"
+ className="w-full rounded-lg border border-gray-200 bg-white py-2 pl-9 pr-3 text-sm text-gray-900 outline-none focus:border-violet-400 dark:border-white/10 dark:bg-white/5 dark:text-white"
+ />
+ </div>
+
+ <div className="flex gap-1 rounded-lg bg-gray-100 p-1 dark:bg-white/5">
+ {(['all', 'image', 'video'] as ModelFilter[]).map(
+ (filter) => (
+ <button
+ key={filter}
+ type="button"
+ onClick={() => setModelFilter(filter)}
+ className={`rounded-md px-3 py-1.5 text-xs capitalize transition-colors ${
+ modelFilter === filter
+ ? 'bg-white text-gray-900 shadow-sm dark:bg-white/10 dark:text-white'
+ : 'text-gray-500 dark:text-gray-400'
+ }`}
+ >
+ {filter}
+ </button>
+ ),
+ )}
+ </div>
+
+ <button
+ type="button"
+ onClick={() => void fetchModels()}
+ className="flex items-center justify-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-600 transition-colors hover:bg-gray-100 dark:border-white/10 dark:text-gray-300 dark:hover:bg-white/5"
+ >
+ <RefreshCw size={15} />
+ Refresh
+ </button>
+ </div>
+
+ {comfyModels.length === 0 ? (
+ <div className="rounded-2xl border border-dashed border-gray-300 px-6 py-12 text-center dark:border-white/15">
+ <p className="text-sm text-gray-500">
+ No matching ComfyUI image or video models were found.
+ </p>
+
+ <p className="mt-1 text-xs text-gray-400">
+ Make sure ComfyUI is running, then press Refresh.
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3">
+ {comfyModels.map((model) => {
+ const mode = model.type as WorkflowTagMode
+ const key = workflowModelKey(
+ model.name,
+ mode,
+ )
+
+ return (
+ <article
+ key={key}
+ className="rounded-2xl border border-gray-200 bg-white p-4 dark:border-white/10 dark:bg-white/[0.025]"
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="min-w-0 flex-1 break-all font-medium text-gray-900 dark:text-white">
+ {model.name}
+ </h3>
+
+ <span className="rounded bg-gray-100 px-2 py-0.5 text-[10px] font-medium uppercase text-gray-500 dark:bg-white/5 dark:text-gray-400">
+ {mode}
+ </span>
+ </div>
+
+ <div className="mt-3">
+ <p className="mb-1.5 text-[10px] font-medium uppercase tracking-wider text-gray-500">
+ Model tags
+ </p>
+
+ <TagPicker
+ tags={tags}
+ selectedIds={modelTags[key] ?? []}
+ onChange={(tagIds) =>
+ setModelTags(
+ model.name,
+ mode,
+ tagIds,
+ )
+ }
+ />
+ </div>
+ </article>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ )}
+
+ {activeTab === 'tags' && (
+ <div className="mx-auto max-w-3xl">
+ <div className="flex gap-2">
+ <input
+ value={newTagName}
+ onChange={(event) =>
+ setNewTagName(event.target.value)
+ }
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ handleCreateTag()
+ }
+ }}
+ placeholder="New tag, for example Wan 2.2"
+ className="min-w-0 flex-1 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-900 outline-none focus:border-violet-400 dark:border-white/10 dark:bg-white/5 dark:text-white"
+ />
+
+ <button
+ type="button"
+ disabled={!newTagName.trim()}
+ onClick={handleCreateTag}
+ className="flex items-center gap-2 rounded-lg bg-violet-600 px-4 py-2 text-sm font-medium text-white hover:bg-violet-500 disabled:opacity-40"
+ >
+ <Plus size={16} />
+ Create tag
+ </button>
+ </div>
+
+ <div className="mt-5 space-y-2">
+ {tags.length === 0 ? (
+ <div className="rounded-2xl border border-dashed border-gray-300 px-6 py-12 text-center dark:border-white/15">
+ <Tags
+ size={28}
+ className="mx-auto text-gray-400"
+ />
+
+ <p className="mt-3 text-sm text-gray-500">
+ No tags have been created.
+ </p>
+ </div>
+ ) : (
+ tags.map((tag) => (
+ <div
+ key={tag.id}
+ className="flex items-center gap-3 rounded-xl border border-gray-200 bg-white px-4 py-3 dark:border-white/10 dark:bg-white/[0.025]"
+ >
+ {editingTagId === tag.id ? (
+ <>
+ <input
+ value={editingTagName}
+ onChange={(event) =>
+ setEditingTagName(
+ event.target.value,
+ )
+ }
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ finishRenameTag()
+ }
+
+ if (event.key === 'Escape') {
+ setEditingTagId(null)
+ }
+ }}
+ autoFocus
+ className="min-w-0 flex-1 rounded-lg border border-violet-400 bg-white px-2 py-1 text-sm text-gray-900 outline-none dark:bg-white/5 dark:text-white"
+ />
+
+ <button
+ type="button"
+ onClick={finishRenameTag}
+ className="rounded-lg p-2 text-emerald-500 hover:bg-emerald-500/10"
+ >
+ <Check size={16} />
+ </button>
+
+ <button
+ type="button"
+ onClick={() => setEditingTagId(null)}
+ className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 dark:hover:bg-white/5"
+ >
+ <X size={16} />
+ </button>
+ </>
+ ) : (
+ <>
+ <span className="min-w-0 flex-1 font-medium text-gray-900 dark:text-white">
+ {tag.name}
+ </span>
+
+ <button
+ type="button"
+ onClick={() =>
+ beginRenameTag(
+ tag.id,
+ tag.name,
+ )
+ }
+ className="rounded-lg p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-white/5 dark:hover:text-white"
+ >
+ <Pencil size={15} />
+ </button>
+
+ <button
+ type="button"
+ onClick={() => {
+ const confirmed = window.confirm(
+ `Delete the tag "${tag.name}" from all workflows and models?`,
+ )
+
+ if (confirmed) {
+ deleteTag(tag.id)
+ }
+ }}
+ className="rounded-lg p-2 text-gray-400 hover:bg-red-500/10 hover:text-red-500"
+ >
+ <Trash2 size={15} />
+ </button>
+ </>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
\ No newline at end of file
diff --git a/src/stores/__tests__/workflowStore.test.ts b/src/stores/__tests__/workflowStore.test.ts
index e00c6767..a31b1177 100644
--- a/src/stores/__tests__/workflowStore.test.ts
+++ b/src/stores/__tests__/workflowStore.test.ts
@@ -23,7 +23,11 @@ const INITIAL_STATE = {
installedWorkflows: [],
modelTypeAssignments: {},
modelNameAssignments: {},
+ tags: [],
+ workflowTags: {},
+ modelTags: {},
civitaiApiKey: '',
+ civitaiHost: 'civitai.com',
}
// ═══════════════════════════════════════════════════════════════
@@ -271,6 +275,376 @@ describe('workflowStore', () => {
})
})
+ // ── workflow and model tags ──────────────────────────────────
+
+ describe('tags', () => {
+ it('creates a trimmed tag and deduplicates names case-insensitively', () => {
+ const firstId = useWorkflowStore
+ .getState()
+ .createTag(' Wan 2.2 ')
+
+ const duplicateId = useWorkflowStore
+ .getState()
+ .createTag('wan 2.2')
+
+ expect(firstId).not.toBeNull()
+ expect(duplicateId).toBe(firstId)
+
+ const tags = useWorkflowStore.getState().tags
+
+ expect(tags).toHaveLength(1)
+ expect(tags[0].name).toBe('Wan 2.2')
+ })
+
+ it('blocks an explicitly assigned workflow that does not match the model tags', () => {
+ const wanTag = useWorkflowStore
+ .getState()
+ .createTag('Wan 2.2')!
+
+ const i2vTag = useWorkflowStore
+ .getState()
+ .createTag('I2V')!
+
+ const t2vTag = useWorkflowStore
+ .getState()
+ .createTag('T2V')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-t2v', 'Wan T2V', {
+ mode: 'video',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags(
+ 'wf-t2v',
+ [wanTag, t2vTag],
+ )
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'wan-i2v.gguf',
+ 'video',
+ [wanTag, i2vTag],
+ )
+
+ useWorkflowStore
+ .getState()
+ .assignToModelName(
+ 'wan-i2v.gguf',
+ 'wf-t2v',
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getWorkflowForModel(
+ 'wan-i2v.gguf',
+ 'wan',
+ ),
+ ).toBeNull()
+ })
+
+ it('rejects an empty tag name', () => {
+ const id = useWorkflowStore.getState().createTag(' ')
+
+ expect(id).toBeNull()
+ expect(useWorkflowStore.getState().tags).toEqual([])
+ })
+
+ it('renames a tag', () => {
+ const id = useWorkflowStore
+ .getState()
+ .createTag('Old name')!
+
+ useWorkflowStore
+ .getState()
+ .renameTag(id, 'New name')
+
+ expect(useWorkflowStore.getState().tags[0].name)
+ .toBe('New name')
+ })
+
+ it('removes a deleted tag from workflows and models', () => {
+ const id = useWorkflowStore
+ .getState()
+ .createTag('Wan')!
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-1', [id])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags('wan.gguf', 'video', [id])
+
+ useWorkflowStore
+ .getState()
+ .deleteTag(id)
+
+ const state = useWorkflowStore.getState()
+
+ expect(state.tags).toEqual([])
+ expect(state.workflowTags).toEqual({})
+ expect(state.modelTags).toEqual({})
+ })
+
+ it('filters unknown and duplicate tag IDs from assignments', () => {
+ const id = useWorkflowStore
+ .getState()
+ .createTag('I2V')!
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-1', [
+ id,
+ 'missing-tag',
+ id,
+ ])
+
+ expect(
+ useWorkflowStore.getState().workflowTags['wf-1'],
+ ).toEqual([id])
+ })
+
+ it('matches a workflow when the model has every required tag', () => {
+ const wanTag = useWorkflowStore
+ .getState()
+ .createTag('Wan 2.2')!
+
+ const i2vTag = useWorkflowStore
+ .getState()
+ .createTag('I2V')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-i2v', 'Wan I2V', {
+ mode: 'video',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-i2v', [
+ wanTag,
+ i2vTag,
+ ])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'wan-i2v.gguf',
+ 'video',
+ [wanTag],
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'wan-i2v.gguf',
+ 'video',
+ ),
+ ).toEqual([])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'wan-i2v.gguf',
+ 'video',
+ [wanTag, i2vTag],
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'wan-i2v.gguf',
+ 'video',
+ )
+ .map((workflow) => workflow.id),
+ ).toEqual(['wf-i2v'])
+ })
+
+ it('normalises model casing and Windows path separators', () => {
+ const tagId = useWorkflowStore
+ .getState()
+ .createTag('Wan')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-video', 'Wan Video', {
+ mode: 'video',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-video', [tagId])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'Models\\WAN.GGUF',
+ 'video',
+ [tagId],
+ )
+
+ const matches = useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'models/wan.gguf',
+ 'video',
+ )
+
+ expect(matches.map((workflow) => workflow.id))
+ .toEqual(['wf-video'])
+ })
+
+ it('does not offer an image-only workflow for a video model', () => {
+ const tagId = useWorkflowStore
+ .getState()
+ .createTag('Shared')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-image', 'Image only', {
+ mode: 'image',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-image', [tagId])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'wan.gguf',
+ 'video',
+ [tagId],
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'wan.gguf',
+ 'video',
+ ),
+ ).toEqual([])
+ })
+
+ it('sorts more specific matching workflows first', () => {
+ const wanTag = useWorkflowStore
+ .getState()
+ .createTag('Wan')!
+
+ const i2vTag = useWorkflowStore
+ .getState()
+ .createTag('I2V')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-general', 'Wan general', {
+ mode: 'video',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-specific', 'Wan I2V', {
+ mode: 'video',
+ }),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-general', [
+ wanTag,
+ ])
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-specific', [
+ wanTag,
+ i2vTag,
+ ])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'wan-i2v.gguf',
+ 'video',
+ [wanTag, i2vTag],
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'wan-i2v.gguf',
+ 'video',
+ )
+ .map((workflow) => workflow.id),
+ ).toEqual([
+ 'wf-specific',
+ 'wf-general',
+ ])
+ })
+
+ it('does not activate a tag match automatically', () => {
+ const tagId = useWorkflowStore
+ .getState()
+ .createTag('SDXL')!
+
+ useWorkflowStore
+ .getState()
+ .installWorkflow(
+ makeWorkflow('wf-tagged', 'Tagged SDXL'),
+ )
+
+ useWorkflowStore
+ .getState()
+ .setWorkflowTags('wf-tagged', [tagId])
+
+ useWorkflowStore
+ .getState()
+ .setModelTags(
+ 'model.safetensors',
+ 'image',
+ [tagId],
+ )
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getMatchingWorkflows(
+ 'model.safetensors',
+ 'image',
+ ),
+ ).toHaveLength(1)
+
+ expect(
+ useWorkflowStore
+ .getState()
+ .getWorkflowForModel(
+ 'model.safetensors',
+ 'sdxl',
+ ),
+ ).toBeNull()
+ })
+ })
+
// ── setCivitaiApiKey ───────────────────────────────────────
describe('setCivitaiApiKey', () => {
diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.ts
index 4bdde099..cbe42b04 100644
--- a/src/stores/uiStore.ts
+++ b/src/stores/uiStore.ts
@@ -1,6 +1,6 @@
import { create } from 'zustand'
-export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark'
+export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark' | 'workflows'
/** Which Cloud teaser sheet is open (Local-mode discovery, 2.5.8).
* 'intent' = a locked Create tab (the cloud-only intents incl. the five
diff --git a/src/stores/workflowStore.ts b/src/stores/workflowStore.ts
index 09b1d97c..35faffde 100644
--- a/src/stores/workflowStore.ts
+++ b/src/stores/workflowStore.ts
@@ -1,27 +1,105 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
-import type { ModelType } from '../api/comfyui'
-import type { WorkflowTemplate } from '../types/workflows'
+import { v4 as uuid } from 'uuid'
+import { isVideoModelType, type ModelType, } from '../api/comfyui'
+import type { WorkflowTag, WorkflowTemplate } from '../types/workflows'
+
+export type WorkflowTagMode = 'image' | 'video'
+
+export function workflowModelKey(
+ modelName: string,
+ mode: WorkflowTagMode,
+): string {
+ const normalisedName = modelName
+ .trim()
+ .replace(/\\/g, '/')
+ .toLowerCase()
+
+ return `${mode}:${normalisedName}`
+}
+
+function normaliseTagName(name: string): string {
+ return name.trim().replace(/\s+/g, ' ')
+}
+
+function validTagIds(
+ tags: WorkflowTag[],
+ requestedIds: string[],
+): string[] {
+ const existingIds = new Set(tags.map((tag) => tag.id))
+
+ return [...new Set(requestedIds)]
+ .filter((id) => existingIds.has(id))
+}
+
+function removeTagFromMap(
+ assignments: Record<string, string[]>,
+ tagId: string,
+): Record<string, string[]> {
+ const next: Record<string, string[]> = {}
+
+ for (const [key, ids] of Object.entries(assignments)) {
+ const remaining = ids.filter((id) => id !== tagId)
+
+ if (remaining.length > 0) {
+ next[key] = remaining
+ }
+ }
+
+ return next
+}
interface WorkflowState {
installedWorkflows: WorkflowTemplate[]
- // ModelType -> WorkflowID (e.g., { flux2: 'uuid-123' })
+
+ // Existing explicit workflow selections. These remain the source used when
+ // generating; tag matches only determine which workflows are offered.
modelTypeAssignments: Record<string, string>
- // Specific model filename -> WorkflowID (e.g., { 'flux2-klein.safetensors': 'uuid-789' })
modelNameAssignments: Record<string, string>
- // CivitAI API key for downloads
+
+ // Shared tag library and its workflow/model relationships.
+ tags: WorkflowTag[]
+ workflowTags: Record<string, string[]>
+ modelTags: Record<string, string[]>
+
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
+
assignToModelType: (modelType: string, workflowId: string) => void
assignToModelName: (modelName: string, workflowId: string) => void
unassignModelType: (modelType: string) => void
unassignModelName: (modelName: string) => void
- getWorkflowForModel: (modelName: string, modelType: ModelType) => WorkflowTemplate | null
+
+ createTag: (name: string) => string | null
+ renameTag: (id: string, name: string) => void
+ deleteTag: (id: string) => void
+
+ setWorkflowTags: (workflowId: string, tagIds: string[]) => void
+ setModelTags: (
+ modelName: string,
+ mode: WorkflowTagMode,
+ tagIds: string[],
+ ) => void
+
+ getTagsForWorkflow: (workflowId: string) => WorkflowTag[]
+ getTagsForModel: (
+ modelName: string,
+ mode: WorkflowTagMode,
+ ) => WorkflowTag[]
+
+ getMatchingWorkflows: (
+ modelName: string,
+ mode: WorkflowTagMode,
+ ) => WorkflowTemplate[]
+
+ getWorkflowForModel: (
+ modelName: string,
+ modelType: ModelType,
+ ) => WorkflowTemplate | null
+
setCivitaiApiKey: (key: string) => void
setCivitaiHost: (host: string) => void
}
@@ -32,76 +110,327 @@ export const useWorkflowStore = create<WorkflowState>()(
installedWorkflows: [],
modelTypeAssignments: {},
modelNameAssignments: {},
+
+ tags: [],
+ workflowTags: {},
+ modelTags: {},
+
civitaiApiKey: '',
civitaiHost: 'civitai.com',
- installWorkflow: (wf) => set((s) => ({
- installedWorkflows: [wf, ...s.installedWorkflows.filter(w => w.id !== wf.id)],
+ installWorkflow: (wf) => set((state) => ({
+ installedWorkflows: [
+ wf,
+ ...state.installedWorkflows.filter(
+ (installed) => installed.id !== wf.id,
+ ),
+ ],
})),
- removeWorkflow: (id) => set((s) => {
- // Also clean up any assignments pointing to this workflow
- const typeAssignments = { ...s.modelTypeAssignments }
- const nameAssignments = { ...s.modelNameAssignments }
- for (const [key, val] of Object.entries(typeAssignments)) {
- if (val === id) delete typeAssignments[key]
+ removeWorkflow: (id) => set((state) => {
+ const typeAssignments = { ...state.modelTypeAssignments }
+ const nameAssignments = { ...state.modelNameAssignments }
+ const workflowTags = { ...state.workflowTags }
+
+ for (const [key, value] of Object.entries(typeAssignments)) {
+ if (value === id) {
+ delete typeAssignments[key]
+ }
}
- for (const [key, val] of Object.entries(nameAssignments)) {
- if (val === id) delete nameAssignments[key]
+
+ for (const [key, value] of Object.entries(nameAssignments)) {
+ if (value === id) {
+ delete nameAssignments[key]
+ }
}
+
+ delete workflowTags[id]
+
return {
- installedWorkflows: s.installedWorkflows.filter(w => w.id !== id),
+ installedWorkflows: state.installedWorkflows.filter(
+ (workflow) => workflow.id !== id,
+ ),
modelTypeAssignments: typeAssignments,
modelNameAssignments: nameAssignments,
+ workflowTags,
}
}),
- assignToModelType: (modelType, workflowId) => set((s) => ({
- modelTypeAssignments: { ...s.modelTypeAssignments, [modelType]: workflowId },
+ assignToModelType: (modelType, workflowId) => set((state) => ({
+ modelTypeAssignments: {
+ ...state.modelTypeAssignments,
+ [modelType]: workflowId,
+ },
})),
- assignToModelName: (modelName, workflowId) => set((s) => ({
- modelNameAssignments: { ...s.modelNameAssignments, [modelName]: workflowId },
+ assignToModelName: (modelName, workflowId) => set((state) => ({
+ modelNameAssignments: {
+ ...state.modelNameAssignments,
+ [modelName]: workflowId,
+ },
})),
- unassignModelType: (modelType) => set((s) => {
- const assignments = { ...s.modelTypeAssignments }
+ unassignModelType: (modelType) => set((state) => {
+ const assignments = { ...state.modelTypeAssignments }
delete assignments[modelType]
- return { modelTypeAssignments: assignments }
+
+ return {
+ modelTypeAssignments: assignments,
+ }
}),
- unassignModelName: (modelName) => set((s) => {
- const assignments = { ...s.modelNameAssignments }
+ unassignModelName: (modelName) => set((state) => {
+ const assignments = { ...state.modelNameAssignments }
delete assignments[modelName]
- return { modelNameAssignments: assignments }
+
+ return {
+ modelNameAssignments: assignments,
+ }
+ }),
+
+ createTag: (name) => {
+ const normalisedName = normaliseTagName(name)
+
+ if (!normalisedName) {
+ return null
+ }
+
+ const existing = get().tags.find(
+ (tag) => tag.name.toLowerCase() === normalisedName.toLowerCase(),
+ )
+
+ if (existing) {
+ return existing.id
+ }
+
+ const id = uuid()
+
+ set((state) => ({
+ tags: [
+ ...state.tags,
+ {
+ id,
+ name: normalisedName,
+ createdAt: Date.now(),
+ },
+ ],
+ }))
+
+ return id
+ },
+
+ renameTag: (id, name) => {
+ const normalisedName = normaliseTagName(name)
+
+ if (!normalisedName) {
+ return
+ }
+
+ set((state) => {
+ const duplicate = state.tags.some(
+ (tag) =>
+ tag.id !== id &&
+ tag.name.toLowerCase() === normalisedName.toLowerCase(),
+ )
+
+ if (duplicate) {
+ return state
+ }
+
+ return {
+ tags: state.tags.map((tag) =>
+ tag.id === id
+ ? { ...tag, name: normalisedName }
+ : tag,
+ ),
+ }
+ })
+ },
+
+ deleteTag: (id) => set((state) => ({
+ tags: state.tags.filter((tag) => tag.id !== id),
+ workflowTags: removeTagFromMap(state.workflowTags, id),
+ modelTags: removeTagFromMap(state.modelTags, id),
+ })),
+
+ setWorkflowTags: (workflowId, tagIds) => set((state) => {
+ const next = { ...state.workflowTags }
+ const cleanedIds = validTagIds(state.tags, tagIds)
+
+ if (cleanedIds.length > 0) {
+ next[workflowId] = cleanedIds
+ } else {
+ delete next[workflowId]
+ }
+
+ return {
+ workflowTags: next,
+ }
+ }),
+
+ setModelTags: (modelName, mode, tagIds) => set((state) => {
+ const next = { ...state.modelTags }
+ const key = workflowModelKey(modelName, mode)
+ const cleanedIds = validTagIds(state.tags, tagIds)
+
+ if (cleanedIds.length > 0) {
+ next[key] = cleanedIds
+ } else {
+ delete next[key]
+ }
+
+ return {
+ modelTags: next,
+ }
}),
- setCivitaiApiKey: (key) => set({ civitaiApiKey: key }),
+ getTagsForWorkflow: (workflowId) => {
+ const state = get()
+ const assignedIds = new Set(
+ state.workflowTags[workflowId] ?? [],
+ )
+
+ return state.tags.filter((tag) => assignedIds.has(tag.id))
+ },
+
+ getTagsForModel: (modelName, mode) => {
+ const state = get()
+ const key = workflowModelKey(modelName, mode)
+ const assignedIds = new Set(state.modelTags[key] ?? [])
+
+ return state.tags.filter((tag) => assignedIds.has(tag.id))
+ },
+
+ getMatchingWorkflows: (modelName, mode) => {
+ const state = get()
+ const key = workflowModelKey(modelName, mode)
+ const modelTagIds = new Set(state.modelTags[key] ?? [])
+
+ if (modelTagIds.size === 0) {
+ return []
+ }
+
+ return state.installedWorkflows
+ .filter((workflow) => {
+ if (
+ workflow.mode !== 'both' &&
+ workflow.mode !== mode
+ ) {
+ return false
+ }
+
+ const requiredTags =
+ state.workflowTags[workflow.id] ?? []
+
+ if (requiredTags.length === 0) {
+ return false
+ }
+
+ // Every tag placed on a workflow is a compatibility requirement.
+ // Models may have additional tags without preventing a match.
+ return requiredTags.every((tagId) =>
+ modelTagIds.has(tagId),
+ )
+ })
+ .sort((left, right) => {
+ const leftSpecificity =
+ state.workflowTags[left.id]?.length ?? 0
+ const rightSpecificity =
+ state.workflowTags[right.id]?.length ?? 0
- // 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' }),
+ if (leftSpecificity !== rightSpecificity) {
+ return rightSpecificity - leftSpecificity
+ }
+
+ return right.installedAt - left.installedAt
+ })
+ },
+
+ setCivitaiApiKey: (key) => set({
+ civitaiApiKey: key,
+ }),
+
+ setCivitaiHost: (host) => set({
+ civitaiHost:
+ (host || 'civitai.com')
+ .trim()
+ .replace(/^https?:\/\//i, '')
+ .replace(/\/+$/, '') ||
+ 'civitai.com',
+ }),
- getWorkflowForModel: (modelName, modelType) => {
+ getWorkflowForModel: (modelName, modelType) => {
const state = get()
- // Priority 1: specific model name assignment
- const nameId = state.modelNameAssignments[modelName]
- if (nameId) {
- const wf = state.installedWorkflows.find(w => w.id === nameId)
- if (wf) return wf
+
+ const mode: WorkflowTagMode =
+ isVideoModelType(modelType)
+ ? 'video'
+ : 'image'
+
+ const modelKey = workflowModelKey(
+ modelName,
+ mode,
+ )
+
+ const modelHasTags =
+ (state.modelTags[modelKey]?.length ?? 0) > 0
+
+ // Once a model has tags, only workflows satisfying all of their
+ // compatibility requirements may be used.
+ const compatibleWorkflowIds = modelHasTags
+ ? new Set(
+ state
+ .getMatchingWorkflows(
+ modelName,
+ mode,
+ )
+ .map((workflow) => workflow.id),
+ )
+ : null
+
+ const isAllowed = (workflowId: string) =>
+ compatibleWorkflowIds === null ||
+ compatibleWorkflowIds.has(workflowId)
+
+ // Priority 1: explicit selection for this model.
+ const nameId =
+ state.modelNameAssignments[modelName]
+
+ if (nameId && isAllowed(nameId)) {
+ const workflow =
+ state.installedWorkflows.find(
+ (candidate) =>
+ candidate.id === nameId,
+ )
+
+ if (workflow) {
+ return workflow
+ }
}
- // Priority 2: model type assignment
- const typeId = state.modelTypeAssignments[modelType]
- if (typeId) {
- const wf = state.installedWorkflows.find(w => w.id === typeId)
- if (wf) return wf
+
+ // Priority 2: legacy model-type assignment. This is retained for
+ // existing installations, but it must also pass tag compatibility
+ // after the model receives tags.
+ const typeId =
+ state.modelTypeAssignments[modelType]
+
+ if (typeId && isAllowed(typeId)) {
+ const workflow =
+ state.installedWorkflows.find(
+ (candidate) =>
+ candidate.id === typeId,
+ )
+
+ if (workflow) {
+ return workflow
+ }
}
+
return null
},
}),
{
name: 'workflow-store',
- }
- )
-)
+ },
+ ),
+)
\ No newline at end of file
diff --git a/src/types/workflows.ts b/src/types/workflows.ts
index 7bbf2e42..cfdc9499 100644
--- a/src/types/workflows.ts
+++ b/src/types/workflows.ts
@@ -2,6 +2,12 @@ import type { ModelType } from '../api/comfyui'
export type WorkflowSource = 'civitai' | 'manual'
+export interface WorkflowTag {
+ id: string
+ name: string
+ createdAt: number
+}
+
export interface ParameterMapping {
nodeId: string
inputKey: string