Compare commits

..

8 Commits

Author SHA1 Message Date
filtered
5f94873ae3 Update pnpm lock file 2025-09-27 12:19:55 +10:00
filtered
b717a21a6a Remove unused zod-to-json-schema dependency 2025-09-27 12:19:49 +10:00
filtered
d9abeec10f Add re-exports for schemas 2025-09-27 12:14:56 +10:00
filtered
240255d9e9 Move schema files to schemas package 2025-09-27 12:14:56 +10:00
filtered
c5b5fb4021 Add tsconfig for schemas package 2025-09-27 12:14:56 +10:00
filtered
0cebc52fd2 Update pnpm lock file 2025-09-27 12:06:43 +10:00
filtered
ca243be027 Add schemas package as dependency 2025-09-27 12:02:25 +10:00
filtered
1d908e18fa Create schemas package structure 2025-09-27 11:38:26 +10:00
73 changed files with 1563 additions and 2054 deletions

View File

@@ -210,6 +210,28 @@ test.describe('Templates', () => {
await expect(nav).toBeVisible() // Nav should be visible at tablet size
})
test('hover effects work on template cards', async ({ comfyPage }) => {
// Open templates dialog
await comfyPage.executeCommand('Comfy.BrowseTemplates')
await expect(comfyPage.templates.content).toBeVisible()
// Get a template card using data-testid
const firstCard = comfyPage.page
.locator('[data-testid^="template-workflow-"]')
.first()
await expect(firstCard).toBeVisible({ timeout: 5000 })
// Check initial state - card should have transition classes
// Take snapshot before hover
await expect(firstCard).toHaveScreenshot('template-card-before-hover.png')
// Hover over the card
await firstCard.hover()
// Take snapshot after hover to verify hover effect
await expect(firstCard).toHaveScreenshot('template-card-after-hover.png')
})
test('template cards descriptions adjust height dynamically', async ({
comfyPage
}) => {

View File

@@ -85,7 +85,6 @@ test.describe('Version Mismatch Warnings', () => {
test('should persist dismissed state across sessions', async ({
comfyPage
}) => {
test.setTimeout(30_000)
// Mock system_stats route to indicate that the installed version is always ahead of the required version
await comfyPage.page.route('**/system_stats**', async (route) => {
await route.fulfill({

View File

@@ -61,19 +61,6 @@ test.describe('NodeHeader', () => {
expect(titleAfterCancel).toBe('My Custom Sampler')
})
test('Double click node body does not trigger edit', async ({
comfyPage
}) => {
const loadCheckpointNode =
comfyPage.vueNodes.getNodeByTitle('Load Checkpoint')
const nodeBbox = await loadCheckpointNode.boundingBox()
if (!nodeBbox) throw new Error('Node not found')
await loadCheckpointNode.dblclick()
const editingTitleInput = comfyPage.page.getByTestId('node-title-input')
await expect(editingTitleInput).not.toBeVisible()
})
test('handles node collapsing', async ({ comfyPage }) => {
// Get the KSampler node from the default workflow
const nodes = await comfyPage.getNodeRefsByType('KSampler')

View File

@@ -1,33 +0,0 @@
import {
comfyExpect as expect,
comfyPageFixture as test
} from '../../../fixtures/ComfyPage'
test.describe('Vue Nodes Zoom', () => {
test.beforeEach(async ({ comfyPage }) => {
await comfyPage.setSetting('Comfy.VueNodes.Enabled', true)
await comfyPage.vueNodes.waitForNodes()
})
test('should not capture drag while zooming with ctrl+shift+drag', async ({
comfyPage
}) => {
const checkpointNode = comfyPage.vueNodes.getNodeByTitle('Load Checkpoint')
const nodeBoundingBox = await checkpointNode.boundingBox()
if (!nodeBoundingBox) throw new Error('Node bounding box not available')
const nodeMidpointX = nodeBoundingBox.x + nodeBoundingBox.width / 2
const nodeMidpointY = nodeBoundingBox.y + nodeBoundingBox.height / 2
// Start the Ctrl+Shift drag-to-zoom on the canvas and continue dragging over
// the node. The node should not capture the drag while drag-zooming.
await comfyPage.page.keyboard.down('Control')
await comfyPage.page.keyboard.down('Shift')
await comfyPage.dragAndDrop(
{ x: 200, y: 300 },
{ x: nodeMidpointX, y: nodeMidpointY }
)
await expect(comfyPage.canvas).toHaveScreenshot('zoomed-in-ctrl-shift.png')
})
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

After

Width:  |  Height:  |  Size: 106 KiB

View File

@@ -1,85 +0,0 @@
import {
comfyExpect as expect,
comfyPageFixture as test
} from '../../../fixtures/ComfyPage'
const PIN_HOTKEY = 'p'
const PIN_INDICATOR = '[data-testid="node-pin-indicator"]'
test.describe('Vue Node Pin', () => {
test.beforeEach(async ({ comfyPage }) => {
await comfyPage.setSetting('Comfy.VueNodes.Enabled', true)
await comfyPage.vueNodes.waitForNodes()
})
test('should allow toggling pin on a selected node with hotkey', async ({
comfyPage
}) => {
await comfyPage.page.getByText('Load Checkpoint').click()
await comfyPage.page.keyboard.press(PIN_HOTKEY)
const checkpointNode = comfyPage.vueNodes.getNodeByTitle('Load Checkpoint')
const pinIndicator = checkpointNode.locator(PIN_INDICATOR)
await expect(pinIndicator).toBeVisible()
await comfyPage.page.keyboard.press(PIN_HOTKEY)
await expect(pinIndicator).not.toBeVisible()
})
test('should allow toggling pin on multiple selected nodes with hotkey', async ({
comfyPage
}) => {
await comfyPage.page.getByText('Load Checkpoint').click()
await comfyPage.page.getByText('KSampler').click({ modifiers: ['Control'] })
const checkpointNode = comfyPage.vueNodes.getNodeByTitle('Load Checkpoint')
const ksamplerNode = comfyPage.vueNodes.getNodeByTitle('KSampler')
await comfyPage.page.keyboard.press(PIN_HOTKEY)
const pinIndicator1 = checkpointNode.locator(PIN_INDICATOR)
await expect(pinIndicator1).toBeVisible()
const pinIndicator2 = ksamplerNode.locator(PIN_INDICATOR)
await expect(pinIndicator2).toBeVisible()
await comfyPage.page.keyboard.press(PIN_HOTKEY)
await expect(pinIndicator1).not.toBeVisible()
await expect(pinIndicator2).not.toBeVisible()
})
test('should not allow dragging pinned nodes', async ({ comfyPage }) => {
const checkpointNodeHeader = comfyPage.page.getByText('Load Checkpoint')
await checkpointNodeHeader.click()
await comfyPage.page.keyboard.press(PIN_HOTKEY)
// Try to drag the node
const headerPos = await checkpointNodeHeader.boundingBox()
if (!headerPos) throw new Error('Failed to get header position')
await comfyPage.dragAndDrop(
{ x: headerPos.x, y: headerPos.y },
{ x: headerPos.x + 256, y: headerPos.y + 256 }
)
// Verify the node is not dragged (same position before and after click-and-drag)
const headerPosAfterDrag = await checkpointNodeHeader.boundingBox()
if (!headerPosAfterDrag)
throw new Error('Failed to get header position after drag')
expect(headerPosAfterDrag).toEqual(headerPos)
// Unpin the node with the hotkey
await checkpointNodeHeader.click()
await comfyPage.page.keyboard.press(PIN_HOTKEY)
// Try to drag the node again
await comfyPage.dragAndDrop(
{ x: headerPos.x, y: headerPos.y },
{ x: headerPos.x + 256, y: headerPos.y + 256 }
)
// Verify the node is dragged
const headerPosAfterDrag2 = await checkpointNodeHeader.boundingBox()
if (!headerPosAfterDrag2)
throw new Error('Failed to get header position after drag')
expect(headerPosAfterDrag2).not.toEqual(headerPos)
})
})

View File

@@ -1,49 +0,0 @@
import {
type ComfyPage,
comfyExpect as expect,
comfyPageFixture as test
} from '../../../../fixtures/ComfyPage'
test.describe('Vue Multiline String Widget', () => {
test.beforeEach(async ({ comfyPage }) => {
await comfyPage.setSetting('Comfy.VueNodes.Enabled', true)
await comfyPage.vueNodes.waitForNodes()
})
const getFirstClipNode = (comfyPage: ComfyPage) =>
comfyPage.vueNodes.getNodeByTitle('CLIP Text Encode (Prompt)').first()
const getFirstMultilineStringWidget = (comfyPage: ComfyPage) =>
getFirstClipNode(comfyPage).getByRole('textbox', { name: 'text' })
test('should allow entering text', async ({ comfyPage }) => {
const textarea = getFirstMultilineStringWidget(comfyPage)
await textarea.fill('Hello World')
await expect(textarea).toHaveValue('Hello World')
await textarea.fill('Hello World 2')
await expect(textarea).toHaveValue('Hello World 2')
})
test('should support entering multiline content', async ({ comfyPage }) => {
const textarea = getFirstMultilineStringWidget(comfyPage)
const multilineValue = ['Line 1', 'Line 2', 'Line 3'].join('\n')
await textarea.fill(multilineValue)
await expect(textarea).toHaveValue(multilineValue)
})
test('should retain value after focus changes', async ({ comfyPage }) => {
const textarea = getFirstMultilineStringWidget(comfyPage)
await textarea.fill('Keep me around')
// Click another node
const loadCheckpointNode =
comfyPage.vueNodes.getNodeByTitle('Load Checkpoint')
await loadCheckpointNode.click()
await getFirstClipNode(comfyPage).click()
await expect(textarea).toHaveValue('Keep me around')
})
})

View File

@@ -181,31 +181,5 @@ export default defineConfig([
{ disallowTypeAnnotations: false }
]
}
},
{
files: ['**/*.spec.ts'],
ignores: ['browser_tests/tests/**/*.spec.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector: 'Program',
message: '.spec.ts files are only allowed under browser_tests/tests/'
}
]
}
},
{
files: ['browser_tests/tests/**/*.test.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector: 'Program',
message:
'.test.ts files are not allowed in browser_tests/tests/; use .spec.ts instead'
}
]
}
}
])

View File

@@ -1,25 +1,15 @@
import type { KnipConfig } from 'knip'
const config: KnipConfig = {
workspaces: {
'.': {
entry: [
'{build,scripts}/**/*.{js,ts}',
'src/assets/css/style.css',
'src/main.ts',
'src/scripts/ui/menu/index.ts',
'src/types/index.ts'
],
project: ['**/*.{js,ts,vue}', '*.{js,ts,mts}']
},
'packages/tailwind-utils': {
project: ['src/**/*.{js,ts}']
},
'packages/design-system': {
entry: ['src/**/*.ts'],
project: ['src/**/*.{js,ts}', '*.{js,ts,mts}']
}
},
entry: [
'{build,scripts}/**/*.{js,ts}',
'src/assets/css/style.css',
'src/main.ts',
'src/scripts/ui/menu/index.ts',
'src/types/index.ts'
],
project: ['**/*.{js,ts,vue}', '*.{js,ts,mts}'],
ignoreBinaries: ['only-allow', 'openapi-typescript'],
ignoreDependencies: [
// Weird importmap things
'@iconify/json',

View File

@@ -1,7 +1,7 @@
{
"name": "@comfyorg/comfyui-frontend",
"private": true,
"version": "1.28.3",
"version": "1.28.2",
"type": "module",
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
"homepage": "https://comfy.org",
@@ -106,6 +106,7 @@
"@atlaskit/pragmatic-drag-and-drop": "^1.3.1",
"@comfyorg/comfyui-electron-types": "0.4.73-0",
"@comfyorg/design-system": "workspace:*",
"@comfyorg/schemas": "workspace:*",
"@comfyorg/tailwind-utils": "workspace:*",
"@iconify/json": "^2.2.380",
"@primeuix/forms": "0.0.2",
@@ -158,4 +159,4 @@
"zod": "^3.23.8",
"zod-validation-error": "^3.3.0"
}
}
}

View File

@@ -0,0 +1,33 @@
{
"name": "@comfyorg/schemas",
"version": "1.0.0",
"type": "module",
"description": "Shared Zod schemas for ComfyUI Frontend",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
"./apiSchema": "./src/apiSchema.ts",
"./colorPaletteSchema": "./src/colorPaletteSchema.ts",
"./keyBindingSchema": "./src/keyBindingSchema.ts",
"./nodeDefSchema": "./src/nodeDefSchema.ts",
"./nodeDef/nodeDefSchemaV2": "./src/nodeDef/nodeDefSchemaV2.ts",
"./nodeDef/migration": "./src/nodeDef/migration.ts",
"./signInSchema": "./src/signInSchema.ts"
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"nx": {
"tags": [
"scope:shared",
"type:schema"
]
},
"dependencies": {
"zod": "^3.23.8",
"zod-validation-error": "^3.3.0"
},
"devDependencies": {
"typescript": "^5.4.5"
}
}

View File

@@ -0,0 +1,526 @@
import { z } from 'zod'
import { LinkMarkerShape } from '@/lib/litegraph/src/litegraph'
import {
zComfyWorkflow,
zNodeId
} from '@/platform/workflow/validation/schemas/workflowSchema'
import { colorPalettesSchema } from '@/schemas/colorPaletteSchema'
import { zKeybinding } from '@/schemas/keyBindingSchema'
import { NodeBadgeMode } from '@/types/nodeSource'
import { LinkReleaseTriggerAction } from '@/types/searchBoxTypes'
const zNodeType = z.string()
const zQueueIndex = z.number()
const zPromptId = z.string()
export const resultItemType = z.enum(['input', 'output', 'temp'])
export type ResultItemType = z.infer<typeof resultItemType>
const zResultItem = z.object({
filename: z.string().optional(),
subfolder: z.string().optional(),
type: resultItemType.optional()
})
export type ResultItem = z.infer<typeof zResultItem>
const zOutputs = z
.object({
audio: z.array(zResultItem).optional(),
images: z.array(zResultItem).optional(),
video: z.array(zResultItem).optional(),
animated: z.array(z.boolean()).optional()
})
.passthrough()
// WS messages
const zStatusWsMessageStatus = z.object({
exec_info: z.object({
queue_remaining: z.number().int()
})
})
const zStatusWsMessage = z.object({
status: zStatusWsMessageStatus.nullish(),
sid: z.string().nullish()
})
const zProgressWsMessage = z.object({
value: z.number().int(),
max: z.number().int(),
prompt_id: zPromptId,
node: zNodeId
})
const zNodeProgressState = z.object({
value: z.number(),
max: z.number(),
state: z.enum(['pending', 'running', 'finished', 'error']),
node_id: zNodeId,
prompt_id: zPromptId,
display_node_id: zNodeId.optional(),
parent_node_id: zNodeId.optional(),
real_node_id: zNodeId.optional()
})
const zProgressStateWsMessage = z.object({
prompt_id: zPromptId,
nodes: z.record(zNodeId, zNodeProgressState)
})
const zExecutingWsMessage = z.object({
node: zNodeId,
display_node: zNodeId,
prompt_id: zPromptId
})
const zExecutedWsMessage = zExecutingWsMessage.extend({
output: zOutputs,
merge: z.boolean().optional()
})
const zExecutionWsMessageBase = z.object({
prompt_id: zPromptId,
timestamp: z.number().int()
})
const zExecutionStartWsMessage = zExecutionWsMessageBase
const zExecutionSuccessWsMessage = zExecutionWsMessageBase
const zExecutionCachedWsMessage = zExecutionWsMessageBase.extend({
nodes: z.array(zNodeId)
})
const zExecutionInterruptedWsMessage = zExecutionWsMessageBase.extend({
node_id: zNodeId,
node_type: zNodeType,
executed: z.array(zNodeId)
})
const zExecutionErrorWsMessage = zExecutionWsMessageBase.extend({
node_id: zNodeId,
node_type: zNodeType,
executed: z.array(zNodeId),
exception_message: z.string(),
exception_type: z.string(),
traceback: z.array(z.string()),
current_inputs: z.any(),
current_outputs: z.any()
})
const zProgressTextWsMessage = z.object({
nodeId: zNodeId,
text: z.string()
})
const zDisplayComponentWsMessage = z.object({
node_id: zNodeId,
component: z.enum(['ChatHistoryWidget']),
props: z.record(z.string(), z.any()).optional()
})
const zTerminalSize = z.object({
cols: z.number(),
row: z.number()
})
const zLogEntry = z.object({
t: z.string(),
m: z.string()
})
const zLogsWsMessage = z.object({
size: zTerminalSize.optional(),
entries: z.array(zLogEntry)
})
const zLogRawResponse = z.object({
size: zTerminalSize,
entries: z.array(zLogEntry)
})
const zFeatureFlagsWsMessage = z.record(z.string(), z.any())
export type StatusWsMessageStatus = z.infer<typeof zStatusWsMessageStatus>
export type StatusWsMessage = z.infer<typeof zStatusWsMessage>
export type ProgressWsMessage = z.infer<typeof zProgressWsMessage>
export type ExecutingWsMessage = z.infer<typeof zExecutingWsMessage>
export type ExecutedWsMessage = z.infer<typeof zExecutedWsMessage>
export type ExecutionStartWsMessage = z.infer<typeof zExecutionStartWsMessage>
export type ExecutionSuccessWsMessage = z.infer<
typeof zExecutionSuccessWsMessage
>
export type ExecutionCachedWsMessage = z.infer<typeof zExecutionCachedWsMessage>
export type ExecutionInterruptedWsMessage = z.infer<
typeof zExecutionInterruptedWsMessage
>
export type ExecutionErrorWsMessage = z.infer<typeof zExecutionErrorWsMessage>
export type LogsWsMessage = z.infer<typeof zLogsWsMessage>
export type ProgressTextWsMessage = z.infer<typeof zProgressTextWsMessage>
export type DisplayComponentWsMessage = z.infer<
typeof zDisplayComponentWsMessage
>
export type NodeProgressState = z.infer<typeof zNodeProgressState>
export type ProgressStateWsMessage = z.infer<typeof zProgressStateWsMessage>
export type FeatureFlagsWsMessage = z.infer<typeof zFeatureFlagsWsMessage>
// End of ws messages
const zPromptInputItem = z.object({
inputs: z.record(z.string(), z.any()),
class_type: zNodeType
})
const zPromptInputs = z.record(zPromptInputItem)
const zExtraPngInfo = z
.object({
workflow: zComfyWorkflow
})
.passthrough()
const zExtraData = z.object({
/** extra_pnginfo can be missing is backend execution gets a validation error. */
extra_pnginfo: zExtraPngInfo.optional(),
client_id: z.string()
})
const zOutputsToExecute = z.array(zNodeId)
const zExecutionStartMessage = z.tuple([
z.literal('execution_start'),
zExecutionStartWsMessage
])
const zExecutionSuccessMessage = z.tuple([
z.literal('execution_success'),
zExecutionSuccessWsMessage
])
const zExecutionCachedMessage = z.tuple([
z.literal('execution_cached'),
zExecutionCachedWsMessage
])
const zExecutionInterruptedMessage = z.tuple([
z.literal('execution_interrupted'),
zExecutionInterruptedWsMessage
])
const zExecutionErrorMessage = z.tuple([
z.literal('execution_error'),
zExecutionErrorWsMessage
])
const zStatusMessage = z.union([
zExecutionStartMessage,
zExecutionSuccessMessage,
zExecutionCachedMessage,
zExecutionInterruptedMessage,
zExecutionErrorMessage
])
const zStatus = z.object({
status_str: z.enum(['success', 'error']),
completed: z.boolean(),
messages: z.array(zStatusMessage)
})
const zTaskPrompt = z.tuple([
zQueueIndex,
zPromptId,
zPromptInputs,
zExtraData,
zOutputsToExecute
])
const zRunningTaskItem = z.object({
taskType: z.literal('Running'),
prompt: zTaskPrompt,
// @Deprecated
remove: z.object({
name: z.literal('Cancel'),
cb: z.function()
})
})
const zPendingTaskItem = z.object({
taskType: z.literal('Pending'),
prompt: zTaskPrompt
})
const zTaskOutput = z.record(zNodeId, zOutputs)
const zNodeOutputsMeta = z.object({
node_id: zNodeId,
display_node: zNodeId,
prompt_id: zPromptId.optional(),
read_node_id: zNodeId.optional()
})
const zTaskMeta = z.record(zNodeId, zNodeOutputsMeta)
const zHistoryTaskItem = z.object({
taskType: z.literal('History'),
prompt: zTaskPrompt,
status: zStatus.optional(),
outputs: zTaskOutput,
meta: zTaskMeta.optional()
})
const zTaskItem = z.union([
zRunningTaskItem,
zPendingTaskItem,
zHistoryTaskItem
])
const zTaskType = z.union([
z.literal('Running'),
z.literal('Pending'),
z.literal('History')
])
export type TaskType = z.infer<typeof zTaskType>
export type TaskPrompt = z.infer<typeof zTaskPrompt>
export type TaskStatus = z.infer<typeof zStatus>
export type TaskOutput = z.infer<typeof zTaskOutput>
// `/queue`
export type RunningTaskItem = z.infer<typeof zRunningTaskItem>
export type PendingTaskItem = z.infer<typeof zPendingTaskItem>
// `/history`
export type HistoryTaskItem = z.infer<typeof zHistoryTaskItem>
export type TaskItem = z.infer<typeof zTaskItem>
const zEmbeddingsResponse = z.array(z.string())
const zExtensionsResponse = z.array(z.string())
const zError = z.object({
type: z.string(),
message: z.string(),
details: z.string(),
extra_info: z
.object({
input_name: z.string().optional()
})
.passthrough()
.optional()
})
const zNodeError = z.object({
errors: z.array(zError),
class_type: z.string(),
dependent_outputs: z.array(z.any())
})
const zPromptResponse = z.object({
node_errors: z.record(zNodeId, zNodeError).optional(),
prompt_id: z.string().optional(),
exec_info: z
.object({
queue_remaining: z.number().optional()
})
.optional(),
error: z.union([z.string(), zError])
})
const zDeviceStats = z.object({
name: z.string(),
type: z.string(),
index: z.number(),
vram_total: z.number(),
vram_free: z.number(),
torch_vram_total: z.number(),
torch_vram_free: z.number()
})
const zSystemStats = z.object({
system: z.object({
os: z.string(),
python_version: z.string(),
embedded_python: z.boolean(),
comfyui_version: z.string(),
pytorch_version: z.string(),
required_frontend_version: z.string().optional(),
argv: z.array(z.string()),
ram_total: z.number(),
ram_free: z.number()
}),
devices: z.array(zDeviceStats)
})
const zUser = z.object({
storage: z.enum(['server']),
// `migrated` is only available in single-user mode.
migrated: z.boolean().optional(),
// `users` is only available in multi-user server mode.
users: z.record(z.string(), z.string()).optional()
})
const zUserData = z.array(z.array(z.string(), z.string()))
const zUserDataFullInfo = z.object({
path: z.string(),
size: z.number(),
modified: z.number()
})
const zBookmarkCustomization = z.object({
icon: z.string().optional(),
color: z.string().optional()
})
export type BookmarkCustomization = z.infer<typeof zBookmarkCustomization>
const zLinkReleaseTriggerAction = z.enum(
Object.values(LinkReleaseTriggerAction) as [string, ...string[]]
)
const zNodeBadgeMode = z.enum(
Object.values(NodeBadgeMode) as [string, ...string[]]
)
const zSettings = z.object({
'Comfy.ColorPalette': z.string(),
'Comfy.CustomColorPalettes': colorPalettesSchema,
'Comfy.Canvas.BackgroundImage': z.string().optional(),
'Comfy.ConfirmClear': z.boolean(),
'Comfy.DevMode': z.boolean(),
'Comfy.Workflow.ShowMissingNodesWarning': z.boolean(),
'Comfy.Workflow.ShowMissingModelsWarning': z.boolean(),
'Comfy.Workflow.WarnBlueprintOverwrite': z.boolean(),
'Comfy.DisableFloatRounding': z.boolean(),
'Comfy.DisableSliders': z.boolean(),
'Comfy.DOMClippingEnabled': z.boolean(),
'Comfy.EditAttention.Delta': z.number(),
'Comfy.EnableTooltips': z.boolean(),
'Comfy.EnableWorkflowViewRestore': z.boolean(),
'Comfy.FloatRoundingPrecision': z.number(),
'Comfy.Graph.CanvasInfo': z.boolean(),
'Comfy.Graph.CanvasMenu': z.boolean(),
'Comfy.Graph.CtrlShiftZoom': z.boolean(),
'Comfy.Graph.LinkMarkers': z.nativeEnum(LinkMarkerShape),
'Comfy.Graph.ZoomSpeed': z.number(),
'Comfy.Group.DoubleClickTitleToEdit': z.boolean(),
'Comfy.GroupSelectedNodes.Padding': z.number(),
'Comfy.Locale': z.string(),
'Comfy.NodeLibrary.Bookmarks': z.array(z.string()),
'Comfy.NodeLibrary.Bookmarks.V2': z.array(z.string()),
'Comfy.NodeLibrary.BookmarksCustomization': z.record(
z.string(),
zBookmarkCustomization
),
'Comfy.LinkRelease.Action': zLinkReleaseTriggerAction,
'Comfy.LinkRelease.ActionShift': zLinkReleaseTriggerAction,
'Comfy.ModelLibrary.AutoLoadAll': z.boolean(),
'Comfy.ModelLibrary.NameFormat': z.enum(['filename', 'title']),
'Comfy.NodeSearchBoxImpl.NodePreview': z.boolean(),
'Comfy.NodeSearchBoxImpl': z.enum(['default', 'simple']),
'Comfy.NodeSearchBoxImpl.ShowCategory': z.boolean(),
'Comfy.NodeSearchBoxImpl.ShowIdName': z.boolean(),
'Comfy.NodeSearchBoxImpl.ShowNodeFrequency': z.boolean(),
'Comfy.NodeSuggestions.number': z.number(),
'Comfy.Node.BypassAllLinksOnDelete': z.boolean(),
'Comfy.Node.Opacity': z.number(),
'Comfy.Node.MiddleClickRerouteNode': z.boolean(),
'Comfy.Node.ShowDeprecated': z.boolean(),
'Comfy.Node.ShowExperimental': z.boolean(),
'Comfy.Pointer.ClickBufferTime': z.number(),
'Comfy.Pointer.ClickDrift': z.number(),
'Comfy.Pointer.DoubleClickTime': z.number(),
'Comfy.PreviewFormat': z.string(),
'Comfy.PromptFilename': z.boolean(),
'Comfy.Sidebar.Location': z.enum(['left', 'right']),
'Comfy.Sidebar.Size': z.enum(['small', 'normal']),
'Comfy.Sidebar.UnifiedWidth': z.boolean(),
'Comfy.SnapToGrid.GridSize': z.number(),
'Comfy.TextareaWidget.FontSize': z.number(),
'Comfy.TextareaWidget.Spellcheck': z.boolean(),
'Comfy.UseNewMenu': z.enum(['Disabled', 'Top', 'Bottom']),
'Comfy.TreeExplorer.ItemPadding': z.number(),
'Comfy.Validation.Workflows': z.boolean(),
'Comfy.Workflow.SortNodeIdOnSave': z.boolean(),
'Comfy.Queue.ImageFit': z.enum(['contain', 'cover']),
'Comfy.Workflow.WorkflowTabsPosition': z.enum([
'Sidebar',
'Topbar',
'Topbar (2nd-row)'
]),
'Comfy.Node.DoubleClickTitleToEdit': z.boolean(),
'Comfy.WidgetControlMode': z.enum(['before', 'after']),
'Comfy.Window.UnloadConfirmation': z.boolean(),
'Comfy.NodeBadge.NodeSourceBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.NodeIdBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.NodeLifeCycleBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.ShowApiPricing': z.boolean(),
'Comfy.Notification.ShowVersionUpdates': z.boolean(),
'Comfy.QueueButton.BatchCountLimit': z.number(),
'Comfy.Queue.MaxHistoryItems': z.number(),
'Comfy.Keybinding.UnsetBindings': z.array(zKeybinding),
'Comfy.Keybinding.NewBindings': z.array(zKeybinding),
'Comfy.Extension.Disabled': z.array(z.string()),
'Comfy.LinkRenderMode': z.number(),
'Comfy.Node.AutoSnapLinkToSlot': z.boolean(),
'Comfy.Node.SnapHighlightsNode': z.boolean(),
'Comfy.Server.ServerConfigValues': z.record(z.string(), z.any()),
'Comfy.Server.LaunchArgs': z.record(z.string(), z.string()),
'LiteGraph.Canvas.MaximumFps': z.number(),
'Comfy.Workflow.ConfirmDelete': z.boolean(),
'Comfy.Workflow.AutoSaveDelay': z.number(),
'Comfy.Workflow.AutoSave': z.enum(['off', 'after delay']),
'Comfy.RerouteBeta': z.boolean(),
'LiteGraph.Canvas.MinFontSizeForLOD': z.number(),
'Comfy.Canvas.SelectionToolbox': z.boolean(),
'LiteGraph.Node.TooltipDelay': z.number(),
'LiteGraph.ContextMenu.Scaling': z.boolean(),
'LiteGraph.Reroute.SplineOffset': z.number(),
'LiteGraph.Canvas.LowQualityRenderingZoomThreshold': z.number(),
'Comfy.Toast.DisableReconnectingToast': z.boolean(),
'Comfy.Workflow.Persist': z.boolean(),
'Comfy.TutorialCompleted': z.boolean(),
'Comfy.InstalledVersion': z.string().nullable(),
'Comfy.Node.AllowImageSizeDraw': z.boolean(),
'Comfy.Minimap.Visible': z.boolean(),
'Comfy.Minimap.NodeColors': z.boolean(),
'Comfy.Minimap.ShowLinks': z.boolean(),
'Comfy.Minimap.ShowGroups': z.boolean(),
'Comfy.Minimap.RenderBypassState': z.boolean(),
'Comfy.Minimap.RenderErrorState': z.boolean(),
'Comfy.Canvas.NavigationMode': z.string(),
'Comfy.Canvas.LeftMouseClickBehavior': z.string(),
'Comfy.Canvas.MouseWheelScroll': z.string(),
'Comfy.VueNodes.Enabled': z.boolean(),
'Comfy.Assets.UseAssetAPI': z.boolean(),
'Comfy-Desktop.AutoUpdate': z.boolean(),
'Comfy-Desktop.SendStatistics': z.boolean(),
'Comfy-Desktop.WindowStyle': z.string(),
'Comfy-Desktop.UV.PythonInstallMirror': z.string(),
'Comfy-Desktop.UV.PypiInstallMirror': z.string(),
'Comfy-Desktop.UV.TorchInstallMirror': z.string(),
'Comfy.MaskEditor.UseNewEditor': z.boolean(),
'Comfy.MaskEditor.BrushAdjustmentSpeed': z.number(),
'Comfy.MaskEditor.UseDominantAxis': z.boolean(),
'Comfy.Load3D.ShowGrid': z.boolean(),
'Comfy.Load3D.ShowPreview': z.boolean(),
'Comfy.Load3D.BackgroundColor': z.string(),
'Comfy.Load3D.LightIntensity': z.number(),
'Comfy.Load3D.LightIntensityMaximum': z.number(),
'Comfy.Load3D.LightIntensityMinimum': z.number(),
'Comfy.Load3D.LightAdjustmentIncrement': z.number(),
'Comfy.Load3D.CameraType': z.enum(['perspective', 'orthographic']),
'Comfy.Load3D.3DViewerEnable': z.boolean(),
'Comfy.Memory.AllowManualUnload': z.boolean(),
'pysssss.SnapToGrid': z.boolean(),
/** VHS setting is used for queue video preview support. */
'VHS.AdvancedPreviews': z.string(),
/** Release data settings */
'Comfy.Release.Version': z.string(),
'Comfy.Release.Status': z.enum([
'skipped',
'changelog seen',
"what's new seen"
]),
'Comfy.Release.Timestamp': z.number(),
/** Settings used for testing */
'test.setting': z.any(),
'main.sub.setting.name': z.any(),
'single.setting': z.any(),
'LiteGraph.Node.DefaultPadding': z.boolean(),
'LiteGraph.Pointer.TrackpadGestures': z.boolean()
})
export type EmbeddingsResponse = z.infer<typeof zEmbeddingsResponse>
export type ExtensionsResponse = z.infer<typeof zExtensionsResponse>
export type PromptResponse = z.infer<typeof zPromptResponse>
export type NodeError = z.infer<typeof zNodeError>
export type Settings = z.infer<typeof zSettings>
export type DeviceStats = z.infer<typeof zDeviceStats>
export type SystemStats = z.infer<typeof zSystemStats>
export type User = z.infer<typeof zUser>
export type UserData = z.infer<typeof zUserData>
export type UserDataFullInfo = z.infer<typeof zUserDataFullInfo>
export type TerminalSize = z.infer<typeof zTerminalSize>
export type LogEntry = z.infer<typeof zLogEntry>
export type LogsRawResponse = z.infer<typeof zLogRawResponse>

View File

@@ -0,0 +1,116 @@
import { z } from 'zod'
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
const nodeSlotSchema = z.object({
CLIP: z.string(),
CLIP_VISION: z.string(),
CLIP_VISION_OUTPUT: z.string(),
CONDITIONING: z.string(),
CONTROL_NET: z.string(),
IMAGE: z.string(),
LATENT: z.string(),
MASK: z.string(),
MODEL: z.string(),
STYLE_MODEL: z.string(),
VAE: z.string(),
NOISE: z.string(),
GUIDER: z.string(),
SAMPLER: z.string(),
SIGMAS: z.string(),
TAESD: z.string()
})
const litegraphBaseSchema = z.object({
BACKGROUND_IMAGE: z.string(),
CLEAR_BACKGROUND_COLOR: z.string(),
NODE_TITLE_COLOR: z.string(),
NODE_SELECTED_TITLE_COLOR: z.string(),
NODE_TEXT_SIZE: z.number(),
NODE_TEXT_COLOR: z.string(),
NODE_TEXT_HIGHLIGHT_COLOR: z.string(),
NODE_SUBTEXT_SIZE: z.number(),
NODE_DEFAULT_COLOR: z.string(),
NODE_DEFAULT_BGCOLOR: z.string(),
NODE_DEFAULT_BOXCOLOR: z.string(),
NODE_DEFAULT_SHAPE: z.union([
z.literal(LiteGraph.BOX_SHAPE),
z.literal(LiteGraph.ROUND_SHAPE),
z.literal(LiteGraph.CARD_SHAPE),
// Legacy palettes have string field for NODE_DEFAULT_SHAPE.
z.string()
]),
NODE_BOX_OUTLINE_COLOR: z.string(),
NODE_BYPASS_BGCOLOR: z.string(),
NODE_ERROR_COLOUR: z.string(),
DEFAULT_SHADOW_COLOR: z.string(),
DEFAULT_GROUP_FONT: z.number(),
WIDGET_BGCOLOR: z.string(),
WIDGET_OUTLINE_COLOR: z.string(),
WIDGET_TEXT_COLOR: z.string(),
WIDGET_SECONDARY_TEXT_COLOR: z.string(),
WIDGET_DISABLED_TEXT_COLOR: z.string(),
LINK_COLOR: z.string(),
EVENT_LINK_COLOR: z.string(),
CONNECTING_LINK_COLOR: z.string(),
BADGE_FG_COLOR: z.string(),
BADGE_BG_COLOR: z.string()
})
const comfyBaseSchema = z.object({
['fg-color']: z.string(),
['bg-color']: z.string(),
['bg-img']: z.string().optional(),
['comfy-menu-bg']: z.string(),
['comfy-menu-secondary-bg']: z.string(),
['comfy-input-bg']: z.string(),
['input-text']: z.string(),
['descrip-text']: z.string(),
['drag-text']: z.string(),
['error-text']: z.string(),
['border-color']: z.string(),
['tr-even-bg-color']: z.string(),
['tr-odd-bg-color']: z.string(),
['content-bg']: z.string(),
['content-fg']: z.string(),
['content-hover-bg']: z.string(),
['content-hover-fg']: z.string(),
['bar-shadow']: z.string()
})
const colorsSchema = z.object({
node_slot: nodeSlotSchema,
litegraph_base: litegraphBaseSchema,
comfy_base: comfyBaseSchema
})
const partialColorsSchema = z.object({
node_slot: nodeSlotSchema.partial(),
litegraph_base: litegraphBaseSchema.partial(),
comfy_base: comfyBaseSchema.partial()
})
// Palette in the wild can have custom metadata fields such as 'version'.
export const paletteSchema = z
.object({
id: z.string(),
name: z.string(),
colors: partialColorsSchema,
light_theme: z.boolean().optional()
})
.passthrough()
const completedPaletteSchema = z
.object({
id: z.string(),
name: z.string(),
colors: colorsSchema
})
.passthrough()
export const colorPalettesSchema = z.record(paletteSchema)
export type Colors = z.infer<typeof colorsSchema>
export type Palette = z.infer<typeof paletteSchema>
export type CompletedPalette = z.infer<typeof completedPaletteSchema>
export type ColorPalettes = z.infer<typeof colorPalettesSchema>

View File

@@ -0,0 +1,25 @@
import { z } from 'zod'
// KeyCombo schema
const zKeyCombo = z.object({
key: z.string(),
ctrl: z.boolean().optional(),
alt: z.boolean().optional(),
shift: z.boolean().optional(),
meta: z.boolean().optional()
})
// Keybinding schema
export const zKeybinding = z.object({
commandId: z.string(),
combo: zKeyCombo,
// Optional target element ID to limit keybinding to.
// Note: Currently only used to distinguish between global keybindings
// and litegraph canvas keybindings.
// Do NOT use this field in extensions as it has no effect.
targetElementId: z.string().optional()
})
// Infer types from schemas
export type KeyCombo = z.infer<typeof zKeyCombo>
export type Keybinding = z.infer<typeof zKeybinding>

View File

@@ -0,0 +1,143 @@
import type {
ComfyNodeDef as ComfyNodeDefV2,
InputSpec as InputSpecV2,
OutputSpec as OutputSpecV2
} from '@/schemas/nodeDef/nodeDefSchemaV2'
import type {
ComfyNodeDef as ComfyNodeDefV1,
InputSpec as InputSpecV1
} from '@/schemas/nodeDefSchema'
import {
getComboSpecComboOptions,
isComboInputSpec,
isComboInputSpecV1
} from '@/schemas/nodeDefSchema'
/**
* Transforms a V1 node definition to V2 format
* @param nodeDefV1 The V1 node definition to transform
* @returns The transformed V2 node definition
*/
export function transformNodeDefV1ToV2(
nodeDefV1: ComfyNodeDefV1
): ComfyNodeDefV2 {
// Transform inputs
const inputs: Record<string, InputSpecV2> = {}
// Process required inputs
if (nodeDefV1.input?.required) {
Object.entries(nodeDefV1.input.required).forEach(([name, inputSpecV1]) => {
inputs[name] = transformInputSpecV1ToV2(inputSpecV1, {
name,
isOptional: false
})
})
}
// Process optional inputs
if (nodeDefV1.input?.optional) {
Object.entries(nodeDefV1.input.optional).forEach(([name, inputSpecV1]) => {
inputs[name] = transformInputSpecV1ToV2(inputSpecV1, {
name,
isOptional: true
})
})
}
// Transform outputs
const outputs: OutputSpecV2[] = []
if (nodeDefV1.output) {
if (Array.isArray(nodeDefV1.output)) {
nodeDefV1.output.forEach((outputType, index) => {
const outputSpec: OutputSpecV2 = {
index,
name: nodeDefV1.output_name?.[index] || `output_${index}`,
type: Array.isArray(outputType) ? 'COMBO' : outputType,
is_list: nodeDefV1.output_is_list?.[index] || false,
tooltip: nodeDefV1.output_tooltips?.[index]
}
// Add options for combo outputs
if (Array.isArray(outputType)) {
outputSpec.options = outputType
}
outputs.push(outputSpec)
})
} else {
console.warn('nodeDefV1.output is not an array:', nodeDefV1.output)
}
}
// Create the V2 node definition
return {
inputs,
outputs,
hidden: nodeDefV1.input?.hidden,
name: nodeDefV1.name,
display_name: nodeDefV1.display_name,
description: nodeDefV1.description,
category: nodeDefV1.category,
output_node: nodeDefV1.output_node,
python_module: nodeDefV1.python_module,
deprecated: nodeDefV1.deprecated,
experimental: nodeDefV1.experimental
}
}
/**
* Transforms a V1 input specification to V2 format
* @param inputSpecV1 The V1 input specification to transform
* @param name The name of the input
* @param isOptional Whether the input is optional
* @returns The transformed V2 input specification
*/
export function transformInputSpecV1ToV2(
inputSpecV1: InputSpecV1,
kwargs: {
name: string
isOptional?: boolean
}
): InputSpecV2 {
const { name, isOptional = false } = kwargs
// Extract options from the input spec
const options = inputSpecV1[1] || {}
// Base properties for all input types
const baseProps = {
name,
isOptional,
...options
}
// Handle different input types
if (isComboInputSpec(inputSpecV1)) {
return {
type: 'COMBO',
...baseProps,
options: isComboInputSpecV1(inputSpecV1)
? inputSpecV1[0]
: getComboSpecComboOptions(inputSpecV1)
}
} else if (typeof inputSpecV1[0] === 'string') {
// Handle standard types (INT, FLOAT, BOOLEAN, STRING) and custom types
return {
type: inputSpecV1[0],
...baseProps
}
}
// Fallback for any unhandled cases
return {
type: 'UNKNOWN',
...baseProps
}
}
export function transformInputSpecV2ToV1(
inputSpecV2: InputSpecV2
): InputSpecV1 {
return [inputSpecV2.type, inputSpecV2]
}

View File

@@ -0,0 +1,264 @@
import { z } from 'zod'
import {
zBaseInputOptions,
zBooleanInputOptions,
zComboInputOptions,
zFloatInputOptions,
zIntInputOptions,
zStringInputOptions
} from '@/schemas/nodeDefSchema'
const zIntInputSpec = zIntInputOptions.extend({
type: z.literal('INT'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zFloatInputSpec = zFloatInputOptions.extend({
type: z.literal('FLOAT'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zBooleanInputSpec = zBooleanInputOptions.extend({
type: z.literal('BOOLEAN'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zStringInputSpec = zStringInputOptions.extend({
type: z.literal('STRING'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zComboInputSpec = zComboInputOptions.extend({
type: z.literal('COMBO'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zColorInputSpec = zBaseInputOptions.extend({
type: z.literal('COLOR'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
default: z.string().optional()
})
.optional()
})
const zFileUploadInputSpec = zBaseInputOptions.extend({
type: z.literal('FILEUPLOAD'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zImageInputSpec = zBaseInputOptions.extend({
type: z.literal('IMAGE'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zImageCompareInputSpec = zBaseInputOptions.extend({
type: z.literal('IMAGECOMPARE'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zMarkdownInputSpec = zBaseInputOptions.extend({
type: z.literal('MARKDOWN'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
content: z.string().optional()
})
.optional()
})
const zTreeSelectInputSpec = zBaseInputOptions.extend({
type: z.literal('TREESELECT'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
multiple: z.boolean().optional(),
values: z.array(z.unknown()).optional()
})
.optional()
})
const zMultiSelectInputSpec = zBaseInputOptions.extend({
type: z.literal('MULTISELECT'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
values: z.array(z.string()).optional()
})
.optional()
})
const zChartInputSpec = zBaseInputOptions.extend({
type: z.literal('CHART'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
type: z.enum(['bar', 'line']).optional(),
data: z.object({}).optional()
})
.optional()
})
const zGalleriaInputSpec = zBaseInputOptions.extend({
type: z.literal('GALLERIA'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
images: z.array(z.string()).optional()
})
.optional()
})
const zSelectButtonInputSpec = zBaseInputOptions.extend({
type: z.literal('SELECTBUTTON'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
values: z.array(z.string()).optional()
})
.optional()
})
const zTextareaInputSpec = zBaseInputOptions.extend({
type: z.literal('TEXTAREA'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
rows: z.number().optional(),
cols: z.number().optional(),
default: z.string().optional()
})
.optional()
})
const zCustomInputSpec = zBaseInputOptions.extend({
type: z.string(),
name: z.string(),
isOptional: z.boolean().optional()
})
const zInputSpec = z.union([
zIntInputSpec,
zFloatInputSpec,
zBooleanInputSpec,
zStringInputSpec,
zComboInputSpec,
zColorInputSpec,
zFileUploadInputSpec,
zImageInputSpec,
zImageCompareInputSpec,
zMarkdownInputSpec,
zTreeSelectInputSpec,
zMultiSelectInputSpec,
zChartInputSpec,
zGalleriaInputSpec,
zSelectButtonInputSpec,
zTextareaInputSpec,
zCustomInputSpec
])
// Output specs
const zOutputSpec = z.object({
index: z.number(),
name: z.string(),
type: z.string(),
is_list: z.boolean(),
options: z.array(z.any()).optional(),
tooltip: z.string().optional()
})
// Main node definition schema
export const zComfyNodeDef = z.object({
inputs: z.record(zInputSpec),
outputs: z.array(zOutputSpec),
hidden: z.record(z.any()).optional(),
name: z.string(),
display_name: z.string(),
description: z.string(),
help: z.string().optional(),
category: z.string(),
output_node: z.boolean(),
python_module: z.string(),
deprecated: z.boolean().optional(),
experimental: z.boolean().optional(),
api_node: z.boolean().optional()
})
// Export types
type IntInputSpec = z.infer<typeof zIntInputSpec>
type FloatInputSpec = z.infer<typeof zFloatInputSpec>
type BooleanInputSpec = z.infer<typeof zBooleanInputSpec>
type StringInputSpec = z.infer<typeof zStringInputSpec>
export type ComboInputSpec = z.infer<typeof zComboInputSpec>
export type ColorInputSpec = z.infer<typeof zColorInputSpec>
export type FileUploadInputSpec = z.infer<typeof zFileUploadInputSpec>
export type ImageCompareInputSpec = z.infer<typeof zImageCompareInputSpec>
export type TreeSelectInputSpec = z.infer<typeof zTreeSelectInputSpec>
export type MultiSelectInputSpec = z.infer<typeof zMultiSelectInputSpec>
export type ChartInputSpec = z.infer<typeof zChartInputSpec>
export type GalleriaInputSpec = z.infer<typeof zGalleriaInputSpec>
export type SelectButtonInputSpec = z.infer<typeof zSelectButtonInputSpec>
export type TextareaInputSpec = z.infer<typeof zTextareaInputSpec>
export type CustomInputSpec = z.infer<typeof zCustomInputSpec>
export type InputSpec = z.infer<typeof zInputSpec>
export type OutputSpec = z.infer<typeof zOutputSpec>
export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
export const isIntInputSpec = (
inputSpec: InputSpec
): inputSpec is IntInputSpec => {
return inputSpec.type === 'INT'
}
export const isFloatInputSpec = (
inputSpec: InputSpec
): inputSpec is FloatInputSpec => {
return inputSpec.type === 'FLOAT'
}
export const isBooleanInputSpec = (
inputSpec: InputSpec
): inputSpec is BooleanInputSpec => {
return inputSpec.type === 'BOOLEAN'
}
export const isStringInputSpec = (
inputSpec: InputSpec
): inputSpec is StringInputSpec => {
return inputSpec.type === 'STRING'
}
export const isComboInputSpec = (
inputSpec: InputSpec
): inputSpec is ComboInputSpec => {
return inputSpec.type === 'COMBO'
}
export const isChartInputSpec = (
inputSpec: InputSpec
): inputSpec is ChartInputSpec => {
return inputSpec.type === 'CHART'
}

View File

@@ -0,0 +1,255 @@
import { z } from 'zod'
import { fromZodError } from 'zod-validation-error'
import { resultItemType } from '@/schemas/apiSchema'
const zComboOption = z.union([z.string(), z.number()])
const zRemoteWidgetConfig = z.object({
route: z.string().url().or(z.string().startsWith('/')),
refresh: z.number().gte(128).safe().or(z.number().lte(0).safe()).optional(),
response_key: z.string().optional(),
query_params: z.record(z.string(), z.string()).optional(),
refresh_button: z.boolean().optional(),
control_after_refresh: z.enum(['first', 'last']).optional(),
timeout: z.number().gte(0).optional(),
max_retries: z.number().gte(0).optional()
})
const zMultiSelectOption = z.object({
placeholder: z.string().optional(),
chip: z.boolean().optional()
})
export const zBaseInputOptions = z
.object({
default: z.any().optional(),
defaultInput: z.boolean().optional(),
forceInput: z.boolean().optional(),
tooltip: z.string().optional(),
hidden: z.boolean().optional(),
advanced: z.boolean().optional(),
widgetType: z.string().optional(),
/** Backend-only properties. */
rawLink: z.boolean().optional(),
lazy: z.boolean().optional()
})
.passthrough()
const zNumericInputOptions = zBaseInputOptions.extend({
min: z.number().optional(),
max: z.number().optional(),
step: z.number().optional(),
/** Note: Many node authors are using INT/FLOAT to pass list of INT/FLOAT. */
default: z.union([z.number(), z.array(z.number())]).optional(),
display: z.enum(['slider', 'number', 'knob']).optional()
})
export const zIntInputOptions = zNumericInputOptions.extend({
/**
* If true, a linked widget will be added to the node to select the mode
* of `control_after_generate`.
*/
control_after_generate: z.boolean().optional()
})
export const zFloatInputOptions = zNumericInputOptions.extend({
round: z.union([z.number(), z.literal(false)]).optional()
})
export const zBooleanInputOptions = zBaseInputOptions.extend({
label_on: z.string().optional(),
label_off: z.string().optional(),
default: z.boolean().optional()
})
export const zStringInputOptions = zBaseInputOptions.extend({
default: z.string().optional(),
multiline: z.boolean().optional(),
dynamicPrompts: z.boolean().optional(),
// Multiline-only fields
defaultVal: z.string().optional(),
placeholder: z.string().optional()
})
export const zComboInputOptions = zBaseInputOptions.extend({
control_after_generate: z.boolean().optional(),
image_upload: z.boolean().optional(),
image_folder: resultItemType.optional(),
allow_batch: z.boolean().optional(),
video_upload: z.boolean().optional(),
audio_upload: z.boolean().optional(),
animated_image_upload: z.boolean().optional(),
options: z.array(zComboOption).optional(),
remote: zRemoteWidgetConfig.optional(),
/** Whether the widget is a multi-select widget. */
multi_select: zMultiSelectOption.optional()
})
const zIntInputSpec = z.tuple([z.literal('INT'), zIntInputOptions.optional()])
const zFloatInputSpec = z.tuple([
z.literal('FLOAT'),
zFloatInputOptions.optional()
])
const zBooleanInputSpec = z.tuple([
z.literal('BOOLEAN'),
zBooleanInputOptions.optional()
])
const zStringInputSpec = z.tuple([
z.literal('STRING'),
zStringInputOptions.optional()
])
/**
* Legacy combo syntax.
* @deprecated Use `zComboInputSpecV2` instead.
*/
const zComboInputSpec = z.tuple([
z.array(zComboOption),
zComboInputOptions.optional()
])
const zComboInputSpecV2 = z.tuple([
z.literal('COMBO'),
zComboInputOptions.optional()
])
export function isComboInputSpecV1(
inputSpec: InputSpec
): inputSpec is ComboInputSpec {
return Array.isArray(inputSpec[0])
}
export function isIntInputSpec(
inputSpec: InputSpec
): inputSpec is IntInputSpec {
return inputSpec[0] === 'INT'
}
export function isFloatInputSpec(
inputSpec: InputSpec
): inputSpec is FloatInputSpec {
return inputSpec[0] === 'FLOAT'
}
export function isComboInputSpecV2(
inputSpec: InputSpec
): inputSpec is ComboInputSpecV2 {
return inputSpec[0] === 'COMBO'
}
export function isComboInputSpec(
inputSpec: InputSpec
): inputSpec is ComboInputSpec | ComboInputSpecV2 {
return isComboInputSpecV1(inputSpec) || isComboInputSpecV2(inputSpec)
}
/**
* Get the type of an input spec.
*
* @param inputSpec - The input spec to get the type of.
* @returns The type of the input spec.
*/
export function getInputSpecType(inputSpec: InputSpec): string {
return isComboInputSpec(inputSpec) ? 'COMBO' : inputSpec[0]
}
/**
* Get the combo options from a combo input spec.
*
* @param inputSpec - The input spec to get the combo options from.
* @returns The combo options.
*/
export function getComboSpecComboOptions(
inputSpec: ComboInputSpec | ComboInputSpecV2
): (number | string)[] {
return (
(isComboInputSpecV2(inputSpec) ? inputSpec[1]?.options : inputSpec[0]) ?? []
)
}
const excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])
const zCustomInputSpec = z.tuple([
z.string().refine((value) => !excludedLiterals.has(value)),
zBaseInputOptions.optional()
])
const zInputSpec = z.union([
zIntInputSpec,
zFloatInputSpec,
zBooleanInputSpec,
zStringInputSpec,
zComboInputSpec,
zComboInputSpecV2,
zCustomInputSpec
])
const zComfyInputsSpec = z.object({
required: z.record(zInputSpec).optional(),
optional: z.record(zInputSpec).optional(),
// Frontend repo is not using it, but some custom nodes are using the
// hidden field to pass various values.
hidden: z.record(z.any()).optional()
})
const zComfyNodeDataType = z.string()
const zComfyComboOutput = z.array(zComboOption)
const zComfyOutputTypesSpec = z.array(
z.union([zComfyNodeDataType, zComfyComboOutput])
)
export const zComfyNodeDef = z.object({
input: zComfyInputsSpec.optional(),
output: zComfyOutputTypesSpec.optional(),
output_is_list: z.array(z.boolean()).optional(),
output_name: z.array(z.string()).optional(),
output_tooltips: z.array(z.string()).optional(),
name: z.string(),
display_name: z.string(),
description: z.string(),
help: z.string().optional(),
category: z.string(),
output_node: z.boolean(),
python_module: z.string(),
deprecated: z.boolean().optional(),
experimental: z.boolean().optional(),
/**
* Whether the node is an API node. Running API nodes requires login to
* Comfy Org account.
* https://docs.comfy.org/tutorials/api-nodes/overview
*/
api_node: z.boolean().optional(),
/**
* Specifies the order of inputs for each input category.
* Used to ensure consistent widget ordering regardless of JSON serialization.
* Keys are 'required', 'optional', etc., values are arrays of input names.
*/
input_order: z.record(z.array(z.string())).optional()
})
// `/object_info`
export type ComfyInputsSpec = z.infer<typeof zComfyInputsSpec>
export type ComfyOutputTypesSpec = z.infer<typeof zComfyOutputTypesSpec>
export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
export type RemoteWidgetConfig = z.infer<typeof zRemoteWidgetConfig>
export type ComboInputOptions = z.infer<typeof zComboInputOptions>
export type NumericInputOptions = z.infer<typeof zNumericInputOptions>
export type IntInputSpec = z.infer<typeof zIntInputSpec>
export type FloatInputSpec = z.infer<typeof zFloatInputSpec>
export type ComboInputSpec = z.infer<typeof zComboInputSpec>
export type ComboInputSpecV2 = z.infer<typeof zComboInputSpecV2>
export type InputSpec = z.infer<typeof zInputSpec>
export function validateComfyNodeDef(
data: any,
onError: (error: string) => void = console.warn
): ComfyNodeDef | null {
const result = zComfyNodeDef.safeParse(data)
if (!result.success) {
const zodError = fromZodError(result.error)
onError(
`Invalid ComfyNodeDef: ${JSON.stringify(data)}\n${zodError.message}`
)
return null
}
return result.data
}

View File

@@ -0,0 +1,60 @@
import { z } from 'zod'
import { t } from '@/i18n'
export const apiKeySchema = z.object({
apiKey: z
.string()
.trim()
.startsWith('comfyui-', t('validation.prefix', { prefix: 'comfyui-' }))
.length(72, t('validation.length', { length: 72 }))
})
export const signInSchema = z.object({
email: z
.string()
.email(t('validation.invalidEmail'))
.min(1, t('validation.required')),
password: z.string().min(1, t('validation.required'))
})
export type SignInData = z.infer<typeof signInSchema>
const passwordSchema = z.object({
password: z
.string()
.min(8, t('validation.minLength', { length: 8 }))
.max(32, t('validation.maxLength', { length: 32 }))
.regex(/[A-Z]/, t('validation.password.uppercase'))
.regex(/[a-z]/, t('validation.password.lowercase'))
.regex(/\d/, t('validation.password.number'))
.regex(/[^A-Za-z0-9]/, t('validation.password.special')),
confirmPassword: z.string().min(1, t('validation.required'))
})
export const updatePasswordSchema = passwordSchema.refine(
(data) => data.password === data.confirmPassword,
{
message: t('validation.password.match'),
path: ['confirmPassword']
}
)
export const signUpSchema = passwordSchema
.extend({
email: z
.string()
.email(t('validation.invalidEmail'))
.min(1, t('validation.required')),
personalDataConsent: z.boolean()
})
.refine((data) => data.password === data.confirmPassword, {
message: t('validation.password.match'),
path: ['confirmPassword']
})
.refine((data) => data.personalDataConsent === true, {
message: t('validation.personalDataConsentRequired'),
path: ['personalDataConsent']
})
export type SignUpData = z.infer<typeof signUpSchema>

View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src/**/*"]
}

16
pnpm-lock.yaml generated
View File

@@ -20,6 +20,9 @@ importers:
'@comfyorg/design-system':
specifier: workspace:*
version: link:packages/design-system
'@comfyorg/schemas':
specifier: workspace:*
version: link:packages/schemas
'@comfyorg/tailwind-utils':
specifier: workspace:*
version: link:packages/tailwind-utils
@@ -368,6 +371,19 @@ importers:
specifier: ^5.4.5
version: 5.9.2
packages/schemas:
dependencies:
zod:
specifier: ^3.23.8
version: 3.24.1
zod-validation-error:
specifier: ^3.3.0
version: 3.3.0(zod@3.24.1)
devDependencies:
typescript:
specifier: ^5.4.5
version: 5.9.2
packages/tailwind-utils:
dependencies:
clsx:

View File

@@ -314,19 +314,9 @@ const hasActiveStateSiblings = (item: MenuItem): boolean => {
.comfy-command-menu ul {
background-color: var(--comfy-menu-secondary-bg) !important;
}
.comfy-command-menu-top .p-tieredmenu-submenu {
left: calc(100% + 15px) !important;
top: -4px !important;
}
@media (max-height: 700px) {
.comfy-command-menu .p-tieredmenu-submenu {
@apply absolute max-h-[90vh] overflow-y-auto;
}
/* Help (last) submenu upward offset in compact mode */
.p-tieredmenu-root-list
> .p-tieredmenu-item:last-of-type
.p-tieredmenu-submenu {
top: -188px !important;
}
}
</style>

View File

@@ -39,7 +39,6 @@ export interface VueNodeData {
hasErrors?: boolean
flags?: {
collapsed?: boolean
pinned?: boolean
}
}
@@ -435,15 +434,6 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
}
})
break
case 'flags.pinned':
vueNodeData.set(nodeId, {
...currentData,
flags: {
...currentData.flags,
pinned: Boolean(event.newValue)
}
})
break
case 'mode':
vueNodeData.set(nodeId, {
...currentData,

View File

@@ -25,8 +25,6 @@ import {
useCanvasStore,
useTitleEditorStore
} from '@/renderer/core/canvas/canvasStore'
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
import { selectionBounds } from '@/renderer/core/layout/utils/layoutMath'
import { api } from '@/scripts/api'
import { app } from '@/scripts/app'
import { useDialogService } from '@/services/dialogService'
@@ -318,53 +316,15 @@ export function useCoreCommands(): ComfyCommand[] {
menubarLabel: 'Zoom to fit',
category: 'view-controls' as const,
function: () => {
const vueNodesEnabled = useSettingStore().get('Comfy.VueNodes.Enabled')
if (vueNodesEnabled) {
// Get nodes from Vue stores
const canvasStore = useCanvasStore()
const selectedNodeIds = canvasStore.selectedNodeIds
const allNodes = layoutStore.getAllNodes().value
// Get nodes to fit - selected if any, otherwise all
const nodesToFit =
selectedNodeIds.size > 0
? Array.from(selectedNodeIds)
.map((id) => allNodes.get(id))
.filter((node) => node != null)
: Array.from(allNodes.values())
// Use Vue nodes bounds calculation
const bounds = selectionBounds(nodesToFit)
if (!bounds) {
toastStore.add({
severity: 'error',
summary: t('toastMessages.emptyCanvas'),
life: 3000
})
return
}
// Convert to LiteGraph format and animate
const lgBounds = [
bounds.x,
bounds.y,
bounds.width,
bounds.height
] as const
const setDirty = () => app.canvas.setDirty(true, true)
app.canvas.ds.animateToBounds(lgBounds, setDirty)
} else {
if (app.canvas.empty) {
toastStore.add({
severity: 'error',
summary: t('toastMessages.emptyCanvas'),
life: 3000
})
return
}
app.canvas.fitViewToSelectionAnimated()
if (app.canvas.empty) {
toastStore.add({
severity: 'error',
summary: t('toastMessages.emptyCanvas'),
life: 3000
})
return
}
app.canvas.fitViewToSelectionAnimated()
}
},
{

View File

@@ -688,8 +688,8 @@ export class LGraphCanvas
/** If true, enable drag zoom. Ctrl+Shift+Drag Up/Down: zoom canvas. */
dragZoomEnabled: boolean = false
/** The start position of the drag zoom and original read-only state. */
#dragZoomStart: { pos: Point; scale: number; readOnly: boolean } | null = null
/** The start position of the drag zoom. */
#dragZoomStart: { pos: Point; scale: number } | null = null
getMenuOptions?(): IContextMenuValue<string>[]
getExtraMenuOptions?(
@@ -2188,12 +2188,7 @@ export class LGraphCanvas
!e.altKey &&
e.buttons
) {
this.#dragZoomStart = {
pos: [e.x, e.y],
scale: this.ds.scale,
readOnly: this.read_only
}
this.read_only = true
this.#dragZoomStart = { pos: [e.x, e.y], scale: this.ds.scale }
return
}
@@ -3130,7 +3125,7 @@ export class LGraphCanvas
#processDragZoom(e: PointerEvent): void {
// stop canvas zoom action
if (!e.buttons) {
this.#finishDragZoom()
this.#dragZoomStart = null
return
}
@@ -3148,13 +3143,6 @@ export class LGraphCanvas
this.graph.change()
}
#finishDragZoom(): void {
const start = this.#dragZoomStart
if (!start) return
this.#dragZoomStart = null
this.read_only = start.readOnly
}
/**
* Called when a mouse move event has to be processed
*/
@@ -3536,8 +3524,6 @@ export class LGraphCanvas
const { graph, pointer } = this
if (!graph) return
this.#finishDragZoom()
LGraphCanvas.active_canvas = this
this.adjustMouseEvent(e)

View File

@@ -3398,7 +3398,9 @@ export class LGraphNode
this.graph._version++
this.flags.pinned = v ?? !this.flags.pinned
this.resizable = !this.pinned
if (!this.pinned) this.flags.pinned = undefined
// Delete the flag if unpinned, so that we don't get unnecessary
// flags.pinned = false in serialized object.
if (!this.pinned) delete this.flags.pinned
}
unpin(): void {

View File

@@ -6,7 +6,6 @@ import type { LGraphNode } from './LGraphNode'
const DEFAULT_TRACKED_PROPERTIES: string[] = [
'title',
'flags.collapsed',
'flags.pinned',
'mode'
]

View File

@@ -6,7 +6,8 @@ import { app } from '@/scripts/app'
/**
* Composable for handling canvas interactions from Vue components.
* This provides a unified way to forward events to the LiteGraph canvas.
* This provides a unified way to forward events to the LiteGraph canvas
* and will be the foundation for migrating canvas interactions to Vue.
*/
export function useCanvasInteractions() {
const settingStore = useSettingStore()

View File

@@ -1,4 +1,4 @@
import type { Bounds, NodeLayout, Point } from '@/renderer/core/layout/types'
import type { Bounds, Point } from '@/renderer/core/layout/types'
export const REROUTE_RADIUS = 8
@@ -19,35 +19,3 @@ export function boundsIntersect(a: Bounds, b: Bounds): boolean {
b.y + b.height < a.y
)
}
export function calculateBounds(nodes: NodeLayout[]): Bounds {
let minX = Infinity,
minY = Infinity
let maxX = -Infinity,
maxY = -Infinity
for (const node of nodes) {
const bounds = node.bounds
minX = Math.min(minX, bounds.x)
minY = Math.min(minY, bounds.y)
maxX = Math.max(maxX, bounds.x + bounds.width)
maxY = Math.max(maxY, bounds.y + bounds.height)
}
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY
}
}
/**
* Calculate combined bounds for Vue nodes selection
* @param nodes Array of NodeLayout objects to calculate bounds for
* @returns Bounds of the nodes or null if no nodes provided
*/
export function selectionBounds(nodes: NodeLayout[]): Bounds | null {
if (nodes.length === 0) return null
return calculateBounds(nodes)
}

View File

@@ -49,7 +49,7 @@
</template>
<!-- Header only updates on title/color changes -->
<NodeHeader
v-memo="[nodeData.title, isCollapsed, nodeData.flags?.pinned]"
v-memo="[nodeData.title, isCollapsed]"
:node-data="nodeData"
:readonly="readonly"
:collapsed="isCollapsed"

View File

@@ -1,5 +1,3 @@
<template>
<div
class="lod-fallback absolute inset-0 w-full h-full bg-zinc-300 dark-theme:bg-zinc-800"
></div>
<div class="lod-fallback absolute inset-0 w-full h-full bg-zinc-800"></div>
</template>

View File

@@ -26,7 +26,7 @@
<!-- Node Title -->
<div
v-tooltip.top="tooltipConfig"
class="text-sm font-bold truncate flex-1 lod-toggle flex items-center gap-2"
class="text-sm font-bold truncate flex-1 lod-toggle"
data-testid="node-title"
>
<EditableText
@@ -36,11 +36,6 @@
@edit="handleTitleEdit"
@cancel="handleTitleCancel"
/>
<i-lucide:pin
v-if="isPinned"
class="w-5 h-5 text-stone-200 dark-theme:text-slate-300"
data-testid="node-pin-indicator"
/>
</div>
<LODFallback />
</div>
@@ -146,8 +141,6 @@ watch(
}
)
const isPinned = computed(() => Boolean(nodeData?.flags?.pinned))
// Subgraph detection
const isSubgraphNode = computed(() => {
if (!nodeData?.id) return false

View File

@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick, ref } from 'vue'
import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
@@ -67,14 +67,20 @@ const createMouseEvent = (
}
describe('useNodePointerInteractions', () => {
let mockNodeData: VueNodeData
let mockOnPointerUp: ReturnType<typeof vi.fn>
beforeEach(() => {
mockNodeData = createMockVueNodeData()
mockOnPointerUp = vi.fn()
vi.clearAllMocks()
})
it('should only start drag on left-click', async () => {
const mockNodeData = createMockVueNodeData()
const mockOnPointerUp = vi.fn()
afterEach(() => {
vi.restoreAllMocks()
})
it('should only start drag on left-click', async () => {
const { pointerHandlers } = useNodePointerInteractions(
ref(mockNodeData),
mockOnPointerUp
@@ -83,15 +89,18 @@ describe('useNodePointerInteractions', () => {
// Right-click should not start drag
const rightClickEvent = createPointerEvent('pointerdown', { button: 2 })
pointerHandlers.onPointerdown(rightClickEvent)
await nextTick()
expect(mockOnPointerUp).not.toHaveBeenCalled()
// Left-click should start drag and emit callback
const leftClickEvent = createPointerEvent('pointerdown', { button: 0 })
pointerHandlers.onPointerdown(leftClickEvent)
await nextTick()
const pointerUpEvent = createPointerEvent('pointerup')
pointerHandlers.onPointerup(pointerUpEvent)
await nextTick()
expect(mockOnPointerUp).toHaveBeenCalledWith(
pointerUpEvent,
@@ -101,9 +110,6 @@ describe('useNodePointerInteractions', () => {
})
it('should distinguish drag from click based on distance threshold', async () => {
const mockNodeData = createMockVueNodeData()
const mockOnPointerUp = vi.fn()
const { pointerHandlers } = useNodePointerInteractions(
ref(mockNodeData),
mockOnPointerUp
@@ -113,12 +119,14 @@ describe('useNodePointerInteractions', () => {
pointerHandlers.onPointerdown(
createPointerEvent('pointerdown', { clientX: 100, clientY: 100 })
)
await nextTick()
const dragUpEvent = createPointerEvent('pointerup', {
clientX: 200,
clientY: 200
})
pointerHandlers.onPointerup(dragUpEvent)
await nextTick()
expect(mockOnPointerUp).toHaveBeenCalledWith(
dragUpEvent,
@@ -131,9 +139,11 @@ describe('useNodePointerInteractions', () => {
// Test click (same position)
const samePos = { clientX: 100, clientY: 100 }
pointerHandlers.onPointerdown(createPointerEvent('pointerdown', samePos))
await nextTick()
const clickUpEvent = createPointerEvent('pointerup', samePos)
pointerHandlers.onPointerup(clickUpEvent)
await nextTick()
expect(mockOnPointerUp).toHaveBeenCalledWith(
clickUpEvent,
@@ -143,9 +153,6 @@ describe('useNodePointerInteractions', () => {
})
it('should handle drag termination via cancel and context menu', async () => {
const mockNodeData = createMockVueNodeData()
const mockOnPointerUp = vi.fn()
const { pointerHandlers } = useNodePointerInteractions(
ref(mockNodeData),
mockOnPointerUp
@@ -153,49 +160,50 @@ describe('useNodePointerInteractions', () => {
// Test pointer cancel
pointerHandlers.onPointerdown(createPointerEvent('pointerdown'))
await nextTick()
pointerHandlers.onPointercancel(createPointerEvent('pointercancel'))
await nextTick()
// Should not emit callback on cancel
expect(mockOnPointerUp).not.toHaveBeenCalled()
// Test context menu during drag prevents default
pointerHandlers.onPointerdown(createPointerEvent('pointerdown'))
await nextTick()
const contextMenuEvent = createMouseEvent('contextmenu')
const preventDefaultSpy = vi.spyOn(contextMenuEvent, 'preventDefault')
pointerHandlers.onContextmenu(contextMenuEvent)
await nextTick()
expect(preventDefaultSpy).toHaveBeenCalled()
})
it('should not emit callback when nodeData becomes null', async () => {
const mockNodeData = createMockVueNodeData()
const mockOnPointerUp = vi.fn()
const nodeDataRef = ref<VueNodeData | null>(mockNodeData)
const { pointerHandlers } = useNodePointerInteractions(
nodeDataRef,
mockOnPointerUp
)
pointerHandlers.onPointerdown(createPointerEvent('pointerdown'))
await nextTick()
// Clear nodeData before pointerup
nodeDataRef.value = null
await nextTick()
pointerHandlers.onPointerup(createPointerEvent('pointerup'))
await nextTick()
expect(mockOnPointerUp).not.toHaveBeenCalled()
})
it('should integrate with layout store dragging state', async () => {
const mockNodeData = createMockVueNodeData()
const mockOnPointerUp = vi.fn()
const { layoutStore } = await import(
'@/renderer/core/layout/store/layoutStore'
)
const { pointerHandlers } = useNodePointerInteractions(
ref(mockNodeData),
mockOnPointerUp

View File

@@ -36,12 +36,9 @@ export function useNodePointerInteractions(
// Drag state for styling
const isDragging = ref(false)
const dragStyle = computed(() => {
if (nodeData.value?.flags?.pinned) {
return { cursor: 'default' }
}
return { cursor: isDragging.value ? 'grabbing' : 'grab' }
})
const dragStyle = computed(() => ({
cursor: isDragging.value ? 'grabbing' : 'grab'
}))
const startPosition = ref({ x: 0, y: 0 })
const handlePointerDown = (event: PointerEvent) => {
@@ -63,12 +60,6 @@ export function useNodePointerInteractions(
return
}
// Don't allow dragging if node is pinned (but still record position for selection)
startPosition.value = { x: event.clientX, y: event.clientY }
if (nodeData.value.flags?.pinned) {
return
}
// Start drag using layout system
isDragging.value = true
@@ -76,6 +67,7 @@ export function useNodePointerInteractions(
layoutStore.isDraggingVueNodes.value = true
startDrag(event)
startPosition.value = { x: event.clientX, y: event.clientY }
}
const handlePointerMove = (event: PointerEvent) => {

View File

@@ -206,148 +206,3 @@ describe('WidgetInputNumberInput Grouping Behavior', () => {
expect(input.value).not.toContain(',')
})
})
describe('WidgetInputNumberInput Large Integer Precision Handling', () => {
const SAFE_INTEGER_MAX = Number.MAX_SAFE_INTEGER // 9,007,199,254,740,991
const UNSAFE_LARGE_INTEGER = 18446744073709552000 // Example seed value that exceeds safe range
it('shows buttons for safe integer values', () => {
const widget = createMockWidget(1000, 'int')
const wrapper = mountComponent(widget, 1000)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(true)
})
it('shows buttons for values at safe integer limit', () => {
const widget = createMockWidget(SAFE_INTEGER_MAX, 'int')
const wrapper = mountComponent(widget, SAFE_INTEGER_MAX)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(true)
})
it('hides buttons for unsafe large integer values', () => {
const widget = createMockWidget(UNSAFE_LARGE_INTEGER, 'int')
const wrapper = mountComponent(widget, UNSAFE_LARGE_INTEGER)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(false)
})
it('hides buttons for unsafe negative integer values', () => {
const unsafeNegative = -UNSAFE_LARGE_INTEGER
const widget = createMockWidget(unsafeNegative, 'int')
const wrapper = mountComponent(widget, unsafeNegative)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(false)
})
it('shows tooltip for disabled buttons due to precision limits', () => {
const widget = createMockWidget(UNSAFE_LARGE_INTEGER, 'int')
const wrapper = mountComponent(widget, UNSAFE_LARGE_INTEGER)
// Check that tooltip wrapper div exists
const tooltipDiv = wrapper.find('div[v-tooltip]')
expect(tooltipDiv.exists()).toBe(true)
})
it('does not show tooltip for safe integer values', () => {
const widget = createMockWidget(1000, 'int')
const wrapper = mountComponent(widget, 1000)
// For safe values, tooltip should not be set (computed returns null)
const tooltipDiv = wrapper.find('div')
expect(tooltipDiv.attributes('v-tooltip')).toBeUndefined()
})
it('handles edge case of zero value', () => {
const widget = createMockWidget(0, 'int')
const wrapper = mountComponent(widget, 0)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(true)
})
it('correctly identifies safe vs unsafe integers using Number.isSafeInteger', () => {
// Test the JavaScript behavior our component relies on
expect(Number.isSafeInteger(SAFE_INTEGER_MAX)).toBe(true)
expect(Number.isSafeInteger(SAFE_INTEGER_MAX + 1)).toBe(false)
expect(Number.isSafeInteger(UNSAFE_LARGE_INTEGER)).toBe(false)
expect(Number.isSafeInteger(-SAFE_INTEGER_MAX)).toBe(true)
expect(Number.isSafeInteger(-SAFE_INTEGER_MAX - 1)).toBe(false)
})
it('maintains readonly behavior even for unsafe values', () => {
const widget = createMockWidget(UNSAFE_LARGE_INTEGER, 'int')
const wrapper = mountComponent(widget, UNSAFE_LARGE_INTEGER, true)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('disabled')).toBe(true)
expect(inputNumber.props('showButtons')).toBe(false) // Still hidden due to unsafe value
})
it('handles floating point values correctly', () => {
const safeFloat = 1000.5
const widget = createMockWidget(safeFloat, 'float')
const wrapper = mountComponent(widget, safeFloat)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(true)
})
it('hides buttons for unsafe floating point values', () => {
const unsafeFloat = UNSAFE_LARGE_INTEGER + 0.5
const widget = createMockWidget(unsafeFloat, 'float')
const wrapper = mountComponent(widget, unsafeFloat)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(false)
})
})
describe('WidgetInputNumberInput Edge Cases for Precision Handling', () => {
it('handles null/undefined model values gracefully', () => {
const widget = createMockWidget(0, 'int')
// Mount with undefined as modelValue
const wrapper = mount(WidgetInputNumberInput, {
global: {
plugins: [PrimeVue],
components: { InputNumber }
},
props: {
widget,
modelValue: undefined as any
}
})
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(true) // Should default to safe behavior
})
it('handles NaN values gracefully', () => {
const widget = createMockWidget(NaN, 'int')
const wrapper = mountComponent(widget, NaN)
const inputNumber = wrapper.findComponent(InputNumber)
// NaN is not a safe integer, so buttons should be hidden
expect(inputNumber.props('showButtons')).toBe(false)
})
it('handles Infinity values', () => {
const widget = createMockWidget(Infinity, 'int')
const wrapper = mountComponent(widget, Infinity)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(false)
})
it('handles negative Infinity values', () => {
const widget = createMockWidget(-Infinity, 'int')
const wrapper = mountComponent(widget, -Infinity)
const inputNumber = wrapper.findComponent(InputNumber)
expect(inputNumber.props('showButtons')).toBe(false)
})
})

View File

@@ -2,7 +2,6 @@
import InputNumber from 'primevue/inputnumber'
import { computed } from 'vue'
import { useNumberWidgetValue } from '@/composables/graph/useWidgetValue'
import type { SimplifiedWidget } from '@/types/simplifiedWidget'
import { cn } from '@/utils/tailwindUtil'
import {
@@ -15,19 +14,10 @@ import WidgetLayoutField from './layout/WidgetLayoutField.vue'
const props = defineProps<{
widget: SimplifiedWidget<number>
modelValue: number
readonly?: boolean
}>()
const emit = defineEmits<{
'update:modelValue': [value: number]
}>()
const { localValue, onChange } = useNumberWidgetValue(
props.widget,
props.modelValue,
emit
)
const modelValue = defineModel<number>({ default: 0 })
const filteredProps = computed(() =>
filterWidgetProps(props.widget.options, INPUT_EXCLUDED_PROPS)
@@ -63,52 +53,34 @@ const stepValue = computed(() => {
const useGrouping = computed(() => {
return props.widget.options?.useGrouping === true
})
// Check if increment/decrement buttons should be disabled due to precision limits
const buttonsDisabled = computed(() => {
const currentValue = localValue.value || 0
return !Number.isSafeInteger(currentValue)
})
// Tooltip message for disabled buttons
const buttonTooltip = computed(() => {
if (props.readonly) return null
if (buttonsDisabled.value) {
return 'Increment/decrement disabled: value exceeds JavaScript precision limit (±2^53)'
}
return null
})
</script>
<template>
<WidgetLayoutField :widget>
<div v-tooltip="buttonTooltip">
<InputNumber
v-model="localValue"
v-bind="filteredProps"
:show-buttons="!buttonsDisabled"
button-layout="horizontal"
size="small"
:disabled="readonly"
:step="stepValue"
:use-grouping="useGrouping"
:class="cn(WidgetInputBaseClass, 'w-full text-xs')"
:pt="{
incrementButton:
'!rounded-r-lg bg-transparent border-none hover:bg-zinc-500/30 active:bg-zinc-500/40',
decrementButton:
'!rounded-l-lg bg-transparent border-none hover:bg-zinc-500/30 active:bg-zinc-500/40'
}"
@update:model-value="onChange"
>
<template #incrementicon>
<span class="pi pi-plus text-sm" />
</template>
<template #decrementicon>
<span class="pi pi-minus text-sm" />
</template>
</InputNumber>
</div>
<InputNumber
v-model="modelValue"
v-bind="filteredProps"
show-buttons
button-layout="horizontal"
size="small"
:disabled="readonly"
:step="stepValue"
:use-grouping="useGrouping"
:class="cn(WidgetInputBaseClass, 'w-full text-xs')"
:pt="{
incrementButton:
'!rounded-r-lg bg-transparent border-none hover:bg-zinc-500/30 active:bg-zinc-500/40',
decrementButton:
'!rounded-l-lg bg-transparent border-none hover:bg-zinc-500/30 active:bg-zinc-500/40'
}"
>
<template #incrementicon>
<span class="pi pi-plus text-sm" />
</template>
<template #decrementicon>
<span class="pi pi-minus text-sm" />
</template>
</InputNumber>
</WidgetLayoutField>
</template>

View File

@@ -5,7 +5,7 @@
:options="selectOptions"
v-bind="combinedProps"
:disabled="readonly"
:class="cn(WidgetInputBaseClass, 'w-full text-xs')"
class="w-full text-xs bg-[#F9F8F4] dark-theme:bg-[#0E0E12] border-[#E1DED5] dark-theme:border-[#15161C] !rounded-lg"
size="small"
:pt="{
option: 'text-xs'
@@ -22,13 +22,11 @@ import { computed } from 'vue'
import { useWidgetValue } from '@/composables/graph/useWidgetValue'
import { useTransformCompatOverlayProps } from '@/composables/useTransformCompatOverlayProps'
import type { SimplifiedWidget } from '@/types/simplifiedWidget'
import { cn } from '@/utils/tailwindUtil'
import {
PANEL_EXCLUDED_PROPS,
filterWidgetProps
} from '@/utils/widgetPropFilter'
import { WidgetInputBaseClass } from './layout'
import WidgetLayoutField from './layout/WidgetLayoutField.vue'
const props = defineProps<{

View File

@@ -1,526 +1 @@
import { z } from 'zod'
import { LinkMarkerShape } from '@/lib/litegraph/src/litegraph'
import {
zComfyWorkflow,
zNodeId
} from '@/platform/workflow/validation/schemas/workflowSchema'
import { colorPalettesSchema } from '@/schemas/colorPaletteSchema'
import { zKeybinding } from '@/schemas/keyBindingSchema'
import { NodeBadgeMode } from '@/types/nodeSource'
import { LinkReleaseTriggerAction } from '@/types/searchBoxTypes'
const zNodeType = z.string()
const zQueueIndex = z.number()
const zPromptId = z.string()
export const resultItemType = z.enum(['input', 'output', 'temp'])
export type ResultItemType = z.infer<typeof resultItemType>
const zResultItem = z.object({
filename: z.string().optional(),
subfolder: z.string().optional(),
type: resultItemType.optional()
})
export type ResultItem = z.infer<typeof zResultItem>
const zOutputs = z
.object({
audio: z.array(zResultItem).optional(),
images: z.array(zResultItem).optional(),
video: z.array(zResultItem).optional(),
animated: z.array(z.boolean()).optional()
})
.passthrough()
// WS messages
const zStatusWsMessageStatus = z.object({
exec_info: z.object({
queue_remaining: z.number().int()
})
})
const zStatusWsMessage = z.object({
status: zStatusWsMessageStatus.nullish(),
sid: z.string().nullish()
})
const zProgressWsMessage = z.object({
value: z.number().int(),
max: z.number().int(),
prompt_id: zPromptId,
node: zNodeId
})
const zNodeProgressState = z.object({
value: z.number(),
max: z.number(),
state: z.enum(['pending', 'running', 'finished', 'error']),
node_id: zNodeId,
prompt_id: zPromptId,
display_node_id: zNodeId.optional(),
parent_node_id: zNodeId.optional(),
real_node_id: zNodeId.optional()
})
const zProgressStateWsMessage = z.object({
prompt_id: zPromptId,
nodes: z.record(zNodeId, zNodeProgressState)
})
const zExecutingWsMessage = z.object({
node: zNodeId,
display_node: zNodeId,
prompt_id: zPromptId
})
const zExecutedWsMessage = zExecutingWsMessage.extend({
output: zOutputs,
merge: z.boolean().optional()
})
const zExecutionWsMessageBase = z.object({
prompt_id: zPromptId,
timestamp: z.number().int()
})
const zExecutionStartWsMessage = zExecutionWsMessageBase
const zExecutionSuccessWsMessage = zExecutionWsMessageBase
const zExecutionCachedWsMessage = zExecutionWsMessageBase.extend({
nodes: z.array(zNodeId)
})
const zExecutionInterruptedWsMessage = zExecutionWsMessageBase.extend({
node_id: zNodeId,
node_type: zNodeType,
executed: z.array(zNodeId)
})
const zExecutionErrorWsMessage = zExecutionWsMessageBase.extend({
node_id: zNodeId,
node_type: zNodeType,
executed: z.array(zNodeId),
exception_message: z.string(),
exception_type: z.string(),
traceback: z.array(z.string()),
current_inputs: z.any(),
current_outputs: z.any()
})
const zProgressTextWsMessage = z.object({
nodeId: zNodeId,
text: z.string()
})
const zDisplayComponentWsMessage = z.object({
node_id: zNodeId,
component: z.enum(['ChatHistoryWidget']),
props: z.record(z.string(), z.any()).optional()
})
const zTerminalSize = z.object({
cols: z.number(),
row: z.number()
})
const zLogEntry = z.object({
t: z.string(),
m: z.string()
})
const zLogsWsMessage = z.object({
size: zTerminalSize.optional(),
entries: z.array(zLogEntry)
})
const zLogRawResponse = z.object({
size: zTerminalSize,
entries: z.array(zLogEntry)
})
const zFeatureFlagsWsMessage = z.record(z.string(), z.any())
export type StatusWsMessageStatus = z.infer<typeof zStatusWsMessageStatus>
export type StatusWsMessage = z.infer<typeof zStatusWsMessage>
export type ProgressWsMessage = z.infer<typeof zProgressWsMessage>
export type ExecutingWsMessage = z.infer<typeof zExecutingWsMessage>
export type ExecutedWsMessage = z.infer<typeof zExecutedWsMessage>
export type ExecutionStartWsMessage = z.infer<typeof zExecutionStartWsMessage>
export type ExecutionSuccessWsMessage = z.infer<
typeof zExecutionSuccessWsMessage
>
export type ExecutionCachedWsMessage = z.infer<typeof zExecutionCachedWsMessage>
export type ExecutionInterruptedWsMessage = z.infer<
typeof zExecutionInterruptedWsMessage
>
export type ExecutionErrorWsMessage = z.infer<typeof zExecutionErrorWsMessage>
export type LogsWsMessage = z.infer<typeof zLogsWsMessage>
export type ProgressTextWsMessage = z.infer<typeof zProgressTextWsMessage>
export type DisplayComponentWsMessage = z.infer<
typeof zDisplayComponentWsMessage
>
export type NodeProgressState = z.infer<typeof zNodeProgressState>
export type ProgressStateWsMessage = z.infer<typeof zProgressStateWsMessage>
export type FeatureFlagsWsMessage = z.infer<typeof zFeatureFlagsWsMessage>
// End of ws messages
const zPromptInputItem = z.object({
inputs: z.record(z.string(), z.any()),
class_type: zNodeType
})
const zPromptInputs = z.record(zPromptInputItem)
const zExtraPngInfo = z
.object({
workflow: zComfyWorkflow
})
.passthrough()
const zExtraData = z.object({
/** extra_pnginfo can be missing is backend execution gets a validation error. */
extra_pnginfo: zExtraPngInfo.optional(),
client_id: z.string()
})
const zOutputsToExecute = z.array(zNodeId)
const zExecutionStartMessage = z.tuple([
z.literal('execution_start'),
zExecutionStartWsMessage
])
const zExecutionSuccessMessage = z.tuple([
z.literal('execution_success'),
zExecutionSuccessWsMessage
])
const zExecutionCachedMessage = z.tuple([
z.literal('execution_cached'),
zExecutionCachedWsMessage
])
const zExecutionInterruptedMessage = z.tuple([
z.literal('execution_interrupted'),
zExecutionInterruptedWsMessage
])
const zExecutionErrorMessage = z.tuple([
z.literal('execution_error'),
zExecutionErrorWsMessage
])
const zStatusMessage = z.union([
zExecutionStartMessage,
zExecutionSuccessMessage,
zExecutionCachedMessage,
zExecutionInterruptedMessage,
zExecutionErrorMessage
])
const zStatus = z.object({
status_str: z.enum(['success', 'error']),
completed: z.boolean(),
messages: z.array(zStatusMessage)
})
const zTaskPrompt = z.tuple([
zQueueIndex,
zPromptId,
zPromptInputs,
zExtraData,
zOutputsToExecute
])
const zRunningTaskItem = z.object({
taskType: z.literal('Running'),
prompt: zTaskPrompt,
// @Deprecated
remove: z.object({
name: z.literal('Cancel'),
cb: z.function()
})
})
const zPendingTaskItem = z.object({
taskType: z.literal('Pending'),
prompt: zTaskPrompt
})
const zTaskOutput = z.record(zNodeId, zOutputs)
const zNodeOutputsMeta = z.object({
node_id: zNodeId,
display_node: zNodeId,
prompt_id: zPromptId.optional(),
read_node_id: zNodeId.optional()
})
const zTaskMeta = z.record(zNodeId, zNodeOutputsMeta)
const zHistoryTaskItem = z.object({
taskType: z.literal('History'),
prompt: zTaskPrompt,
status: zStatus.optional(),
outputs: zTaskOutput,
meta: zTaskMeta.optional()
})
const zTaskItem = z.union([
zRunningTaskItem,
zPendingTaskItem,
zHistoryTaskItem
])
const zTaskType = z.union([
z.literal('Running'),
z.literal('Pending'),
z.literal('History')
])
export type TaskType = z.infer<typeof zTaskType>
export type TaskPrompt = z.infer<typeof zTaskPrompt>
export type TaskStatus = z.infer<typeof zStatus>
export type TaskOutput = z.infer<typeof zTaskOutput>
// `/queue`
export type RunningTaskItem = z.infer<typeof zRunningTaskItem>
export type PendingTaskItem = z.infer<typeof zPendingTaskItem>
// `/history`
export type HistoryTaskItem = z.infer<typeof zHistoryTaskItem>
export type TaskItem = z.infer<typeof zTaskItem>
const zEmbeddingsResponse = z.array(z.string())
const zExtensionsResponse = z.array(z.string())
const zError = z.object({
type: z.string(),
message: z.string(),
details: z.string(),
extra_info: z
.object({
input_name: z.string().optional()
})
.passthrough()
.optional()
})
const zNodeError = z.object({
errors: z.array(zError),
class_type: z.string(),
dependent_outputs: z.array(z.any())
})
const zPromptResponse = z.object({
node_errors: z.record(zNodeId, zNodeError).optional(),
prompt_id: z.string().optional(),
exec_info: z
.object({
queue_remaining: z.number().optional()
})
.optional(),
error: z.union([z.string(), zError])
})
const zDeviceStats = z.object({
name: z.string(),
type: z.string(),
index: z.number(),
vram_total: z.number(),
vram_free: z.number(),
torch_vram_total: z.number(),
torch_vram_free: z.number()
})
const zSystemStats = z.object({
system: z.object({
os: z.string(),
python_version: z.string(),
embedded_python: z.boolean(),
comfyui_version: z.string(),
pytorch_version: z.string(),
required_frontend_version: z.string().optional(),
argv: z.array(z.string()),
ram_total: z.number(),
ram_free: z.number()
}),
devices: z.array(zDeviceStats)
})
const zUser = z.object({
storage: z.enum(['server']),
// `migrated` is only available in single-user mode.
migrated: z.boolean().optional(),
// `users` is only available in multi-user server mode.
users: z.record(z.string(), z.string()).optional()
})
const zUserData = z.array(z.array(z.string(), z.string()))
const zUserDataFullInfo = z.object({
path: z.string(),
size: z.number(),
modified: z.number()
})
const zBookmarkCustomization = z.object({
icon: z.string().optional(),
color: z.string().optional()
})
export type BookmarkCustomization = z.infer<typeof zBookmarkCustomization>
const zLinkReleaseTriggerAction = z.enum(
Object.values(LinkReleaseTriggerAction) as [string, ...string[]]
)
const zNodeBadgeMode = z.enum(
Object.values(NodeBadgeMode) as [string, ...string[]]
)
const zSettings = z.object({
'Comfy.ColorPalette': z.string(),
'Comfy.CustomColorPalettes': colorPalettesSchema,
'Comfy.Canvas.BackgroundImage': z.string().optional(),
'Comfy.ConfirmClear': z.boolean(),
'Comfy.DevMode': z.boolean(),
'Comfy.Workflow.ShowMissingNodesWarning': z.boolean(),
'Comfy.Workflow.ShowMissingModelsWarning': z.boolean(),
'Comfy.Workflow.WarnBlueprintOverwrite': z.boolean(),
'Comfy.DisableFloatRounding': z.boolean(),
'Comfy.DisableSliders': z.boolean(),
'Comfy.DOMClippingEnabled': z.boolean(),
'Comfy.EditAttention.Delta': z.number(),
'Comfy.EnableTooltips': z.boolean(),
'Comfy.EnableWorkflowViewRestore': z.boolean(),
'Comfy.FloatRoundingPrecision': z.number(),
'Comfy.Graph.CanvasInfo': z.boolean(),
'Comfy.Graph.CanvasMenu': z.boolean(),
'Comfy.Graph.CtrlShiftZoom': z.boolean(),
'Comfy.Graph.LinkMarkers': z.nativeEnum(LinkMarkerShape),
'Comfy.Graph.ZoomSpeed': z.number(),
'Comfy.Group.DoubleClickTitleToEdit': z.boolean(),
'Comfy.GroupSelectedNodes.Padding': z.number(),
'Comfy.Locale': z.string(),
'Comfy.NodeLibrary.Bookmarks': z.array(z.string()),
'Comfy.NodeLibrary.Bookmarks.V2': z.array(z.string()),
'Comfy.NodeLibrary.BookmarksCustomization': z.record(
z.string(),
zBookmarkCustomization
),
'Comfy.LinkRelease.Action': zLinkReleaseTriggerAction,
'Comfy.LinkRelease.ActionShift': zLinkReleaseTriggerAction,
'Comfy.ModelLibrary.AutoLoadAll': z.boolean(),
'Comfy.ModelLibrary.NameFormat': z.enum(['filename', 'title']),
'Comfy.NodeSearchBoxImpl.NodePreview': z.boolean(),
'Comfy.NodeSearchBoxImpl': z.enum(['default', 'simple']),
'Comfy.NodeSearchBoxImpl.ShowCategory': z.boolean(),
'Comfy.NodeSearchBoxImpl.ShowIdName': z.boolean(),
'Comfy.NodeSearchBoxImpl.ShowNodeFrequency': z.boolean(),
'Comfy.NodeSuggestions.number': z.number(),
'Comfy.Node.BypassAllLinksOnDelete': z.boolean(),
'Comfy.Node.Opacity': z.number(),
'Comfy.Node.MiddleClickRerouteNode': z.boolean(),
'Comfy.Node.ShowDeprecated': z.boolean(),
'Comfy.Node.ShowExperimental': z.boolean(),
'Comfy.Pointer.ClickBufferTime': z.number(),
'Comfy.Pointer.ClickDrift': z.number(),
'Comfy.Pointer.DoubleClickTime': z.number(),
'Comfy.PreviewFormat': z.string(),
'Comfy.PromptFilename': z.boolean(),
'Comfy.Sidebar.Location': z.enum(['left', 'right']),
'Comfy.Sidebar.Size': z.enum(['small', 'normal']),
'Comfy.Sidebar.UnifiedWidth': z.boolean(),
'Comfy.SnapToGrid.GridSize': z.number(),
'Comfy.TextareaWidget.FontSize': z.number(),
'Comfy.TextareaWidget.Spellcheck': z.boolean(),
'Comfy.UseNewMenu': z.enum(['Disabled', 'Top', 'Bottom']),
'Comfy.TreeExplorer.ItemPadding': z.number(),
'Comfy.Validation.Workflows': z.boolean(),
'Comfy.Workflow.SortNodeIdOnSave': z.boolean(),
'Comfy.Queue.ImageFit': z.enum(['contain', 'cover']),
'Comfy.Workflow.WorkflowTabsPosition': z.enum([
'Sidebar',
'Topbar',
'Topbar (2nd-row)'
]),
'Comfy.Node.DoubleClickTitleToEdit': z.boolean(),
'Comfy.WidgetControlMode': z.enum(['before', 'after']),
'Comfy.Window.UnloadConfirmation': z.boolean(),
'Comfy.NodeBadge.NodeSourceBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.NodeIdBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.NodeLifeCycleBadgeMode': zNodeBadgeMode,
'Comfy.NodeBadge.ShowApiPricing': z.boolean(),
'Comfy.Notification.ShowVersionUpdates': z.boolean(),
'Comfy.QueueButton.BatchCountLimit': z.number(),
'Comfy.Queue.MaxHistoryItems': z.number(),
'Comfy.Keybinding.UnsetBindings': z.array(zKeybinding),
'Comfy.Keybinding.NewBindings': z.array(zKeybinding),
'Comfy.Extension.Disabled': z.array(z.string()),
'Comfy.LinkRenderMode': z.number(),
'Comfy.Node.AutoSnapLinkToSlot': z.boolean(),
'Comfy.Node.SnapHighlightsNode': z.boolean(),
'Comfy.Server.ServerConfigValues': z.record(z.string(), z.any()),
'Comfy.Server.LaunchArgs': z.record(z.string(), z.string()),
'LiteGraph.Canvas.MaximumFps': z.number(),
'Comfy.Workflow.ConfirmDelete': z.boolean(),
'Comfy.Workflow.AutoSaveDelay': z.number(),
'Comfy.Workflow.AutoSave': z.enum(['off', 'after delay']),
'Comfy.RerouteBeta': z.boolean(),
'LiteGraph.Canvas.MinFontSizeForLOD': z.number(),
'Comfy.Canvas.SelectionToolbox': z.boolean(),
'LiteGraph.Node.TooltipDelay': z.number(),
'LiteGraph.ContextMenu.Scaling': z.boolean(),
'LiteGraph.Reroute.SplineOffset': z.number(),
'LiteGraph.Canvas.LowQualityRenderingZoomThreshold': z.number(),
'Comfy.Toast.DisableReconnectingToast': z.boolean(),
'Comfy.Workflow.Persist': z.boolean(),
'Comfy.TutorialCompleted': z.boolean(),
'Comfy.InstalledVersion': z.string().nullable(),
'Comfy.Node.AllowImageSizeDraw': z.boolean(),
'Comfy.Minimap.Visible': z.boolean(),
'Comfy.Minimap.NodeColors': z.boolean(),
'Comfy.Minimap.ShowLinks': z.boolean(),
'Comfy.Minimap.ShowGroups': z.boolean(),
'Comfy.Minimap.RenderBypassState': z.boolean(),
'Comfy.Minimap.RenderErrorState': z.boolean(),
'Comfy.Canvas.NavigationMode': z.string(),
'Comfy.Canvas.LeftMouseClickBehavior': z.string(),
'Comfy.Canvas.MouseWheelScroll': z.string(),
'Comfy.VueNodes.Enabled': z.boolean(),
'Comfy.Assets.UseAssetAPI': z.boolean(),
'Comfy-Desktop.AutoUpdate': z.boolean(),
'Comfy-Desktop.SendStatistics': z.boolean(),
'Comfy-Desktop.WindowStyle': z.string(),
'Comfy-Desktop.UV.PythonInstallMirror': z.string(),
'Comfy-Desktop.UV.PypiInstallMirror': z.string(),
'Comfy-Desktop.UV.TorchInstallMirror': z.string(),
'Comfy.MaskEditor.UseNewEditor': z.boolean(),
'Comfy.MaskEditor.BrushAdjustmentSpeed': z.number(),
'Comfy.MaskEditor.UseDominantAxis': z.boolean(),
'Comfy.Load3D.ShowGrid': z.boolean(),
'Comfy.Load3D.ShowPreview': z.boolean(),
'Comfy.Load3D.BackgroundColor': z.string(),
'Comfy.Load3D.LightIntensity': z.number(),
'Comfy.Load3D.LightIntensityMaximum': z.number(),
'Comfy.Load3D.LightIntensityMinimum': z.number(),
'Comfy.Load3D.LightAdjustmentIncrement': z.number(),
'Comfy.Load3D.CameraType': z.enum(['perspective', 'orthographic']),
'Comfy.Load3D.3DViewerEnable': z.boolean(),
'Comfy.Memory.AllowManualUnload': z.boolean(),
'pysssss.SnapToGrid': z.boolean(),
/** VHS setting is used for queue video preview support. */
'VHS.AdvancedPreviews': z.string(),
/** Release data settings */
'Comfy.Release.Version': z.string(),
'Comfy.Release.Status': z.enum([
'skipped',
'changelog seen',
"what's new seen"
]),
'Comfy.Release.Timestamp': z.number(),
/** Settings used for testing */
'test.setting': z.any(),
'main.sub.setting.name': z.any(),
'single.setting': z.any(),
'LiteGraph.Node.DefaultPadding': z.boolean(),
'LiteGraph.Pointer.TrackpadGestures': z.boolean()
})
export type EmbeddingsResponse = z.infer<typeof zEmbeddingsResponse>
export type ExtensionsResponse = z.infer<typeof zExtensionsResponse>
export type PromptResponse = z.infer<typeof zPromptResponse>
export type NodeError = z.infer<typeof zNodeError>
export type Settings = z.infer<typeof zSettings>
export type DeviceStats = z.infer<typeof zDeviceStats>
export type SystemStats = z.infer<typeof zSystemStats>
export type User = z.infer<typeof zUser>
export type UserData = z.infer<typeof zUserData>
export type UserDataFullInfo = z.infer<typeof zUserDataFullInfo>
export type TerminalSize = z.infer<typeof zTerminalSize>
export type LogEntry = z.infer<typeof zLogEntry>
export type LogsRawResponse = z.infer<typeof zLogRawResponse>
export * from '@comfyorg/schemas/apiSchema'

View File

@@ -1,116 +1 @@
import { z } from 'zod'
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
const nodeSlotSchema = z.object({
CLIP: z.string(),
CLIP_VISION: z.string(),
CLIP_VISION_OUTPUT: z.string(),
CONDITIONING: z.string(),
CONTROL_NET: z.string(),
IMAGE: z.string(),
LATENT: z.string(),
MASK: z.string(),
MODEL: z.string(),
STYLE_MODEL: z.string(),
VAE: z.string(),
NOISE: z.string(),
GUIDER: z.string(),
SAMPLER: z.string(),
SIGMAS: z.string(),
TAESD: z.string()
})
const litegraphBaseSchema = z.object({
BACKGROUND_IMAGE: z.string(),
CLEAR_BACKGROUND_COLOR: z.string(),
NODE_TITLE_COLOR: z.string(),
NODE_SELECTED_TITLE_COLOR: z.string(),
NODE_TEXT_SIZE: z.number(),
NODE_TEXT_COLOR: z.string(),
NODE_TEXT_HIGHLIGHT_COLOR: z.string(),
NODE_SUBTEXT_SIZE: z.number(),
NODE_DEFAULT_COLOR: z.string(),
NODE_DEFAULT_BGCOLOR: z.string(),
NODE_DEFAULT_BOXCOLOR: z.string(),
NODE_DEFAULT_SHAPE: z.union([
z.literal(LiteGraph.BOX_SHAPE),
z.literal(LiteGraph.ROUND_SHAPE),
z.literal(LiteGraph.CARD_SHAPE),
// Legacy palettes have string field for NODE_DEFAULT_SHAPE.
z.string()
]),
NODE_BOX_OUTLINE_COLOR: z.string(),
NODE_BYPASS_BGCOLOR: z.string(),
NODE_ERROR_COLOUR: z.string(),
DEFAULT_SHADOW_COLOR: z.string(),
DEFAULT_GROUP_FONT: z.number(),
WIDGET_BGCOLOR: z.string(),
WIDGET_OUTLINE_COLOR: z.string(),
WIDGET_TEXT_COLOR: z.string(),
WIDGET_SECONDARY_TEXT_COLOR: z.string(),
WIDGET_DISABLED_TEXT_COLOR: z.string(),
LINK_COLOR: z.string(),
EVENT_LINK_COLOR: z.string(),
CONNECTING_LINK_COLOR: z.string(),
BADGE_FG_COLOR: z.string(),
BADGE_BG_COLOR: z.string()
})
const comfyBaseSchema = z.object({
['fg-color']: z.string(),
['bg-color']: z.string(),
['bg-img']: z.string().optional(),
['comfy-menu-bg']: z.string(),
['comfy-menu-secondary-bg']: z.string(),
['comfy-input-bg']: z.string(),
['input-text']: z.string(),
['descrip-text']: z.string(),
['drag-text']: z.string(),
['error-text']: z.string(),
['border-color']: z.string(),
['tr-even-bg-color']: z.string(),
['tr-odd-bg-color']: z.string(),
['content-bg']: z.string(),
['content-fg']: z.string(),
['content-hover-bg']: z.string(),
['content-hover-fg']: z.string(),
['bar-shadow']: z.string()
})
const colorsSchema = z.object({
node_slot: nodeSlotSchema,
litegraph_base: litegraphBaseSchema,
comfy_base: comfyBaseSchema
})
const partialColorsSchema = z.object({
node_slot: nodeSlotSchema.partial(),
litegraph_base: litegraphBaseSchema.partial(),
comfy_base: comfyBaseSchema.partial()
})
// Palette in the wild can have custom metadata fields such as 'version'.
export const paletteSchema = z
.object({
id: z.string(),
name: z.string(),
colors: partialColorsSchema,
light_theme: z.boolean().optional()
})
.passthrough()
const completedPaletteSchema = z
.object({
id: z.string(),
name: z.string(),
colors: colorsSchema
})
.passthrough()
export const colorPalettesSchema = z.record(paletteSchema)
export type Colors = z.infer<typeof colorsSchema>
export type Palette = z.infer<typeof paletteSchema>
export type CompletedPalette = z.infer<typeof completedPaletteSchema>
export type ColorPalettes = z.infer<typeof colorPalettesSchema>
export * from '@comfyorg/schemas/colorPaletteSchema'

View File

@@ -1,25 +1 @@
import { z } from 'zod'
// KeyCombo schema
const zKeyCombo = z.object({
key: z.string(),
ctrl: z.boolean().optional(),
alt: z.boolean().optional(),
shift: z.boolean().optional(),
meta: z.boolean().optional()
})
// Keybinding schema
export const zKeybinding = z.object({
commandId: z.string(),
combo: zKeyCombo,
// Optional target element ID to limit keybinding to.
// Note: Currently only used to distinguish between global keybindings
// and litegraph canvas keybindings.
// Do NOT use this field in extensions as it has no effect.
targetElementId: z.string().optional()
})
// Infer types from schemas
export type KeyCombo = z.infer<typeof zKeyCombo>
export type Keybinding = z.infer<typeof zKeybinding>
export * from '@comfyorg/schemas/keyBindingSchema'

View File

@@ -1,143 +1 @@
import type {
ComfyNodeDef as ComfyNodeDefV2,
InputSpec as InputSpecV2,
OutputSpec as OutputSpecV2
} from '@/schemas/nodeDef/nodeDefSchemaV2'
import type {
ComfyNodeDef as ComfyNodeDefV1,
InputSpec as InputSpecV1
} from '@/schemas/nodeDefSchema'
import {
getComboSpecComboOptions,
isComboInputSpec,
isComboInputSpecV1
} from '@/schemas/nodeDefSchema'
/**
* Transforms a V1 node definition to V2 format
* @param nodeDefV1 The V1 node definition to transform
* @returns The transformed V2 node definition
*/
export function transformNodeDefV1ToV2(
nodeDefV1: ComfyNodeDefV1
): ComfyNodeDefV2 {
// Transform inputs
const inputs: Record<string, InputSpecV2> = {}
// Process required inputs
if (nodeDefV1.input?.required) {
Object.entries(nodeDefV1.input.required).forEach(([name, inputSpecV1]) => {
inputs[name] = transformInputSpecV1ToV2(inputSpecV1, {
name,
isOptional: false
})
})
}
// Process optional inputs
if (nodeDefV1.input?.optional) {
Object.entries(nodeDefV1.input.optional).forEach(([name, inputSpecV1]) => {
inputs[name] = transformInputSpecV1ToV2(inputSpecV1, {
name,
isOptional: true
})
})
}
// Transform outputs
const outputs: OutputSpecV2[] = []
if (nodeDefV1.output) {
if (Array.isArray(nodeDefV1.output)) {
nodeDefV1.output.forEach((outputType, index) => {
const outputSpec: OutputSpecV2 = {
index,
name: nodeDefV1.output_name?.[index] || `output_${index}`,
type: Array.isArray(outputType) ? 'COMBO' : outputType,
is_list: nodeDefV1.output_is_list?.[index] || false,
tooltip: nodeDefV1.output_tooltips?.[index]
}
// Add options for combo outputs
if (Array.isArray(outputType)) {
outputSpec.options = outputType
}
outputs.push(outputSpec)
})
} else {
console.warn('nodeDefV1.output is not an array:', nodeDefV1.output)
}
}
// Create the V2 node definition
return {
inputs,
outputs,
hidden: nodeDefV1.input?.hidden,
name: nodeDefV1.name,
display_name: nodeDefV1.display_name,
description: nodeDefV1.description,
category: nodeDefV1.category,
output_node: nodeDefV1.output_node,
python_module: nodeDefV1.python_module,
deprecated: nodeDefV1.deprecated,
experimental: nodeDefV1.experimental
}
}
/**
* Transforms a V1 input specification to V2 format
* @param inputSpecV1 The V1 input specification to transform
* @param name The name of the input
* @param isOptional Whether the input is optional
* @returns The transformed V2 input specification
*/
export function transformInputSpecV1ToV2(
inputSpecV1: InputSpecV1,
kwargs: {
name: string
isOptional?: boolean
}
): InputSpecV2 {
const { name, isOptional = false } = kwargs
// Extract options from the input spec
const options = inputSpecV1[1] || {}
// Base properties for all input types
const baseProps = {
name,
isOptional,
...options
}
// Handle different input types
if (isComboInputSpec(inputSpecV1)) {
return {
type: 'COMBO',
...baseProps,
options: isComboInputSpecV1(inputSpecV1)
? inputSpecV1[0]
: getComboSpecComboOptions(inputSpecV1)
}
} else if (typeof inputSpecV1[0] === 'string') {
// Handle standard types (INT, FLOAT, BOOLEAN, STRING) and custom types
return {
type: inputSpecV1[0],
...baseProps
}
}
// Fallback for any unhandled cases
return {
type: 'UNKNOWN',
...baseProps
}
}
export function transformInputSpecV2ToV1(
inputSpecV2: InputSpecV2
): InputSpecV1 {
return [inputSpecV2.type, inputSpecV2]
}
export * from '@comfyorg/schemas/nodeDef/migration'

View File

@@ -1,264 +1 @@
import { z } from 'zod'
import {
zBaseInputOptions,
zBooleanInputOptions,
zComboInputOptions,
zFloatInputOptions,
zIntInputOptions,
zStringInputOptions
} from '@/schemas/nodeDefSchema'
const zIntInputSpec = zIntInputOptions.extend({
type: z.literal('INT'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zFloatInputSpec = zFloatInputOptions.extend({
type: z.literal('FLOAT'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zBooleanInputSpec = zBooleanInputOptions.extend({
type: z.literal('BOOLEAN'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zStringInputSpec = zStringInputOptions.extend({
type: z.literal('STRING'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zComboInputSpec = zComboInputOptions.extend({
type: z.literal('COMBO'),
name: z.string(),
isOptional: z.boolean().optional()
})
const zColorInputSpec = zBaseInputOptions.extend({
type: z.literal('COLOR'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
default: z.string().optional()
})
.optional()
})
const zFileUploadInputSpec = zBaseInputOptions.extend({
type: z.literal('FILEUPLOAD'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zImageInputSpec = zBaseInputOptions.extend({
type: z.literal('IMAGE'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zImageCompareInputSpec = zBaseInputOptions.extend({
type: z.literal('IMAGECOMPARE'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z.record(z.unknown()).optional()
})
const zMarkdownInputSpec = zBaseInputOptions.extend({
type: z.literal('MARKDOWN'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
content: z.string().optional()
})
.optional()
})
const zTreeSelectInputSpec = zBaseInputOptions.extend({
type: z.literal('TREESELECT'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
multiple: z.boolean().optional(),
values: z.array(z.unknown()).optional()
})
.optional()
})
const zMultiSelectInputSpec = zBaseInputOptions.extend({
type: z.literal('MULTISELECT'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
values: z.array(z.string()).optional()
})
.optional()
})
const zChartInputSpec = zBaseInputOptions.extend({
type: z.literal('CHART'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
type: z.enum(['bar', 'line']).optional(),
data: z.object({}).optional()
})
.optional()
})
const zGalleriaInputSpec = zBaseInputOptions.extend({
type: z.literal('GALLERIA'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
images: z.array(z.string()).optional()
})
.optional()
})
const zSelectButtonInputSpec = zBaseInputOptions.extend({
type: z.literal('SELECTBUTTON'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
values: z.array(z.string()).optional()
})
.optional()
})
const zTextareaInputSpec = zBaseInputOptions.extend({
type: z.literal('TEXTAREA'),
name: z.string(),
isOptional: z.boolean().optional(),
options: z
.object({
rows: z.number().optional(),
cols: z.number().optional(),
default: z.string().optional()
})
.optional()
})
const zCustomInputSpec = zBaseInputOptions.extend({
type: z.string(),
name: z.string(),
isOptional: z.boolean().optional()
})
const zInputSpec = z.union([
zIntInputSpec,
zFloatInputSpec,
zBooleanInputSpec,
zStringInputSpec,
zComboInputSpec,
zColorInputSpec,
zFileUploadInputSpec,
zImageInputSpec,
zImageCompareInputSpec,
zMarkdownInputSpec,
zTreeSelectInputSpec,
zMultiSelectInputSpec,
zChartInputSpec,
zGalleriaInputSpec,
zSelectButtonInputSpec,
zTextareaInputSpec,
zCustomInputSpec
])
// Output specs
const zOutputSpec = z.object({
index: z.number(),
name: z.string(),
type: z.string(),
is_list: z.boolean(),
options: z.array(z.any()).optional(),
tooltip: z.string().optional()
})
// Main node definition schema
export const zComfyNodeDef = z.object({
inputs: z.record(zInputSpec),
outputs: z.array(zOutputSpec),
hidden: z.record(z.any()).optional(),
name: z.string(),
display_name: z.string(),
description: z.string(),
help: z.string().optional(),
category: z.string(),
output_node: z.boolean(),
python_module: z.string(),
deprecated: z.boolean().optional(),
experimental: z.boolean().optional(),
api_node: z.boolean().optional()
})
// Export types
type IntInputSpec = z.infer<typeof zIntInputSpec>
type FloatInputSpec = z.infer<typeof zFloatInputSpec>
type BooleanInputSpec = z.infer<typeof zBooleanInputSpec>
type StringInputSpec = z.infer<typeof zStringInputSpec>
export type ComboInputSpec = z.infer<typeof zComboInputSpec>
export type ColorInputSpec = z.infer<typeof zColorInputSpec>
export type FileUploadInputSpec = z.infer<typeof zFileUploadInputSpec>
export type ImageCompareInputSpec = z.infer<typeof zImageCompareInputSpec>
export type TreeSelectInputSpec = z.infer<typeof zTreeSelectInputSpec>
export type MultiSelectInputSpec = z.infer<typeof zMultiSelectInputSpec>
export type ChartInputSpec = z.infer<typeof zChartInputSpec>
export type GalleriaInputSpec = z.infer<typeof zGalleriaInputSpec>
export type SelectButtonInputSpec = z.infer<typeof zSelectButtonInputSpec>
export type TextareaInputSpec = z.infer<typeof zTextareaInputSpec>
export type CustomInputSpec = z.infer<typeof zCustomInputSpec>
export type InputSpec = z.infer<typeof zInputSpec>
export type OutputSpec = z.infer<typeof zOutputSpec>
export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
export const isIntInputSpec = (
inputSpec: InputSpec
): inputSpec is IntInputSpec => {
return inputSpec.type === 'INT'
}
export const isFloatInputSpec = (
inputSpec: InputSpec
): inputSpec is FloatInputSpec => {
return inputSpec.type === 'FLOAT'
}
export const isBooleanInputSpec = (
inputSpec: InputSpec
): inputSpec is BooleanInputSpec => {
return inputSpec.type === 'BOOLEAN'
}
export const isStringInputSpec = (
inputSpec: InputSpec
): inputSpec is StringInputSpec => {
return inputSpec.type === 'STRING'
}
export const isComboInputSpec = (
inputSpec: InputSpec
): inputSpec is ComboInputSpec => {
return inputSpec.type === 'COMBO'
}
export const isChartInputSpec = (
inputSpec: InputSpec
): inputSpec is ChartInputSpec => {
return inputSpec.type === 'CHART'
}
export * from '@comfyorg/schemas/nodeDef/nodeDefSchemaV2'

View File

@@ -1,255 +1 @@
import { z } from 'zod'
import { fromZodError } from 'zod-validation-error'
import { resultItemType } from '@/schemas/apiSchema'
const zComboOption = z.union([z.string(), z.number()])
const zRemoteWidgetConfig = z.object({
route: z.string().url().or(z.string().startsWith('/')),
refresh: z.number().gte(128).safe().or(z.number().lte(0).safe()).optional(),
response_key: z.string().optional(),
query_params: z.record(z.string(), z.string()).optional(),
refresh_button: z.boolean().optional(),
control_after_refresh: z.enum(['first', 'last']).optional(),
timeout: z.number().gte(0).optional(),
max_retries: z.number().gte(0).optional()
})
const zMultiSelectOption = z.object({
placeholder: z.string().optional(),
chip: z.boolean().optional()
})
export const zBaseInputOptions = z
.object({
default: z.any().optional(),
defaultInput: z.boolean().optional(),
forceInput: z.boolean().optional(),
tooltip: z.string().optional(),
hidden: z.boolean().optional(),
advanced: z.boolean().optional(),
widgetType: z.string().optional(),
/** Backend-only properties. */
rawLink: z.boolean().optional(),
lazy: z.boolean().optional()
})
.passthrough()
const zNumericInputOptions = zBaseInputOptions.extend({
min: z.number().optional(),
max: z.number().optional(),
step: z.number().optional(),
/** Note: Many node authors are using INT/FLOAT to pass list of INT/FLOAT. */
default: z.union([z.number(), z.array(z.number())]).optional(),
display: z.enum(['slider', 'number', 'knob']).optional()
})
export const zIntInputOptions = zNumericInputOptions.extend({
/**
* If true, a linked widget will be added to the node to select the mode
* of `control_after_generate`.
*/
control_after_generate: z.boolean().optional()
})
export const zFloatInputOptions = zNumericInputOptions.extend({
round: z.union([z.number(), z.literal(false)]).optional()
})
export const zBooleanInputOptions = zBaseInputOptions.extend({
label_on: z.string().optional(),
label_off: z.string().optional(),
default: z.boolean().optional()
})
export const zStringInputOptions = zBaseInputOptions.extend({
default: z.string().optional(),
multiline: z.boolean().optional(),
dynamicPrompts: z.boolean().optional(),
// Multiline-only fields
defaultVal: z.string().optional(),
placeholder: z.string().optional()
})
export const zComboInputOptions = zBaseInputOptions.extend({
control_after_generate: z.boolean().optional(),
image_upload: z.boolean().optional(),
image_folder: resultItemType.optional(),
allow_batch: z.boolean().optional(),
video_upload: z.boolean().optional(),
audio_upload: z.boolean().optional(),
animated_image_upload: z.boolean().optional(),
options: z.array(zComboOption).optional(),
remote: zRemoteWidgetConfig.optional(),
/** Whether the widget is a multi-select widget. */
multi_select: zMultiSelectOption.optional()
})
const zIntInputSpec = z.tuple([z.literal('INT'), zIntInputOptions.optional()])
const zFloatInputSpec = z.tuple([
z.literal('FLOAT'),
zFloatInputOptions.optional()
])
const zBooleanInputSpec = z.tuple([
z.literal('BOOLEAN'),
zBooleanInputOptions.optional()
])
const zStringInputSpec = z.tuple([
z.literal('STRING'),
zStringInputOptions.optional()
])
/**
* Legacy combo syntax.
* @deprecated Use `zComboInputSpecV2` instead.
*/
const zComboInputSpec = z.tuple([
z.array(zComboOption),
zComboInputOptions.optional()
])
const zComboInputSpecV2 = z.tuple([
z.literal('COMBO'),
zComboInputOptions.optional()
])
export function isComboInputSpecV1(
inputSpec: InputSpec
): inputSpec is ComboInputSpec {
return Array.isArray(inputSpec[0])
}
export function isIntInputSpec(
inputSpec: InputSpec
): inputSpec is IntInputSpec {
return inputSpec[0] === 'INT'
}
export function isFloatInputSpec(
inputSpec: InputSpec
): inputSpec is FloatInputSpec {
return inputSpec[0] === 'FLOAT'
}
export function isComboInputSpecV2(
inputSpec: InputSpec
): inputSpec is ComboInputSpecV2 {
return inputSpec[0] === 'COMBO'
}
export function isComboInputSpec(
inputSpec: InputSpec
): inputSpec is ComboInputSpec | ComboInputSpecV2 {
return isComboInputSpecV1(inputSpec) || isComboInputSpecV2(inputSpec)
}
/**
* Get the type of an input spec.
*
* @param inputSpec - The input spec to get the type of.
* @returns The type of the input spec.
*/
export function getInputSpecType(inputSpec: InputSpec): string {
return isComboInputSpec(inputSpec) ? 'COMBO' : inputSpec[0]
}
/**
* Get the combo options from a combo input spec.
*
* @param inputSpec - The input spec to get the combo options from.
* @returns The combo options.
*/
export function getComboSpecComboOptions(
inputSpec: ComboInputSpec | ComboInputSpecV2
): (number | string)[] {
return (
(isComboInputSpecV2(inputSpec) ? inputSpec[1]?.options : inputSpec[0]) ?? []
)
}
const excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])
const zCustomInputSpec = z.tuple([
z.string().refine((value) => !excludedLiterals.has(value)),
zBaseInputOptions.optional()
])
const zInputSpec = z.union([
zIntInputSpec,
zFloatInputSpec,
zBooleanInputSpec,
zStringInputSpec,
zComboInputSpec,
zComboInputSpecV2,
zCustomInputSpec
])
const zComfyInputsSpec = z.object({
required: z.record(zInputSpec).optional(),
optional: z.record(zInputSpec).optional(),
// Frontend repo is not using it, but some custom nodes are using the
// hidden field to pass various values.
hidden: z.record(z.any()).optional()
})
const zComfyNodeDataType = z.string()
const zComfyComboOutput = z.array(zComboOption)
const zComfyOutputTypesSpec = z.array(
z.union([zComfyNodeDataType, zComfyComboOutput])
)
export const zComfyNodeDef = z.object({
input: zComfyInputsSpec.optional(),
output: zComfyOutputTypesSpec.optional(),
output_is_list: z.array(z.boolean()).optional(),
output_name: z.array(z.string()).optional(),
output_tooltips: z.array(z.string()).optional(),
name: z.string(),
display_name: z.string(),
description: z.string(),
help: z.string().optional(),
category: z.string(),
output_node: z.boolean(),
python_module: z.string(),
deprecated: z.boolean().optional(),
experimental: z.boolean().optional(),
/**
* Whether the node is an API node. Running API nodes requires login to
* Comfy Org account.
* https://docs.comfy.org/tutorials/api-nodes/overview
*/
api_node: z.boolean().optional(),
/**
* Specifies the order of inputs for each input category.
* Used to ensure consistent widget ordering regardless of JSON serialization.
* Keys are 'required', 'optional', etc., values are arrays of input names.
*/
input_order: z.record(z.array(z.string())).optional()
})
// `/object_info`
export type ComfyInputsSpec = z.infer<typeof zComfyInputsSpec>
export type ComfyOutputTypesSpec = z.infer<typeof zComfyOutputTypesSpec>
export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
export type RemoteWidgetConfig = z.infer<typeof zRemoteWidgetConfig>
export type ComboInputOptions = z.infer<typeof zComboInputOptions>
export type NumericInputOptions = z.infer<typeof zNumericInputOptions>
export type IntInputSpec = z.infer<typeof zIntInputSpec>
export type FloatInputSpec = z.infer<typeof zFloatInputSpec>
export type ComboInputSpec = z.infer<typeof zComboInputSpec>
export type ComboInputSpecV2 = z.infer<typeof zComboInputSpecV2>
export type InputSpec = z.infer<typeof zInputSpec>
export function validateComfyNodeDef(
data: any,
onError: (error: string) => void = console.warn
): ComfyNodeDef | null {
const result = zComfyNodeDef.safeParse(data)
if (!result.success) {
const zodError = fromZodError(result.error)
onError(
`Invalid ComfyNodeDef: ${JSON.stringify(data)}\n${zodError.message}`
)
return null
}
return result.data
}
export * from '@comfyorg/schemas/nodeDefSchema'

View File

@@ -1,60 +1 @@
import { z } from 'zod'
import { t } from '@/i18n'
export const apiKeySchema = z.object({
apiKey: z
.string()
.trim()
.startsWith('comfyui-', t('validation.prefix', { prefix: 'comfyui-' }))
.length(72, t('validation.length', { length: 72 }))
})
export const signInSchema = z.object({
email: z
.string()
.email(t('validation.invalidEmail'))
.min(1, t('validation.required')),
password: z.string().min(1, t('validation.required'))
})
export type SignInData = z.infer<typeof signInSchema>
const passwordSchema = z.object({
password: z
.string()
.min(8, t('validation.minLength', { length: 8 }))
.max(32, t('validation.maxLength', { length: 32 }))
.regex(/[A-Z]/, t('validation.password.uppercase'))
.regex(/[a-z]/, t('validation.password.lowercase'))
.regex(/\d/, t('validation.password.number'))
.regex(/[^A-Za-z0-9]/, t('validation.password.special')),
confirmPassword: z.string().min(1, t('validation.required'))
})
export const updatePasswordSchema = passwordSchema.refine(
(data) => data.password === data.confirmPassword,
{
message: t('validation.password.match'),
path: ['confirmPassword']
}
)
export const signUpSchema = passwordSchema
.extend({
email: z
.string()
.email(t('validation.invalidEmail'))
.min(1, t('validation.required')),
personalDataConsent: z.boolean()
})
.refine((data) => data.password === data.confirmPassword, {
message: t('validation.password.match'),
path: ['confirmPassword']
})
.refine((data) => data.personalDataConsent === true, {
message: t('validation.personalDataConsentRequired'),
path: ['personalDataConsent']
})
export type SignUpData = z.infer<typeof signUpSchema>
export * from '@comfyorg/schemas/signInSchema'

View File

@@ -1,10 +1,8 @@
import { describe, expect, it } from 'vitest'
import type { NodeLayout } from '@/renderer/core/layout/types'
import {
REROUTE_RADIUS,
boundsIntersect,
calculateBounds,
pointInBounds
} from '@/renderer/core/layout/utils/layoutMath'
@@ -48,75 +46,4 @@ describe('layoutMath utils', () => {
expect(REROUTE_RADIUS).toBeGreaterThan(0)
})
})
describe('calculateBounds', () => {
const createTestNode = (
id: string,
x: number,
y: number,
width: number,
height: number
): NodeLayout => ({
id,
position: { x, y },
size: { width, height },
zIndex: 0,
visible: true,
bounds: { x, y, width, height }
})
it('calculates bounds for single node', () => {
const nodes = [createTestNode('1', 10, 20, 100, 50)]
const bounds = calculateBounds(nodes)
expect(bounds).toEqual({
x: 10,
y: 20,
width: 100,
height: 50
})
})
it('calculates combined bounds for multiple nodes', () => {
const nodes = [
createTestNode('1', 0, 0, 50, 50), // Top-left: (0,0) to (50,50)
createTestNode('2', 100, 100, 30, 40), // Bottom-right: (100,100) to (130,140)
createTestNode('3', 25, 75, 20, 10) // Middle: (25,75) to (45,85)
]
const bounds = calculateBounds(nodes)
expect(bounds).toEqual({
x: 0, // leftmost
y: 0, // topmost
width: 130, // rightmost (130) - leftmost (0)
height: 140 // bottommost (140) - topmost (0)
})
})
it('handles nodes with negative positions', () => {
const nodes = [
createTestNode('1', -50, -30, 40, 20), // (-50,-30) to (-10,-10)
createTestNode('2', 10, 15, 25, 35) // (10,15) to (35,50)
]
const bounds = calculateBounds(nodes)
expect(bounds).toEqual({
x: -50,
y: -30,
width: 85, // 35 - (-50)
height: 80 // 50 - (-30)
})
})
it('handles empty array', () => {
const bounds = calculateBounds([])
expect(bounds).toEqual({
x: Infinity,
y: Infinity,
width: -Infinity,
height: -Infinity
})
})
})
})