Skip to content

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

feat(comfyui): share scoped HTTP connection checks and clarify pending tasks

H-Bole91015abbbf33
diff --git a/src/components/studio/ComfyConnectionStatus.tsx b/src/components/studio/ComfyConnectionStatus.tsx
new file mode 100644
index 0000000..e043594
--- /dev/null
+++ b/src/components/studio/ComfyConnectionStatus.tsx
@@ -0,0 +1,24 @@
+import { useEffect } from 'react'
+import { Badge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { useStudio } from '@/store/studioStore'
+import { COMFY_CONNECTION_LABELS } from '@/store/useComfyConnection'
+
+export function ComfyConnectionStatus({ compact = false }: { compact?: boolean }) {
+ const { comfyConnection, checkComfyConnection, setComfyConnectionVisible } = useStudio()
+ useEffect(() => {
+ setComfyConnectionVisible(true)
+ return () => setComfyConnectionVisible(false)
+ }, [setComfyConnectionVisible])
+ const { status, checkedAt, info, error } = comfyConnection
+ return <div className="flex min-w-0 flex-wrap items-center gap-2 text-xs" role="status">
+ <Badge variant={status === 'error' ? 'destructive' : status === 'connected' ? 'default' : 'secondary'}>{`ComfyUI · ${COMFY_CONNECTION_LABELS[status]}`}</Badge>
+ {compact && checkedAt && <span className="text-muted-foreground">{new Date(checkedAt).toLocaleTimeString()}</span>}
+ {!compact && <>
+ {info && status === 'connected' && <span>{info}</span>}
+ {error && <span className="break-words text-destructive">{error}</span>}
+ <span className="text-muted-foreground">{checkedAt ? `最近检测 ${new Date(checkedAt).toLocaleTimeString()}` : '尚无检测记录'};HTTP 检测不代表任务 WebSocket 已连接</span>
+ </>}
+ <Button type="button" size="sm" variant="outline" className="min-h-11" disabled={status === 'checking'} onClick={() => void checkComfyConnection(true)}>检测连接</Button>
+ </div>
+}
diff --git a/src/routes/settings.tsx b/src/routes/settings.tsx
index d764aec..5bca56d 100644
--- a/src/routes/settings.tsx
+++ b/src/routes/settings.tsx
@@ -1,6 +1,5 @@
import { createFileRoute, Link } from '@tanstack/react-router'
import {
- ActivityIcon,
CheckIcon,
ExternalLinkIcon,
EyeIcon,
@@ -17,9 +16,11 @@ 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 { detectComfyUi, PROVIDER_META, testComfyConnection } from '@/services/aiGenerator'
+import { detectComfyUi, PROVIDER_META } from '@/services/aiGenerator'
import { useStudio } from '@/store/studioStore'
import type { ImagePassMode, ImageProviderId } from '@/types/gallery'
+import { ComfyConnectionStatus } from '@/components/studio/ComfyConnectionStatus'
+import { COMFY_CONNECTION_LABELS } from '@/store/useComfyConnection'
export const Route = createFileRoute('/settings')({
staticData: { title: 'API 配置' },
@@ -29,7 +30,7 @@ export const Route = createFileRoute('/settings')({
const PROVIDER_ORDER: ImageProviderId[] = ['gemini', 'gpt', 'qwen', 'doubao', 'comfyui']
function SettingsPage() {
- const { apiConfig, updateApiConfig, updateProviderConfig } = useStudio()
+ const { apiConfig, updateApiConfig, updateProviderConfig, comfyConnection } = useStudio()
const [showKey, setShowKey] = useState(false)
const [testingComfy, setTestingComfy] = useState(false)
@@ -37,18 +38,6 @@ function SettingsPage() {
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 (e) {
- toast.error(e instanceof Error ? e.message : '连接失败', { duration: 10000 })
- } finally {
- setTestingComfy(false)
- }
- }
-
const handleDetectComfy = async () => {
setTestingComfy(true)
try {
@@ -100,18 +89,21 @@ function SettingsPage() {
: 'border-border/60 bg-card hover:bg-muted/40'
}`}
>
- <span className="truncate text-xs sm:text-sm">{itemMeta.name}</span>
+ <span className="min-w-0"><span className="block truncate text-sm">{itemMeta.name}</span><span className="block text-xs font-normal text-muted-foreground">{id === 'comfyui' ? COMFY_CONNECTION_LABELS[comfyConnection.status] : hasKey ? '已配置' : '未配置 Key'}</span></span>
<span
+ aria-hidden="true"
className={`size-2 shrink-0 rounded-full ${
- hasKey ? 'bg-emerald-500' : 'bg-muted-foreground/30'
+ id === 'comfyui' && comfyConnection.status === 'connected' ? 'bg-emerald-500' : hasKey ? 'bg-amber-500' : 'bg-muted-foreground/30'
}`}
- title={hasKey ? '已就绪' : '未配置 Key'}
+ title={id === 'comfyui' ? COMFY_CONNECTION_LABELS[comfyConnection.status] : hasKey ? '已配置,尚未检测' : '未配置 Key'}
/>
</button>
)
})}
</div>
+ {pid === 'comfyui' && <ComfyConnectionStatus />}
+
{/* 当前厂商连接配置 */}
<Section
title={`${meta.name} 连接配置`}
@@ -123,10 +115,6 @@ function SettingsPage() {
<ScanSearchIcon className="size-3.5" />
自动识别
</Button>
- <Button variant="outline" size="sm" onClick={handleTestComfy} disabled={testingComfy}>
- <ActivityIcon className="size-3.5" />
- {testingComfy ? '检测中…' : '测试连接'}
- </Button>
</>
)}
<Button variant="ghost" size="sm" asChild>
diff --git a/src/routes/studio.tsx b/src/routes/studio.tsx
index b0c39cd..a6403b6 100644
--- a/src/routes/studio.tsx
+++ b/src/routes/studio.tsx
@@ -30,6 +30,7 @@ import { type ChangeEvent, type DragEvent, useEffect, useMemo, useRef, useState
import { toast } from 'sonner'
import { costumesQuery, portraitsQuery, posesQuery } from '@/api/gallery'
import { Field, Section } from '@/components/common/FormSection'
+import { ComfyConnectionStatus } from '@/components/studio/ComfyConnectionStatus'
import { WorkflowParameters } from '@/components/studio/WorkflowParameters'
import { applyWorkflowOverrides, validateReferenceCombinations, workflowIdentity } from '@/lib/comfyWorkflowParameters'
import { PageHeader } from '@/components/common/PageHeader'
@@ -382,10 +383,10 @@ function StudioPage() {
<PageHeader
title="AI 角色合成台"
actions={
- <Button variant="outline" size="sm" asChild>
+ activeProvider === 'comfyui' ? <ComfyConnectionStatus compact /> : <Button variant="outline" size="sm" asChild>
<Link to="/settings">
<KeyRoundIcon className="size-4" />
- {providerCfg.apiKey ? `${providerMeta.shortName} 已就绪` : '配置 API Key'}
+ {providerCfg.apiKey.trim() ? `${providerMeta.shortName} 已配置` : '配置 API Key'}
</Link>
</Button>
}
@@ -1357,13 +1358,6 @@ function StudioPage() {
)}
</Section>
- {activeTask && <Section title="未决任务" className="@lg/section:grid-cols-1">
- <p className="break-all text-xs">{activeTask.task ? `任务 ${activeTask.task.promptId}:刷新后查询原任务,不重复提交。` : '提交结果未知或提交前被中断,请核对后端队列;不会自动重试提交。'}</p>
- <div className="flex flex-wrap gap-2">
- <Button disabled={isGenerating || !activeTask.task} onClick={() => void resumeGeneration()}>恢复追踪</Button>
- <Button variant="outline" onClick={() => void stopTracking()}>停止跟踪(不取消后端)</Button>
- </div>
- </Section>}
{/* 3. 提示词与生成按钮 */}
<Section
title="3. 提示词 (Prompt)"
@@ -1416,7 +1410,7 @@ function StudioPage() {
</div>
{/* 右栏:专注展示 AI 生成结果与生成状态 */}
- <div className="min-w-0 lg:col-span-5">
+ <div className="min-w-0 space-y-4 lg:col-span-5">
<Section
title="生成结果"
className="@lg/section:grid-cols-1"
@@ -1486,6 +1480,13 @@ function StudioPage() {
)}
</div>
</Section>
+ {activeTask && <Section title="待确认任务" className="@lg/section:grid-cols-1">
+ <p className="break-all text-xs">{activeTask.task ? `任务 ${activeTask.task.promptId}:刷新后查询原任务,不重复提交。` : '提交结果未知或提交前被中断,请核对后端队列;不会自动重试提交。'}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button disabled={isGenerating || !activeTask.task} onClick={() => void resumeGeneration()}>恢复跟踪</Button>
+ <Button variant="outline" onClick={() => void stopTracking()}>停止跟踪(不取消后端)</Button>
+ </div>
+ </Section>}
</div>
</div>
diff --git a/src/services/aiGenerator.ts b/src/services/aiGenerator.ts
index 29dc5cf..dad4986 100644
--- a/src/services/aiGenerator.ts
+++ b/src/services/aiGenerator.ts
@@ -743,7 +743,7 @@ export function autoDetectComfyMappings(workflowJson: string): ComfyNodeMappings
// 网络请求与中文错误
// ---------------------------------------------------------------------------
-function normalizeComfyBase(baseUrl: string): string {
+export function normalizeComfyBase(baseUrl: string): string {
return (baseUrl.trim() || defaultComfyBaseUrl()).replace(/\/+$/, '')
}
@@ -768,7 +768,7 @@ function describeComfyNetworkError(baseUrl: string, timedOut: boolean): string {
return `[ComfyUI] 无法连接 ${baseUrl}。可能原因:\n${reasons.join('\n')}`
}
-async function comfyFetch(
+export async function comfyFetch(
baseUrl: string,
path: string,
init: RequestInit = {},
@@ -781,7 +781,8 @@ async function comfyFetch(
const timer = setTimeout(() => ctrl.abort(), timeoutMs)
let res: Response
try {
- res = await fetch(`${baseUrl}${path}`, { ...init, headers, signal: ctrl.signal })
+ const signal = init.signal ? AbortSignal.any([ctrl.signal, init.signal]) : ctrl.signal
+ res = await fetch(`${baseUrl}${path}`, { ...init, headers, signal })
} catch (e: any) {
throw new Error(describeComfyNetworkError(baseUrl, e?.name === 'AbortError'))
} finally {
diff --git a/src/store/studioStore.tsx b/src/store/studioStore.tsx
index 0fe9f13..1d38269 100644
--- a/src/store/studioStore.tsx
+++ b/src/store/studioStore.tsx
@@ -11,6 +11,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog'
+import { useComfyConnection, type ComfyConnectionState } from './useComfyConnection'
import { idbRead, idbWrite } from '@/lib/idbStorage'
import { parseParameterWorkflow, workflowIdentity } from '@/lib/comfyWorkflowParameters'
import { durableImage, snapshotGeneration } from '@/lib/generationSnapshot'
@@ -194,6 +195,9 @@ function mergeStoredConfig(raw: unknown): ApiConfig {
}
interface StudioContextValue {
+ comfyConnection: ComfyConnectionState
+ checkComfyConnection: (manual?: boolean) => Promise<void>
+ setComfyConnectionVisible: (visible: boolean) => void
hydrated: boolean
activeTask: ActiveTask | null
resumeGeneration: () => Promise<void>
@@ -279,6 +283,9 @@ export function StudioProvider({ children }: { children: ReactNode }) {
}
})
+ const [comfyConnectionVisible, setComfyConnectionVisible] = useState(false)
+ const { comfyConnection, checkComfyConnection } = useComfyConnection(apiConfig.providers.comfyui.baseUrl, apiConfig.providers.comfyui.apiKey, comfyConnectionVisible && apiConfig.activeProvider === 'comfyui')
+
const [safeMode, setSafeMode] = useState<boolean>(() => {
try {
const raw = localStorage.getItem(SAFE_MODE_KEY)
@@ -344,7 +351,7 @@ export function StudioProvider({ children }: { children: ReactNode }) {
activeTaskRef.current = savedTask || null
setActiveTask(savedTask || null)
setIdbHydrated(true)
- }).catch(() => { if (active) toast.error('无法读取浏览器存储,已暂停生成以保护未决任务;请恢复存储后刷新') })
+ }).catch(() => { if (active) toast.error('无法读取浏览器存储,已暂停生成以保护待确认任务;请恢复存储后刷新') })
return () => {
active = false
}
@@ -646,7 +653,7 @@ export function StudioProvider({ children }: { children: ReactNode }) {
useEffect(() => () => trackingRef.current?.abort(), [])
const startGeneration = async (overridePrompt?: string) => {
if (!idbHydrated || isGeneratingRef.current) return
- if (activeTaskRef.current) { toast.error('存在未决任务,请先恢复或明确停止跟踪'); return }
+ if (activeTaskRef.current) { toast.error('存在待确认任务,请先恢复或明确停止跟踪'); return }
const recipeSnapshot = recipe
const configSnapshot = apiConfig
const finalPrompt = overridePrompt ?? customPrompt ?? buildRecipePrompt(recipeSnapshot, configSnapshot.stylePreset, configSnapshot.activeProvider === 'comfyui' && recipeSnapshot.workflowImagesIdentity === workflowIdentity(configSnapshot.comfyuiParams.workflowJson) ? Object.values(recipeSnapshot.workflowImages || {}) : [])
@@ -692,6 +699,7 @@ export function StudioProvider({ children }: { children: ReactNode }) {
return (
<StudioContext.Provider
value={{
+ comfyConnection, checkComfyConnection, setComfyConnectionVisible,
hydrated: idbHydrated,
activeTask, resumeGeneration, stopTracking,
recipe,
diff --git a/src/store/useComfyConnection.ts b/src/store/useComfyConnection.ts
new file mode 100644
index 0000000..48a3931
--- /dev/null
+++ b/src/store/useComfyConnection.ts
@@ -0,0 +1,104 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { toast } from 'sonner'
+import { comfyFetch, normalizeComfyBase } from '@/services/aiGenerator'
+
+export type ComfyConnectionState = {
+ status: 'notconfigured' | 'unchecked' | 'checking' | 'connected' | 'error' | 'offline'
+ checkedAt?: number
+ info?: string
+ error?: string
+}
+
+export const COMFY_CONNECTION_LABELS: Record<ComfyConnectionState['status'], string> = {
+ notconfigured: '未配置地址', unchecked: '尚未检测', checking: '检测中…', connected: 'HTTP 可达', error: '连接失败', offline: '浏览器离线',
+}
+const TOAST_ID = 'comfy-connection-test'
+const isOffline = () => navigator.onLine === false
+
+// 根 Provider 持有唯一检测器,页面只注册是否需要检测,不影响生成任务的 WebSocket。
+export function useComfyConnection(baseUrl: string, apiKey: string, enabled: boolean) {
+ const scope = useMemo(() => Symbol(baseUrl ? apiKey ? 'authenticated-endpoint' : 'anonymous-endpoint' : 'unconfigured-endpoint'), [baseUrl, apiKey])
+ const [saved, setSaved] = useState<{ scope: symbol; value: ComfyConnectionState }>()
+ const request = useRef<{ controller: AbortController; epoch: number; manual: boolean } | null>(null)
+ const epoch = useRef(0)
+ const initialStatus = !baseUrl.trim() ? 'notconfigured' : isOffline() ? 'offline' : 'unchecked'
+ const connection: ComfyConnectionState = saved?.scope === scope ? saved.value : { status: initialStatus }
+
+ const abort = useCallback(() => {
+ epoch.current += 1
+ request.current?.controller.abort()
+ if (request.current?.manual) toast.dismiss(TOAST_ID)
+ request.current = null
+ setSaved((previous) => previous?.value.status === 'checking' ? { ...previous, value: { ...previous.value, status: 'unchecked' } } : previous)
+ }, [])
+
+ const checkConnection = useCallback(async (manual = false) => {
+ if (!enabled || document.visibilityState !== 'visible') return
+ if (request.current && !manual) return
+ abort()
+ if (!baseUrl.trim() || isOffline()) {
+ const value: ComfyConnectionState = { status: !baseUrl.trim() ? 'notconfigured' : 'offline' }
+ setSaved({ scope, value })
+ if (manual) toast.error(COMFY_CONNECTION_LABELS[value.status], { id: TOAST_ID })
+ return
+ }
+ const controller = new AbortController()
+ const startedEpoch = epoch.current
+ request.current = { controller, epoch: startedEpoch, manual }
+ setSaved((previous) => ({ scope, value: { ...(previous?.scope === scope ? previous.value : {}), status: 'checking', error: undefined } }))
+ if (manual) toast.loading('正在检测 ComfyUI HTTP 连接…', { id: TOAST_ID })
+ const timeout = setTimeout(() => controller.abort('timeout'), 8000)
+ const publish = (value: ComfyConnectionState) => {
+ if (epoch.current !== startedEpoch) return
+ setSaved({ scope, value })
+ if (manual) {
+ if (value.status === 'connected') toast.success(`HTTP 连接成功:${value.info}`, { id: TOAST_ID })
+ else toast.error(value.error || COMFY_CONNECTION_LABELS[value.status], { id: TOAST_ID, duration: 10000 })
+ }
+ }
+ try {
+ const response = await comfyFetch(normalizeComfyBase(baseUrl), '/system_stats', { signal: controller.signal }, apiKey, 8000)
+ if (!response.ok) {
+ publish({ status: 'error', checkedAt: Date.now(), error: response.status === 401 || response.status === 403 ? `鉴权失败(HTTP ${response.status}),请检查 API Key / 鉴权设置` : `HTTP ${response.status},请检查 ComfyUI 服务与代理` })
+ return
+ }
+ const data = await response.json()
+ controller.signal.throwIfAborted()
+ if (!data?.system || typeof data.system !== 'object' || Array.isArray(data.system)) {
+ publish({ status: 'error', checkedAt: Date.now(), error: '响应不是 ComfyUI system_stats 格式,请检查地址' })
+ return
+ }
+ // 只展示允许的版本字符,避免后端响应或错误文本带出凭据。
+ const version = typeof data.system.comfyui_version === 'string' && /^[\d.a-zA-Z_-]{1,40}$/.test(data.system.comfyui_version) && (!apiKey.trim() || !data.system.comfyui_version.includes(apiKey.trim())) ? data.system.comfyui_version : '未知版本'
+ publish({ status: 'connected', checkedAt: Date.now(), info: `ComfyUI ${version}` })
+ } catch {
+ publish({ status: isOffline() ? 'offline' : 'error', checkedAt: Date.now(), error: controller.signal.reason === 'timeout' ? '连接检测超时(8 秒),请检查 ComfyUI 是否忙碌或无响应' : '无法读取 ComfyUI 状态,请检查服务、地址、跨域和本地网络访问权限' })
+ } finally {
+ clearTimeout(timeout)
+ if (request.current?.epoch === startedEpoch) request.current = null
+ }
+ }, [enabled, baseUrl, apiKey, scope, abort])
+
+ useEffect(() => {
+ const activate = () => {
+ if (document.visibilityState === 'visible') void checkConnection()
+ else abort()
+ }
+ const offline = () => { abort(); setSaved({ scope, value: { status: baseUrl.trim() ? 'offline' : 'notconfigured' } }) }
+ if (!enabled) return abort
+ activate()
+ const interval = setInterval(activate, 30_000)
+ window.addEventListener('online', activate)
+ window.addEventListener('offline', offline)
+ document.addEventListener('visibilitychange', activate)
+ return () => {
+ abort()
+ clearInterval(interval)
+ window.removeEventListener('online', activate)
+ window.removeEventListener('offline', offline)
+ document.removeEventListener('visibilitychange', activate)
+ }
+ }, [enabled, baseUrl, scope, checkConnection, abort])
+
+ return { comfyConnection: connection, checkComfyConnection: checkConnection }
+}