Skip to content

中文版 AI 姿势参考图库 · 1439 组 / 2878 张图片 / 完整汉化 · 零依赖静态画廊

feat(comfyui): 支持本地 ComfyUI 工作流直连生图与 API JSON 导入导出

Alone885d45a2c4447a
diff --git a/src/routes/settings.tsx b/src/routes/settings.tsx
index 9f0ab26..bc23358 100644
--- a/src/routes/settings.tsx
+++ b/src/routes/settings.tsx
@@ -1,5 +1,13 @@
import { createFileRoute, Link } from '@tanstack/react-router'
-import { CheckIcon, ExternalLinkIcon, EyeIcon, EyeOffIcon, RotateCcwIcon, SparklesIcon } from 'lucide-react'
+import {
+ ActivityIcon,
+ CheckIcon,
+ ExternalLinkIcon,
+ EyeIcon,
+ EyeOffIcon,
+ RotateCcwIcon,
+ SparklesIcon,
+} from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { Field, Section } from '@/components/common/FormSection'
@@ -8,7 +16,7 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
-import { PROVIDER_META } from '@/services/aiGenerator'
+import { PROVIDER_META, testComfyConnection } from '@/services/aiGenerator'
import { useStudio } from '@/store/studioStore'
import type { ImagePassMode, ImageProviderId } from '@/types/gallery'
@@ -17,16 +25,29 @@ export const Route = createFileRoute('/settings')({
component: SettingsPage,
})
-const PROVIDER_ORDER: ImageProviderId[] = ['gemini', 'gpt', 'qwen', 'doubao']
+const PROVIDER_ORDER: ImageProviderId[] = ['gemini', 'gpt', 'qwen', 'doubao', 'comfyui']
function SettingsPage() {
const { apiConfig, updateApiConfig, updateProviderConfig } = useStudio()
const [showKey, setShowKey] = useState(false)
+ const [testingComfy, setTestingComfy] = useState(false)
const pid = apiConfig.activeProvider
const meta = PROVIDER_META[pid]
const pCfg = apiConfig.providers[pid]
+ const handleTestComfy = async () => {
+ setTestingComfy(true)
+ try {
+ const info = await testComfyConnection(pCfg.baseUrl, pCfg.apiKey)
+ toast.success(`连接成功:${info}`)
+ } catch {
+ toast.error('连接失败,请确认 ComfyUI 已启动且添加了 --enable-cors-header *')
+ } finally {
+ setTestingComfy(false)
+ }
+ }
+
return (
<>
<PageHeader
@@ -41,12 +62,15 @@ function SettingsPage() {
}
/>
- {/* 四大协议切换标签 */}
- <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
+ {/* 五大协议切换标签 */}
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
{PROVIDER_ORDER.map((id) => {
const itemMeta = PROVIDER_META[id]
const isActive = pid === id
- const hasKey = Boolean(apiConfig.providers[id].apiKey.trim())
+ const hasKey =
+ id === 'comfyui'
+ ? Boolean(apiConfig.providers.comfyui.baseUrl.trim())
+ : Boolean(apiConfig.providers[id].apiKey.trim())
return (
<button
key={id}
@@ -63,7 +87,7 @@ function SettingsPage() {
className={`size-2 shrink-0 rounded-full ${
hasKey ? 'bg-emerald-500' : 'bg-muted-foreground/30'
}`}
- title={hasKey ? '已配置 Key' : '未配置 Key'}
+ title={hasKey ? '已就绪' : '未配置 Key'}
/>
</button>
)
@@ -75,6 +99,12 @@ function SettingsPage() {
title={`${meta.name} 连接配置`}
actions={
<div className="flex items-center gap-1.5">
+ {pid === 'comfyui' && (
+ <Button variant="outline" size="sm" onClick={handleTestComfy} disabled={testingComfy}>
+ <ActivityIcon className="size-3.5" />
+ {testingComfy ? '检测中…' : '测试连接'}
+ </Button>
+ )}
<Button variant="ghost" size="sm" asChild>
<a href={meta.docUrl} target="_blank" rel="noreferrer">
<ExternalLinkIcon className="size-3.5" />
@@ -98,7 +128,14 @@ function SettingsPage() {
</div>
}
>
- <Field label="Base URL">
+ <Field
+ label={pid === 'comfyui' ? 'ComfyUI 地址 (Base URL)' : 'Base URL'}
+ hint={
+ pid === 'comfyui'
+ ? '启动 ComfyUI 需加参数 --enable-cors-header *(秋叶整合包勾选「允许跨域」)'
+ : undefined
+ }
+ >
<Input
type="url"
value={pCfg.baseUrl}
@@ -107,13 +144,17 @@ function SettingsPage() {
/>
</Field>
- <Field label="API Key">
+ <Field label={pid === 'comfyui' ? 'API Key(可选,本地留空)' : 'API Key'}>
<div className="relative">
<Input
type={showKey ? 'text' : 'password'}
value={pCfg.apiKey}
onChange={(e) => updateProviderConfig(pid, { apiKey: e.target.value })}
- placeholder="输入 API Key(仅保存在本地浏览器)"
+ placeholder={
+ pid === 'comfyui'
+ ? '本地 ComfyUI 无需填写,远程鉴权可填 Token'
+ : '输入 API Key(仅保存在本地浏览器)'
+ }
className="pr-10"
/>
<button
diff --git a/src/routes/studio.tsx b/src/routes/studio.tsx
index b4c1d25..e45a60a 100644
--- a/src/routes/studio.tsx
+++ b/src/routes/studio.tsx
@@ -3,9 +3,11 @@ import { createFileRoute, Link } from '@tanstack/react-router'
import {
ChevronDownIcon,
ChevronUpIcon,
+ CodeXmlIcon,
CopyIcon,
DicesIcon,
DownloadIcon,
+ FileUpIcon,
ImagePlusIcon,
KeyRoundIcon,
LayoutGridIcon,
@@ -20,7 +22,7 @@ import {
UserRoundIcon,
XIcon,
} from 'lucide-react'
-import { type ChangeEvent, type DragEvent, useEffect, useRef, useState } from 'react'
+import { type ChangeEvent, type DragEvent, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import { costumesQuery, portraitsQuery, posesQuery } from '@/api/gallery'
import { Field, Section } from '@/components/common/FormSection'
@@ -33,14 +35,18 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import {
+ autoDetectComfyMappings,
buildRecipePrompt,
+ COMFYUI_WORKFLOW_TEMPLATES,
fileToDataUrl,
+ parseComfyWorkflowNodes,
PROVIDER_META,
stitchRecipeCanvas,
STYLE_PRESETS,
} from '@/services/aiGenerator'
import { useStudio } from '@/store/studioStore'
import type {
+ ComfyUiParams,
DoubaoParams,
GeminiParams,
GptParams,
@@ -54,7 +60,7 @@ export const Route = createFileRoute('/studio')({
component: StudioPage,
})
-const PROVIDER_LIST: ImageProviderId[] = ['gemini', 'gpt', 'qwen', 'doubao']
+const PROVIDER_LIST: ImageProviderId[] = ['gemini', 'gpt', 'qwen', 'doubao', 'comfyui']
function StudioPage() {
const {
@@ -80,12 +86,14 @@ function StudioPage() {
updateGeminiParams,
updateQwenParams,
updateDoubaoParams,
+ updateComfyUiParams,
randomizeRecipe,
removeHistoryItem,
clearHistory,
} = useStudio()
const qc = useQueryClient()
const fileInputRef = useRef<HTMLInputElement | null>(null)
+ const comfyFileInputRef = useRef<HTMLInputElement | null>(null)
const activeProvider = apiConfig.activeProvider
const providerMeta = PROVIDER_META[activeProvider]
@@ -98,8 +106,80 @@ function StudioPage() {
const [showUrlInput, setShowUrlInput] = useState(false)
const [stitchModalUrl, setStitchModalUrl] = useState<string | null>(null)
const [zoomImageUrl, setZoomImageUrl] = useState<string | null>(null)
+ const [showComfyJsonModal, setShowComfyJsonModal] = useState(false)
const [isDragging, setIsDragging] = useState(false)
+ const parsedComfyNodes = useMemo(
+ () => parseComfyWorkflowNodes(apiConfig.comfyuiParams.workflowJson),
+ [apiConfig.comfyuiParams.workflowJson]
+ )
+
+ const handleSelectComfyPreset = (preset: ComfyUiParams['workflowPreset']) => {
+ if (preset === 'custom') {
+ updateComfyUiParams({ workflowPreset: 'custom' })
+ return
+ }
+ const tpl = COMFYUI_WORKFLOW_TEMPLATES[preset]
+ updateComfyUiParams({
+ workflowPreset: preset,
+ workflowJson: JSON.stringify(tpl.workflow, null, 2),
+ ...tpl.defaults,
+ })
+ toast.success(`已切换为:${tpl.label}`)
+ }
+
+ const handleComfyFileUpload = async (e: ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0]
+ e.target.value = ''
+ if (!file) return
+ try {
+ const text = await file.text()
+ const info = parseComfyWorkflowNodes(text)
+ if (!info.valid) {
+ toast.error(info.error || '工作流 JSON 无效')
+ return
+ }
+ const detected = autoDetectComfyMappings(text)
+ updateComfyUiParams({
+ workflowPreset: 'custom',
+ workflowJson: text,
+ ...detected,
+ })
+ setShowAdvanced(true)
+ toast.success(
+ `已导入工作流:识别到 ${info.imageNodes.length} 个图片节点、${info.promptNodes.length} 个提示词节点`
+ )
+ } catch {
+ toast.error('读取 JSON 文件失败')
+ }
+ }
+
+ const handleExportComfyJson = () => {
+ try {
+ const wf = JSON.parse(apiConfig.comfyuiParams.workflowJson)
+ const cp = apiConfig.comfyuiParams
+ if (cp.promptNodeId && cp.promptNodeId !== 'none' && wf[cp.promptNodeId]?.inputs) {
+ const inputs = wf[cp.promptNodeId].inputs
+ for (const field of ['prompt', 'text', 'string', 'positive']) {
+ if (typeof inputs[field] === 'string') {
+ inputs[field] = prompt
+ break
+ }
+ }
+ }
+ const blob = new Blob([JSON.stringify(wf, null, 2)], { type: 'application/json' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `comfyui-workflow-${Date.now()}.api.json`
+ a.click()
+ URL.revokeObjectURL(url)
+ toast.success('已导出 ComfyUI API 工作流 JSON')
+ } catch {
+ toast.error('当前工作流 JSON 格式有误,无法导出')
+ }
+ }
+
const extraImages = recipe.extraImages || []
const hasAnyRef = Boolean(
recipe.portrait || recipe.costume || recipe.pose || extraImages.length > 0
@@ -473,35 +553,104 @@ function StudioPage() {
</Select>
</Field>
- <Field label="模型 ID">
- <Select
- value={providerCfg.model}
- onValueChange={(v) => updateProviderConfig(activeProvider, { model: v })}
- >
- <SelectTrigger className="w-full font-mono text-xs">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {providerMeta.models.map((m) => (
- <SelectItem key={m.value} value={m.value} className="font-mono text-xs">
- {m.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
-
- {providerCfg.model === 'custom' && (
- <Field label="自定义模型 ID">
- <Input
- value={providerCfg.customModel}
- onChange={(e) =>
- updateProviderConfig(activeProvider, { customModel: e.target.value })
- }
- placeholder="输入模型 ID"
- className="bg-background font-mono text-xs"
- />
+ {activeProvider === 'comfyui' ? (
+ <Field label="工作流模板 (API 格式)">
+ <div className="space-y-2">
+ <Select
+ value={apiConfig.comfyuiParams.workflowPreset}
+ onValueChange={(v) =>
+ handleSelectComfyPreset(v as ComfyUiParams['workflowPreset'])
+ }
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="qwen21_3img" className="text-xs">
+ {COMFYUI_WORKFLOW_TEMPLATES.qwen21_3img.label}
+ </SelectItem>
+ <SelectItem value="qwen21_2img" className="text-xs">
+ {COMFYUI_WORKFLOW_TEMPLATES.qwen21_2img.label}
+ </SelectItem>
+ <SelectItem value="custom" className="text-xs">
+ 自定义工作流 (已导入 JSON)
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <div className="flex flex-wrap gap-1.5">
+ <input
+ ref={comfyFileInputRef}
+ type="file"
+ accept=".json,application/json"
+ onChange={handleComfyFileUpload}
+ className="hidden"
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => comfyFileInputRef.current?.click()}
+ >
+ <FileUpIcon className="size-3.5" />
+ 导入 .json
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => setShowComfyJsonModal(true)}
+ >
+ <CodeXmlIcon className="size-3.5" />
+ 编辑 JSON
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={handleExportComfyJson}
+ >
+ <DownloadIcon className="size-3.5" />
+ 导出 .json
+ </Button>
+ </div>
+ </div>
</Field>
+ ) : (
+ <>
+ <Field label="模型 ID">
+ <Select
+ value={providerCfg.model}
+ onValueChange={(v) => updateProviderConfig(activeProvider, { model: v })}
+ >
+ <SelectTrigger className="w-full font-mono text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {providerMeta.models.map((m) => (
+ <SelectItem key={m.value} value={m.value} className="font-mono text-xs">
+ {m.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ {providerCfg.model === 'custom' && (
+ <Field label="自定义模型 ID">
+ <Input
+ value={providerCfg.customModel}
+ onChange={(e) =>
+ updateProviderConfig(activeProvider, { customModel: e.target.value })
+ }
+ placeholder="输入模型 ID"
+ className="bg-background font-mono text-xs"
+ />
+ </Field>
+ )}
+ </>
)}
<Field label="画风预设">
@@ -522,6 +671,92 @@ function StudioPage() {
</Select>
</Field>
+ {activeProvider === 'comfyui' && (
+ <>
+ {!parsedComfyNodes.valid && (
+ <div className="col-span-full rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
+ {parsedComfyNodes.error}
+ </div>
+ )}
+
+ <Field label="人像图节点 (LoadImage)">
+ <Select
+ value={apiConfig.comfyuiParams.portraitNodeId}
+ onValueChange={(v) => updateComfyUiParams({ portraitNodeId: v })}
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">不绑定</SelectItem>
+ {parsedComfyNodes.imageNodes.map((n) => (
+ <SelectItem key={n.id} value={n.id} className="text-xs">
+ #{n.id} {n.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field label="服装图节点 (LoadImage)">
+ <Select
+ value={apiConfig.comfyuiParams.costumeNodeId}
+ onValueChange={(v) => updateComfyUiParams({ costumeNodeId: v })}
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">不绑定</SelectItem>
+ {parsedComfyNodes.imageNodes.map((n) => (
+ <SelectItem key={n.id} value={n.id} className="text-xs">
+ #{n.id} {n.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field label="姿势图节点 (LoadImage)">
+ <Select
+ value={apiConfig.comfyuiParams.poseNodeId}
+ onValueChange={(v) => updateComfyUiParams({ poseNodeId: v })}
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">不绑定</SelectItem>
+ {parsedComfyNodes.imageNodes.map((n) => (
+ <SelectItem key={n.id} value={n.id} className="text-xs">
+ #{n.id} {n.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field label="正向提示词节点 (Prompt)">
+ <Select
+ value={apiConfig.comfyuiParams.promptNodeId}
+ onValueChange={(v) => updateComfyUiParams({ promptNodeId: v })}
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">保留工作流原提示词</SelectItem>
+ {parsedComfyNodes.promptNodes.map((n) => (
+ <SelectItem key={n.id} value={n.id} className="text-xs">
+ #{n.id} {n.title} ({n.field})
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </>
+ )}
+
{/* 展开的高级协议专属参数 */}
{showAdvanced && (
<>
@@ -791,32 +1026,70 @@ function StudioPage() {
</>
)}
- <Field label="图片传参方式">
- <Select
- value={apiConfig.imagePassMode}
- onValueChange={(v) => updateApiConfig({ imagePassMode: v as ImagePassMode })}
- >
- <SelectTrigger className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="url">URL</SelectItem>
- <SelectItem value="base64">Base64</SelectItem>
- </SelectContent>
- </Select>
- </Field>
+ {activeProvider === 'comfyui' && (
+ <>
+ <Field label="三合一拼图节点 (可选)">
+ <Select
+ value={apiConfig.comfyuiParams.stitchedNodeId}
+ onValueChange={(v) => updateComfyUiParams({ stitchedNodeId: v })}
+ >
+ <SelectTrigger className="w-full text-xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="none">不绑定</SelectItem>
+ {parsedComfyNodes.imageNodes.map((n) => (
+ <SelectItem key={n.id} value={n.id} className="text-xs">
+ #{n.id} {n.title}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ <Field label="随机种子 (seed)">
+ <div className="flex h-9 items-center justify-between rounded-xl border bg-background px-3">
+ <span className="text-xs text-muted-foreground">
+ {apiConfig.comfyuiParams.randomizeSeed ? '每次随机种子' : '固定工作流种子'}
+ </span>
+ <Switch
+ checked={apiConfig.comfyuiParams.randomizeSeed}
+ onCheckedChange={(v) => updateComfyUiParams({ randomizeSeed: v })}
+ />
+ </div>
+ </Field>
+ </>
+ )}
- <Field label="附带合成拼图">
- <div className="flex h-9 items-center justify-between rounded-xl border bg-background px-3">
- <span className="text-xs text-muted-foreground">
- {apiConfig.sendStitchedSheet ? '同时发送拼图' : '仅发单图序列'}
- </span>
- <Switch
- checked={apiConfig.sendStitchedSheet}
- onCheckedChange={(v) => updateApiConfig({ sendStitchedSheet: v })}
- />
- </div>
- </Field>
+ {activeProvider !== 'comfyui' && (
+ <>
+ <Field label="图片传参方式">
+ <Select
+ value={apiConfig.imagePassMode}
+ onValueChange={(v) => updateApiConfig({ imagePassMode: v as ImagePassMode })}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="url">URL</SelectItem>
+ <SelectItem value="base64">Base64</SelectItem>
+ </SelectContent>
+ </Select>
+ </Field>
+
+ <Field label="附带合成拼图">
+ <div className="flex h-9 items-center justify-between rounded-xl border bg-background px-3">
+ <span className="text-xs text-muted-foreground">
+ {apiConfig.sendStitchedSheet ? '同时发送拼图' : '仅发单图序列'}
+ </span>
+ <Switch
+ checked={apiConfig.sendStitchedSheet}
+ onCheckedChange={(v) => updateApiConfig({ sendStitchedSheet: v })}
+ />
+ </div>
+ </Field>
+ </>
+ )}
</>
)}
</Section>
@@ -1048,6 +1321,47 @@ function StudioPage() {
)}
</DialogContent>
</Dialog>
+
+ {/* ComfyUI API 工作流 JSON 编辑器弹窗 */}
+ <Dialog open={showComfyJsonModal} onOpenChange={setShowComfyJsonModal}>
+ <DialogContent className="max-h-[90vh] w-[95vw] max-w-3xl overflow-y-auto p-4 sm:max-w-3xl">
+ <DialogHeader className="flex flex-row items-center justify-between pr-6">
+ <DialogTitle className="text-base">ComfyUI API 工作流 JSON</DialogTitle>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ const info = parseComfyWorkflowNodes(apiConfig.comfyuiParams.workflowJson)
+ if (!info.valid) {
+ toast.error(info.error || '工作流 JSON 无效')
+ return
+ }
+ const detected = autoDetectComfyMappings(apiConfig.comfyuiParams.workflowJson)
+ updateComfyUiParams(detected)
+ toast.success(
+ `已自动重新识别节点:${info.imageNodes.length} 个图片节点、${info.promptNodes.length} 个提示词节点`
+ )
+ }}
+ >
+ 自动识别节点
+ </Button>
+ </DialogHeader>
+ <p className="text-xs text-muted-foreground">
+ 请在 ComfyUI 设置中开启「启用开发模式选项」,点击菜单中的「导出 (API)」获取 JSON 并粘贴于下方。
+ </p>
+ <Textarea
+ value={apiConfig.comfyuiParams.workflowJson}
+ onChange={(e) =>
+ updateComfyUiParams({
+ workflowPreset: 'custom',
+ workflowJson: e.target.value,
+ })
+ }
+ rows={18}
+ className="font-mono text-xs leading-relaxed"
+ />
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/src/services/aiGenerator.ts b/src/services/aiGenerator.ts
index 9f5ae09..cb8e6b6 100644
--- a/src/services/aiGenerator.ts
+++ b/src/services/aiGenerator.ts
@@ -76,6 +76,19 @@ export const PROVIDER_META: Record<
{ value: 'custom', label: '自定义模型 ID / Endpoint' },
],
},
+ comfyui: {
+ id: 'comfyui',
+ name: '本地 ComfyUI',
+ shortName: 'ComfyUI',
+ defaultBaseUrl: 'http://127.0.0.1:8188',
+ docUrl: 'https://docs.comfy.org/essentials/comfyui_server',
+ models: [
+ { value: 'qwen_image_2.1', label: 'qwen_image_2.1' },
+ { value: 'flux_redux_controlnet', label: 'flux_redux_controlnet' },
+ { value: 'sdxl_ipadapter_openpose', label: 'sdxl_ipadapter_openpose' },
+ { value: 'custom', label: '自定义工作流' },
+ ],
+ },
}
export const STYLE_PRESETS: Record<string, { label: string; prompt: string }> = {
@@ -404,6 +417,529 @@ function extractUniversalImage(json: any): string | null {
return null
}
+// ============================================================================
+// 本地 ComfyUI API 工作流模板与节点解析工具
+// ============================================================================
+
+export const COMFYUI_WORKFLOW_TEMPLATES: Record<
+ 'qwen21_3img' | 'qwen21_2img',
+ {
+ label: string
+ workflow: Record<string, any>
+ defaults: {
+ promptNodeId: string
+ portraitNodeId: string
+ costumeNodeId: string
+ poseNodeId: string
+ stitchedNodeId: string
+ }
+ }
+> = {
+ qwen21_3img: {
+ label: 'Qwen-Image 2.1 三图合成(人像+服装+姿势)',
+ defaults: {
+ promptNodeId: '9',
+ portraitNodeId: '1',
+ costumeNodeId: '2',
+ poseNodeId: '3',
+ stitchedNodeId: 'none',
+ },
+ workflow: {
+ '1': {
+ inputs: { image: 'portrait_ref.png' },
+ class_type: 'LoadImage',
+ _meta: { title: '图1:人像参考 (Portrait)' },
+ },
+ '2': {
+ inputs: { image: 'costume_ref.png' },
+ class_type: 'LoadImage',
+ _meta: { title: '图2:服装参考 (Costume)' },
+ },
+ '3': {
+ inputs: { image: 'pose_ref.png' },
+ class_type: 'LoadImage',
+ _meta: { title: '图3:姿势参考 (Pose)' },
+ },
+ '4': {
+ inputs: {
+ unet_name: 'image2image/qwen_image_2.1_bf16.safetensors',
+ weight_dtype: 'default',
+ },
+ class_type: 'UNETLoader',
+ _meta: { title: '加载 Qwen Image 2.1 基础模型' },
+ },
+ '5': {
+ inputs: {
+ model: ['4', 0],
+ lora_name: 'qwen2.1/动作编辑VNCCS_QI2_PoseStudioV2_3294845.safetensors',
+ strength_model: 1.0,
+ },
+ class_type: 'LoraLoaderModelOnly',
+ _meta: { title: '加载姿态编辑 LoRA 适配器' },
+ },
+ '6': {
+ inputs: { device: 'auto', dtype: 'default', model: ['5', 0] },
+ class_type: 'QwenImage21Cache',
+ _meta: { title: 'Qwen Image 2.1 条件缓存' },
+ },
+ '7': {
+ inputs: {
+ clip_name: 'text_encoders/qwen3vl_8b_bf16.safetensors',
+ type: 'qwen_image',
+ device: 'default',
+ },
+ class_type: 'CLIPLoader',
+ _meta: { title: '加载 Qwen3-VL 8B 编码器' },
+ },
+ '8': {
+ inputs: { vae_name: 'vae/qwen_image_2.1_vae_bf16.safetensors' },
+ class_type: 'VAELoader',
+ _meta: { title: '加载 Qwen Image 2.1 VAE' },
+ },
+ '9': {
+ inputs: {
+ prompt: '',
+ negative_prompt: '',
+ resolution: 1024,
+ clip: ['7', 0],
+ 'images.image_1': ['1', 0],
+ 'images.image_2': ['2', 0],
+ 'images.image_3': ['3', 0],
+ vae: ['8', 0],
+ },
+ class_type: 'TextEncodeQwenImage21',
+ _meta: { title: '正向提示词与多图编码 (Qwen 2.1)' },
+ },
+ '10': {
+ inputs: {
+ seed: 20261031,
+ steps: 25,
+ cfg: 1.0,
+ sampler_name: 'euler',
+ scheduler: 'simple',
+ denoise: 1.0,
+ model: ['6', 0],
+ positive: ['9', 0],
+ negative: ['9', 1],
+ latent_image: ['9', 2],
+ },
+ class_type: 'KSampler',
+ _meta: { title: 'KSampler 采样器' },
+ },
+ '11': {
+ inputs: { samples: ['10', 0], vae: ['8', 0] },
+ class_type: 'VAEDecode',
+ _meta: { title: 'VAE 解码' },
+ },
+ '12': {
+ inputs: { filename_prefix: 'pose_studio/result', images: ['11', 0] },
+ class_type: 'SaveImage',
+ _meta: { title: '保存生成结果' },
+ },
+ },
+ },
+ qwen21_2img: {
+ label: 'Qwen-Image 2.1 双图姿态迁移(姿势+人物/拼图)',
+ defaults: {
+ promptNodeId: '9',
+ portraitNodeId: '1',
+ costumeNodeId: 'none',
+ poseNodeId: '2',
+ stitchedNodeId: 'none',
+ },
+ workflow: {
+ '1': {
+ inputs: { image: 'person_reference.png' },
+ class_type: 'LoadImage',
+ _meta: { title: '图2:人物/服装参考图 (LoadImage)' },
+ },
+ '2': {
+ inputs: { image: 'pose_reference.png' },
+ class_type: 'LoadImage',
+ _meta: { title: '图1:姿势参考图 (LoadImage)' },
+ },
+ '4': {
+ inputs: {
+ unet_name: 'image2image/qwen_image_2.1_bf16.safetensors',
+ weight_dtype: 'default',
+ },
+ class_type: 'UNETLoader',
+ _meta: { title: '加载 Qwen Image 2.1 基础模型' },
+ },
+ '5': {
+ inputs: {
+ model: ['4', 0],
+ lora_name: 'qwen2.1/动作编辑VNCCS_QI2_PoseStudioV2_3294845.safetensors',
+ strength_model: 1.0,
+ },
+ class_type: 'LoraLoaderModelOnly',
+ _meta: { title: '加载姿态编辑 LoRA 适配器' },
+ },
+ '6': {
+ inputs: { device: 'auto', dtype: 'default', model: ['5', 0] },
+ class_type: 'QwenImage21Cache',
+ _meta: { title: 'Qwen Image 2.1 条件缓存' },
+ },
+ '7': {
+ inputs: {
+ clip_name: 'text_encoders/qwen3vl_8b_bf16.safetensors',
+ type: 'qwen_image',
+ device: 'default',
+ },
+ class_type: 'CLIPLoader',
+ _meta: { title: '加载 Qwen3-VL 8B 编码器' },
+ },
+ '8': {
+ inputs: { vae_name: 'vae/qwen_image_2.1_vae_bf16.safetensors' },
+ class_type: 'VAELoader',
+ _meta: { title: '加载 Qwen Image 2.1 VAE' },
+ },
+ '9': {
+ inputs: {
+ prompt: '',
+ negative_prompt: '',
+ resolution: 1024,
+ clip: ['7', 0],
+ 'images.image_1': ['2', 0],
+ 'images.image_2': ['1', 0],
+ vae: ['8', 0],
+ },
+ class_type: 'TextEncodeQwenImage21',
+ _meta: { title: '正向提示词与双图编码 (Qwen 2.1)' },
+ },
+ '10': {
+ inputs: {
+ seed: 20261031,
+ steps: 25,
+ cfg: 1.0,
+ sampler_name: 'euler',
+ scheduler: 'simple',
+ denoise: 1.0,
+ model: ['6', 0],
+ positive: ['9', 0],
+ negative: ['9', 1],
+ latent_image: ['9', 2],
+ },
+ class_type: 'KSampler',
+ _meta: { title: 'KSampler 采样器' },
+ },
+ '11': {
+ inputs: { samples: ['10', 0], vae: ['8', 0] },
+ class_type: 'VAEDecode',
+ _meta: { title: 'VAE 解码' },
+ },
+ '12': {
+ inputs: { filename_prefix: 'pose_studio/result', images: ['11', 0] },
+ class_type: 'SaveImage',
+ _meta: { title: '保存生成结果' },
+ },
+ },
+ },
+}
+
+export interface ComfyParsedNodes {
+ valid: boolean
+ isUiFormat: boolean
+ error?: string
+ imageNodes: Array<{ id: string; title: string; classType: string; currentImage: string }>
+ promptNodes: Array<{ id: string; title: string; classType: string; field: string }>
+}
+
+export function parseComfyWorkflowNodes(workflowJson: string): ComfyParsedNodes {
+ if (!workflowJson.trim()) {
+ return { valid: false, isUiFormat: false, error: '工作流 JSON 为空', imageNodes: [], promptNodes: [] }
+ }
+ try {
+ const parsed = JSON.parse(workflowJson)
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ return { valid: false, isUiFormat: false, error: '无效的 JSON 对象', imageNodes: [], promptNodes: [] }
+ }
+ if (Array.isArray(parsed.nodes) && Array.isArray(parsed.links)) {
+ return {
+ valid: false,
+ isUiFormat: true,
+ error: '检测到普通画布格式 JSON,请在 ComfyUI 设置中开启「开发者模式」并使用「导出 (API)」',
+ imageNodes: [],
+ promptNodes: [],
+ }
+ }
+
+ const imageNodes: ComfyParsedNodes['imageNodes'] = []
+ const promptNodes: ComfyParsedNodes['promptNodes'] = []
+
+ for (const [id, node] of Object.entries<any>(parsed)) {
+ if (!node || typeof node !== 'object' || !node.class_type) continue
+ const classType = String(node.class_type)
+ const title = String(node._meta?.title || classType)
+ const inputs = node.inputs || {}
+
+ if (classType === 'LoadImage' || typeof inputs.image === 'string') {
+ imageNodes.push({
+ id,
+ title,
+ classType,
+ currentImage: String(inputs.image || ''),
+ })
+ }
+
+ for (const field of ['prompt', 'text', 'string', 'positive']) {
+ if (typeof inputs[field] === 'string') {
+ promptNodes.push({
+ id,
+ title,
+ classType,
+ field,
+ })
+ break
+ }
+ }
+ }
+
+ return { valid: true, isUiFormat: false, imageNodes, promptNodes }
+ } catch (err: any) {
+ return {
+ valid: false,
+ isUiFormat: false,
+ error: `JSON 解析失败: ${err?.message || '语法错误'}`,
+ imageNodes: [],
+ promptNodes: [],
+ }
+ }
+}
+
+export function autoDetectComfyMappings(workflowJson: string): {
+ promptNodeId: string
+ portraitNodeId: string
+ costumeNodeId: string
+ poseNodeId: string
+ stitchedNodeId: string
+} {
+ const parsed = parseComfyWorkflowNodes(workflowJson)
+ let promptNodeId = 'none'
+ let portraitNodeId = 'none'
+ let costumeNodeId = 'none'
+ let poseNodeId = 'none'
+ let stitchedNodeId = 'none'
+
+ const posPrompt =
+ parsed.promptNodes.find((n) => !/negative|反向|负面/i.test(n.title)) || parsed.promptNodes[0]
+ if (posPrompt) promptNodeId = posPrompt.id
+
+ const usedIds = new Set<string>()
+ for (const n of parsed.imageNodes) {
+ if (/人像|脸|人物|portrait|face|person/i.test(n.title) && portraitNodeId === 'none') {
+ portraitNodeId = n.id
+ usedIds.add(n.id)
+ } else if (/服装|衣|穿搭|costume|cloth|outfit/i.test(n.title) && costumeNodeId === 'none') {
+ costumeNodeId = n.id
+ usedIds.add(n.id)
+ } else if (/姿势|动作|骨架|pose/i.test(n.title) && poseNodeId === 'none') {
+ poseNodeId = n.id
+ usedIds.add(n.id)
+ } else if (/拼图|合成|stitch/i.test(n.title) && stitchedNodeId === 'none') {
+ stitchedNodeId = n.id
+ usedIds.add(n.id)
+ }
+ }
+
+ const remaining = parsed.imageNodes.filter((n) => !usedIds.has(n.id))
+ if (portraitNodeId === 'none' && remaining[0]) {
+ portraitNodeId = remaining.shift()!.id
+ }
+ if (costumeNodeId === 'none' && remaining[0]) {
+ costumeNodeId = remaining.shift()!.id
+ }
+ if (poseNodeId === 'none' && remaining[0]) {
+ poseNodeId = remaining.shift()!.id
+ }
+
+ return { promptNodeId, portraitNodeId, costumeNodeId, poseNodeId, stitchedNodeId }
+}
+
+export async function testComfyConnection(baseUrl: string, apiKey = ''): Promise<string> {
+ const cleanUrl = (baseUrl.trim() || PROVIDER_META.comfyui.defaultBaseUrl).replace(/\/+$/, '')
+ const headers: Record<string, string> = {}
+ if (apiKey.trim()) headers.Authorization = `Bearer ${apiKey.trim()}`
+ const res = await fetch(`${cleanUrl}/system_stats`, { headers })
+ if (!res.ok) {
+ throw new Error(`HTTP ${res.status}`)
+ }
+ const data = await res.json()
+ const ver = data?.system?.comfyui_version || '未知版本'
+ const gpu = data?.devices?.[0]?.name || '本地设备'
+ return `ComfyUI ${ver} · ${gpu}`
+}
+
+async function uploadImageToComfy(
+ baseUrl: string,
+ src: string,
+ filenamePrefix: string,
+ apiKey: string
+): Promise<string> {
+ const dataUrl = await srcToPngDataUrl(src)
+ const blob = dataUrlToBlob(dataUrl)
+ const form = new FormData()
+ form.append('image', blob, `${filenamePrefix}_${Date.now()}.png`)
+ form.append('overwrite', 'true')
+
+ const headers: Record<string, string> = {}
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`
+
+ const res = await fetch(`${baseUrl}/upload/image`, {
+ method: 'POST',
+ headers,
+ body: form,
+ })
+ if (!res.ok) {
+ throw new Error(`上传参考图到 ComfyUI 失败 (HTTP ${res.status}),请确认已开启 --enable-cors-header *`)
+ }
+ const json = await res.json()
+ return json.subfolder ? `${json.subfolder}/${json.name}` : json.name
+}
+
+async function generateWithComfyUi(params: {
+ recipe: RecipeState
+ prompt: string
+ config: ApiConfig
+ baseUrl: string
+ apiKey: string
+ model: string
+}): Promise<{ imageUrl: string; modelUsed: string; providerUsed: ImageProviderId }> {
+ const { recipe, prompt, config, baseUrl, apiKey, model } = params
+ const cp = config.comfyuiParams
+ const parsedInfo = parseComfyWorkflowNodes(cp.workflowJson)
+ if (!parsedInfo.valid) {
+ throw new Error(`[ComfyUI] ${parsedInfo.error || '工作流 JSON 无效'}`)
+ }
+
+ const workflow = JSON.parse(cp.workflowJson)
+
+ // 1. 按映射槽位上传参考图并注入节点
+ const slotUploads: Array<{ nodeId: string; src: string | null; prefix: string }> = [
+ {
+ nodeId: cp.portraitNodeId,
+ src: recipe.portrait ? recipe.portrait.原图 || recipe.portrait.缩略图 : null,
+ prefix: 'studio_portrait',
+ },
+ {
+ nodeId: cp.costumeNodeId,
+ src: recipe.costume ? recipe.costume.预览图 || recipe.costume.原图 || recipe.costume.缩略图 : null,
+ prefix: 'studio_costume',
+ },
+ {
+ nodeId: cp.poseNodeId,
+ src: recipe.pose ? recipe.pose.原图 || recipe.pose.缩略图 : null,
+ prefix: 'studio_pose',
+ },
+ ]
+
+ for (const slot of slotUploads) {
+ if (slot.nodeId && slot.nodeId !== 'none' && slot.src && workflow[slot.nodeId]?.inputs) {
+ const uploadedName = await uploadImageToComfy(baseUrl, slot.src, slot.prefix, apiKey)
+ workflow[slot.nodeId].inputs.image = uploadedName
+ }
+ }
+
+ if (cp.stitchedNodeId && cp.stitchedNodeId !== 'none' && workflow[cp.stitchedNodeId]?.inputs) {
+ const stitchedDataUrl = await stitchRecipeCanvas(recipe)
+ const uploadedName = await uploadImageToComfy(baseUrl, stitchedDataUrl, 'studio_stitched', apiKey)
+ workflow[cp.stitchedNodeId].inputs.image = uploadedName
+ }
+
+ // 2. 注入提示词节点
+ if (cp.promptNodeId && cp.promptNodeId !== 'none' && workflow[cp.promptNodeId]?.inputs) {
+ const inputs = workflow[cp.promptNodeId].inputs
+ for (const field of ['prompt', 'text', 'string', 'positive']) {
+ if (typeof inputs[field] === 'string') {
+ inputs[field] = prompt
+ break
+ }
+ }
+ }
+
+ // 3. 随机化种子
+ if (cp.randomizeSeed) {
+ const nextSeed = Math.floor(Math.random() * 90000000000000) + 1000000
+ for (const node of Object.values<any>(workflow)) {
+ if (!node?.inputs) continue
+ if (typeof node.inputs.seed === 'number') node.inputs.seed = nextSeed
+ if (typeof node.inputs.noise_seed === 'number') node.inputs.noise_seed = nextSeed
+ }
+ }
+
+ // 4. 提交任务到 ComfyUI /prompt
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`
+
+ const clientId = `pose_studio_${Math.random().toString(36).slice(2, 10)}`
+ let promptRes: Response
+ try {
+ promptRes = await fetch(`${baseUrl}/prompt`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ prompt: workflow, client_id: clientId }),
+ })
+ } catch {
+ throw new Error(
+ `无法连接本地 ComfyUI (${baseUrl})。请确认 ComfyUI 已启动,且启动参数包含 --enable-cors-header *`
+ )
+ }
+
+ const promptJson = await promptRes.json()
+ if (!promptRes.ok || !promptJson?.prompt_id) {
+ const nodeErr = promptJson?.node_errors
+ ? JSON.stringify(promptJson.node_errors).slice(0, 220)
+ : promptJson?.error?.message || `HTTP ${promptRes.status}`
+ throw new Error(`[ComfyUI] 提交工作流失败:${nodeErr}`)
+ }
+
+ const promptId: string = promptJson.prompt_id
+
+ // 5. 轮询 /history/{prompt_id} 获取生成结果图片
+ const authHeaders: Record<string, string> = {}
+ if (apiKey) authHeaders.Authorization = `Bearer ${apiKey}`
+
+ for (let attempt = 0; attempt < 250; attempt++) {
+ await new Promise((r) => setTimeout(r, 1200))
+ const histRes = await fetch(`${baseUrl}/history/${promptId}`, { headers: authHeaders })
+ if (!histRes.ok) continue
+ const histJson = await histRes.json()
+ const item = histJson?.[promptId]
+ if (!item) continue
+
+ if (item.status?.status_str === 'error') {
+ const errDetail = JSON.stringify(item.status?.messages || '执行出错').slice(0, 220)
+ throw new Error(`[ComfyUI] 工作流执行出错:${errDetail}`)
+ }
+
+ const outputs = item.outputs || {}
+ let outImg: { filename: string; subfolder?: string; type?: string } | null = null
+ for (const nodeOut of Object.values<any>(outputs)) {
+ if (Array.isArray(nodeOut?.images) && nodeOut.images.length > 0) {
+ outImg = nodeOut.images[0]
+ if (outImg?.type === 'output') break
+ }
+ }
+
+ if (outImg) {
+ const qs = new URLSearchParams({
+ filename: outImg.filename,
+ subfolder: outImg.subfolder || '',
+ type: outImg.type || 'output',
+ })
+ const viewUrl = `${baseUrl}/view?${qs.toString()}`
+ try {
+ const imgDataUrl = await srcToPngDataUrl(viewUrl)
+ return { imageUrl: imgDataUrl, modelUsed: model || 'comfyui', providerUsed: 'comfyui' }
+ } catch {
+ return { imageUrl: viewUrl, modelUsed: model || 'comfyui', providerUsed: 'comfyui' }
+ }
+ }
+ }
+
+ throw new Error('[ComfyUI] 等待生图结果超时(超过 5 分钟),请在 ComfyUI 终端查看进度')
+}
+
export async function generateCharacterImage(params: {
recipe: RecipeState
prompt: string
@@ -414,7 +950,7 @@ export async function generateCharacterImage(params: {
const pCfg = config.providers[provider]
const apiKey = pCfg.apiKey.trim()
- if (!apiKey) {
+ if (provider !== 'comfyui' && !apiKey) {
throw new Error(`请先配置 ${PROVIDER_META[provider].name} 的 API Key`)
}
@@ -436,6 +972,10 @@ export async function generateCharacterImage(params: {
const baseUrl = (pCfg.baseUrl.trim() || PROVIDER_META[provider].defaultBaseUrl).replace(/\/+$/, '')
+ if (provider === 'comfyui') {
+ return generateWithComfyUi({ recipe, prompt, config, baseUrl, apiKey, model })
+ }
+
// 判断当前请求是否需要转换为本地 Base64:
// 1) 用户显式选择了 base64 模式
// 2) 或者勾选了「附带三合一 Canvas 合成图」(本地动态绘制无公网 URL)
diff --git a/src/store/studioStore.tsx b/src/store/studioStore.tsx
index e7224a6..a01ec7b 100644
--- a/src/store/studioStore.tsx
+++ b/src/store/studioStore.tsx
@@ -3,12 +3,14 @@ import { toast } from 'sonner'
import { idbGet, idbSet } from '@/lib/idbStorage'
import {
buildRecipePrompt,
+ COMFYUI_WORKFLOW_TEMPLATES,
generateCharacterImage,
PROVIDER_META,
stitchRecipeCanvas,
} from '@/services/aiGenerator'
import type {
ApiConfig,
+ ComfyUiParams,
CostumeItem,
DoubaoParams,
ExtraReferenceImage,
@@ -58,6 +60,12 @@ const DEFAULT_API_CONFIG: ApiConfig = {
model: PROVIDER_META.doubao.models[0].value,
customModel: '',
},
+ comfyui: {
+ baseUrl: PROVIDER_META.comfyui.defaultBaseUrl,
+ apiKey: '',
+ model: PROVIDER_META.comfyui.models[0].value,
+ customModel: '',
+ },
},
gptParams: {
endpointMode: 'images_edits_json',
@@ -86,6 +94,12 @@ const DEFAULT_API_CONFIG: ApiConfig = {
watermark: false,
responseFormat: 'b64_json',
},
+ comfyuiParams: {
+ workflowPreset: 'qwen21_3img',
+ workflowJson: JSON.stringify(COMFYUI_WORKFLOW_TEMPLATES.qwen21_3img.workflow, null, 2),
+ ...COMFYUI_WORKFLOW_TEMPLATES.qwen21_3img.defaults,
+ randomizeSeed: true,
+ },
}
function mergeStoredConfig(raw: unknown): ApiConfig {
@@ -99,11 +113,13 @@ function mergeStoredConfig(raw: unknown): ApiConfig {
gpt: { ...DEFAULT_API_CONFIG.providers.gpt, ...obj.providers?.gpt },
qwen: { ...DEFAULT_API_CONFIG.providers.qwen, ...obj.providers?.qwen },
doubao: { ...DEFAULT_API_CONFIG.providers.doubao, ...obj.providers?.doubao },
+ comfyui: { ...DEFAULT_API_CONFIG.providers.comfyui, ...obj.providers?.comfyui },
},
gptParams: { ...DEFAULT_API_CONFIG.gptParams, ...obj.gptParams },
geminiParams: { ...DEFAULT_API_CONFIG.geminiParams, ...obj.geminiParams },
qwenParams: { ...DEFAULT_API_CONFIG.qwenParams, ...obj.qwenParams },
doubaoParams: { ...DEFAULT_API_CONFIG.doubaoParams, ...obj.doubaoParams },
+ comfyuiParams: { ...DEFAULT_API_CONFIG.comfyuiParams, ...obj.comfyuiParams },
}
}
@@ -137,6 +153,7 @@ interface StudioContextValue {
updateGeminiParams: (patch: Partial<GeminiParams>) => void
updateQwenParams: (patch: Partial<QwenParams>) => void
updateDoubaoParams: (patch: Partial<DoubaoParams>) => void
+ updateComfyUiParams: (patch: Partial<ComfyUiParams>) => void
addHistory: (item: Omit<GenerationHistoryItem, 'id' | 'createdAt'>) => void
removeHistoryItem: (id: string) => void
clearHistory: () => void
@@ -351,6 +368,10 @@ export function StudioProvider({ children }: { children: ReactNode }) {
setApiConfig((prev) => ({ ...prev, doubaoParams: { ...prev.doubaoParams, ...patch } }))
}
+ const updateComfyUiParams = (patch: Partial<ComfyUiParams>) => {
+ setApiConfig((prev) => ({ ...prev, comfyuiParams: { ...prev.comfyuiParams, ...patch } }))
+ }
+
const addHistory = (item: Omit<GenerationHistoryItem, 'id' | 'createdAt'>) => {
setHistory((prev) => [
{ ...item, id: `${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, createdAt: Date.now() },
@@ -458,6 +479,7 @@ export function StudioProvider({ children }: { children: ReactNode }) {
updateGeminiParams,
updateQwenParams,
updateDoubaoParams,
+ updateComfyUiParams,
addHistory,
removeHistoryItem,
clearHistory,
diff --git a/src/types/gallery.ts b/src/types/gallery.ts
index 3ee671d..5088efa 100644
--- a/src/types/gallery.ts
+++ b/src/types/gallery.ts
@@ -62,7 +62,7 @@ export interface RecipeState {
extraImages?: ExtraReferenceImage[]
}
-export type ImageProviderId = 'gemini' | 'gpt' | 'qwen' | 'doubao'
+export type ImageProviderId = 'gemini' | 'gpt' | 'qwen' | 'doubao' | 'comfyui'
export interface ProviderEndpointConfig {
baseUrl: string
@@ -73,6 +73,17 @@ export interface ProviderEndpointConfig {
export type ImagePassMode = 'url' | 'base64'
+export interface ComfyUiParams {
+ workflowPreset: 'qwen21_3img' | 'qwen21_2img' | 'custom'
+ workflowJson: string
+ promptNodeId: string
+ portraitNodeId: string
+ costumeNodeId: string
+ poseNodeId: string
+ stitchedNodeId: string
+ randomizeSeed: boolean
+}
+
export interface GptParams {
endpointMode: 'images_edits_json' | 'images_edits' | 'responses' | 'chat'
size: 'auto' | '1024x1536' | '1024x1024' | '1536x1024'
@@ -115,6 +126,7 @@ export interface ApiConfig {
geminiParams: GeminiParams
qwenParams: QwenParams
doubaoParams: DoubaoParams
+ comfyuiParams: ComfyUiParams
}
export interface GenerationHistoryItem {