Compare commits

..

13 Commits

Author SHA1 Message Date
Deep Roy
5d3e24096b test whether tests are passing 2025-08-13 18:38:42 -04:00
Robin Huang
2de65d7e17 Use hostname to determine environment. 2025-08-12 12:34:18 -07:00
Richard Yu
164d7aac4d sort history by exec start time rather than priority 2025-08-12 12:34:18 -07:00
Richard Yu
76d453aaa3 Add "as TaskPrompt" 2025-08-12 12:34:18 -07:00
Richard Yu
9c65b47a64 update api.ts to handle prompt formats 2025-08-12 12:34:18 -07:00
Richard Yu
c4c1c8121c [fix] handle cancelling pending jobs 2025-08-12 12:34:18 -07:00
Robin Huang
58c076dd84 Fix type error. 2025-08-12 12:34:18 -07:00
Robin Huang
581b319b05 Add 2025-08-12 12:34:18 -07:00
Robin Huang
141615b911 Enable sentry integrations. 2025-08-12 12:34:18 -07:00
Richard Yu
31fac20a03 [feat] Update history API to v2 array format and add comprehensive tests
- Migrate from object-based to array-based history response format
- Update /history endpoint to /history_v2 with max_items parameter
- Add lazy loading of workflows via /history_v2/:prompt_id endpoint
- Implement comprehensive browser tests for history API functionality
- Add unit tests for API methods and queue store
- Update TaskItemImpl to support history workflow loading
- Add proper error handling and edge case coverage
- Follow established test patterns for better maintainability

This change improves performance by reducing initial payload size
and enables on-demand workflow loading for history items.
2025-08-12 12:34:18 -07:00
Robin Huang
5e9abf2c41 Add notifications via websocket. 2025-08-12 12:34:18 -07:00
Robin Huang
309cbd4dc4 Prevent access without login. 2025-08-12 12:34:18 -07:00
Robin Huang
ad2ffdcd85 Add client_id to query param. 2025-08-12 12:34:18 -07:00
94 changed files with 1269 additions and 935 deletions

View File

@@ -49,7 +49,7 @@ DO NOT use deprecated PrimeVue components. Use these replacements instead:
## Development Guidelines
1. Leverage VueUse functions for performance-enhancing styles
2. Use es-toolkit for utility functions
2. Use lodash for utility functions
3. Use TypeScript for type safety
4. Implement proper props and emits definitions
5. Utilize Vue 3's Teleport component when needed

View File

@@ -18,7 +18,7 @@ Use Tailwind CSS for styling
Leverage VueUse functions for performance-enhancing styles
Use es-toolkit for utility functions
Use lodash for utility functions
Use TypeScript for type safety

View File

@@ -61,11 +61,6 @@ jobs:
exit 1
fi
- name: Lint generated types
run: |
echo "Linting generated ComfyUI-Manager API types..."
npm run lint:fix:no-cache -- ./src/types/generatedManagerTypes.ts
- name: Check for changes
id: check-changes
run: |

View File

@@ -61,11 +61,6 @@ jobs:
exit 1
fi
- name: Lint generated types
run: |
echo "Linting generated Comfy Registry API types..."
npm run lint:fix:no-cache -- ./src/types/comfyRegistryTypes.ts
- name: Check for changes
id: check-changes
run: |

3
.gitignore vendored
View File

@@ -7,9 +7,6 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# ESLint cache
.eslintcache
node_modules
dist
dist-ssr

0
a Normal file
View File

View File

@@ -1,5 +1,5 @@
import _ from 'es-toolkit/compat'
import fs from 'fs'
import _ from 'lodash'
import path from 'path'
import type { Request, Route } from 'playwright'
import { v4 as uuidv4 } from 'uuid'
@@ -34,17 +34,23 @@ const getContentType = (filename: string, fileType: OutputFileType) => {
}
const setQueueIndex = (task: TaskItem) => {
task.prompt[0] = TaskHistory.queueIndex++
task.prompt.priority = TaskHistory.queueIndex++
}
const setPromptId = (task: TaskItem) => {
task.prompt[1] = uuidv4()
if (!task.prompt.prompt_id || task.prompt.prompt_id === 'prompt-id') {
task.prompt.prompt_id = uuidv4()
}
}
export default class TaskHistory {
static queueIndex = 0
static readonly defaultTask: Readonly<HistoryTaskItem> = {
prompt: [0, 'prompt-id', {}, { client_id: uuidv4() }, []],
prompt: {
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: uuidv4() }
},
outputs: {},
status: {
status_str: 'success',
@@ -66,18 +72,43 @@ export default class TaskHistory {
)
private async handleGetHistory(route: Route) {
const url = route.request().url()
// Handle history_v2/:prompt_id endpoint
const promptIdMatch = url.match(/history_v2\/([^?]+)/)
if (promptIdMatch) {
const promptId = promptIdMatch[1]
const task = this.tasks.find((t) => t.prompt.prompt_id === promptId)
const response: Record<string, any> = {}
if (task) {
response[promptId] = task
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(response)
})
}
// Handle history_v2 list endpoint
// Convert HistoryTaskItem to RawHistoryItem format expected by API
const rawHistoryItems = this.tasks.map((task) => ({
prompt_id: task.prompt.prompt_id,
prompt: task.prompt,
status: task.status,
outputs: task.outputs,
...(task.meta && { meta: task.meta })
}))
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(this.tasks)
body: JSON.stringify({ history: rawHistoryItems })
})
}
private async handleGetView(route: Route) {
const fileName = getFilenameParam(route.request())
if (!this.outputContentTypes.has(fileName)) {
return route.continue()
}
if (!this.outputContentTypes.has(fileName)) return route.continue()
const asset = this.loadAsset(fileName)
return route.fulfill({
@@ -93,7 +124,7 @@ export default class TaskHistory {
async setupRoutes() {
return this.comfyPage.page.route(
/.*\/api\/(view|history)(\?.*)?$/,
/.*\/api\/(view|history_v2)(\/[^?]*)?(\?.*)?$/,
async (route) => {
const request = route.request()
const method = request.method()

View File

@@ -0,0 +1,131 @@
import {
comfyExpect as expect,
comfyPageFixture as test
} from '../fixtures/ComfyPage'
test.describe('History API v2', () => {
const TEST_PROMPT_ID = 'test-prompt-id'
const TEST_CLIENT_ID = 'test-client'
test('Can fetch history with new v2 format', async ({ comfyPage }) => {
// Set up mocked history with tasks
await comfyPage.setupHistory().withTask(['example.webp']).setupRoutes()
// Verify history_v2 API response format
const result = await comfyPage.page.evaluate(async () => {
try {
const response = await window['app'].api.getHistory()
return { success: true, data: response }
} catch (error) {
console.error('Failed to fetch history:', error)
return { success: false, error: error.message }
}
})
expect(result.success).toBe(true)
expect(result.data).toHaveProperty('History')
expect(Array.isArray(result.data.History)).toBe(true)
expect(result.data.History.length).toBeGreaterThan(0)
const historyItem = result.data.History[0]
// Verify the new prompt structure (object instead of array)
expect(historyItem.prompt).toHaveProperty('priority')
expect(historyItem.prompt).toHaveProperty('prompt_id')
expect(historyItem.prompt).toHaveProperty('extra_data')
expect(typeof historyItem.prompt.priority).toBe('number')
expect(typeof historyItem.prompt.prompt_id).toBe('string')
expect(historyItem.prompt.extra_data).toHaveProperty('client_id')
})
test('Can load workflow from history using history_v2 endpoint', async ({
comfyPage
}) => {
// Simple mock workflow for testing
const mockWorkflow = {
version: 0.4,
nodes: [{ id: 1, type: 'TestNode', pos: [100, 100], size: [200, 100] }],
links: [],
groups: [],
config: {},
extra: {}
}
// Set up history with workflow data
await comfyPage
.setupHistory()
.withTask(['example.webp'], 'images', {
prompt: {
priority: 0,
prompt_id: TEST_PROMPT_ID,
extra_data: {
client_id: TEST_CLIENT_ID,
extra_pnginfo: { workflow: mockWorkflow }
}
}
})
.setupRoutes()
// Load initial workflow to clear canvas
await comfyPage.loadWorkflow('simple_slider')
await comfyPage.nextFrame()
// Load workflow from history
const loadResult = await comfyPage.page.evaluate(async (promptId) => {
try {
const workflow =
await window['app'].api.getWorkflowFromHistory(promptId)
if (workflow) {
await window['app'].loadGraphData(workflow)
return { success: true }
}
return { success: false, error: 'No workflow found' }
} catch (error) {
console.error('Failed to load workflow from history:', error)
return { success: false, error: error.message }
}
}, TEST_PROMPT_ID)
expect(loadResult.success).toBe(true)
// Verify workflow loaded correctly
await comfyPage.nextFrame()
const nodeInfo = await comfyPage.page.evaluate(() => {
try {
const graph = window['app'].graph
return {
success: true,
nodeCount: graph.nodes?.length || 0,
firstNodeType: graph.nodes?.[0]?.type || null
}
} catch (error) {
return { success: false, error: error.message }
}
})
expect(nodeInfo.success).toBe(true)
expect(nodeInfo.nodeCount).toBe(1)
expect(nodeInfo.firstNodeType).toBe('TestNode')
})
test('Handles missing workflow data gracefully', async ({ comfyPage }) => {
// Set up empty history routes
await comfyPage.setupHistory().setupRoutes()
// Test loading from history with invalid prompt_id
const result = await comfyPage.page.evaluate(async () => {
try {
const workflow =
await window['app'].api.getWorkflowFromHistory('invalid-id')
return { success: true, workflow }
} catch (error) {
console.error('Expected error for invalid prompt_id:', error)
return { success: false, error: error.message }
}
})
// Should handle gracefully without throwing
expect(result.success).toBe(true)
expect(result.workflow).toBeNull()
})
})

View File

@@ -187,12 +187,14 @@ test.describe('Workflows sidebar', () => {
test('Can save workflow as with same name', async ({ comfyPage }) => {
await comfyPage.menu.topbar.saveWorkflow('workflow5.json')
await comfyPage.nextFrame()
expect(await comfyPage.menu.workflowsTab.getOpenedWorkflowNames()).toEqual([
'workflow5.json'
])
await comfyPage.menu.topbar.saveWorkflowAs('workflow5.json')
await comfyPage.confirmDialog.click('overwrite')
await comfyPage.nextFrame()
expect(await comfyPage.menu.workflowsTab.getOpenedWorkflowNames()).toEqual([
'workflow5.json'
])
@@ -317,25 +319,6 @@ test.describe('Workflows sidebar', () => {
])
})
test('Can duplicate workflow from context menu', async ({ comfyPage }) => {
await comfyPage.setupWorkflowsDirectory({
'workflow1.json': 'default.json'
})
const { workflowsTab } = comfyPage.menu
await workflowsTab.open()
await workflowsTab
.getPersistedItem('workflow1.json')
.click({ button: 'right' })
await comfyPage.clickContextMenuItem('Duplicate')
expect(await workflowsTab.getOpenedWorkflowNames()).toEqual([
'*Unsaved Workflow.json',
'*workflow1 (Copy).json'
])
})
test('Can drop workflow from workflows sidebar', async ({ comfyPage }) => {
await comfyPage.setupWorkflowsDirectory({
'workflow1.json': 'default.json'

View File

@@ -14,10 +14,7 @@ export default [
ignores: [
'src/scripts/*',
'src/extensions/core/*',
'src/types/vue-shim.d.ts',
// Generated files that don't need linting
'src/types/comfyRegistryTypes.ts',
'src/types/generatedManagerTypes.ts'
'src/types/vue-shim.d.ts'
]
},
{

21
package-lock.json generated
View File

@@ -30,12 +30,12 @@
"axios": "^1.8.2",
"dompurify": "^3.2.5",
"dotenv": "^16.4.5",
"es-toolkit": "^1.39.9",
"extendable-media-recorder": "^9.2.27",
"extendable-media-recorder-wav-encoder": "^7.0.129",
"firebase": "^11.6.0",
"fuse.js": "^7.0.0",
"jsondiffpatch": "^0.6.0",
"lodash": "^4.17.21",
"loglevel": "^1.9.2",
"marked": "^15.0.11",
"pinia": "^2.1.7",
@@ -62,6 +62,7 @@
"@trivago/prettier-plugin-sort-imports": "^5.2.0",
"@types/dompurify": "^3.0.5",
"@types/fs-extra": "^11.0.4",
"@types/lodash": "^4.17.6",
"@types/node": "^20.14.8",
"@types/semver": "^7.7.0",
"@types/three": "^0.169.0",
@@ -4886,6 +4887,12 @@
"integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==",
"license": "MIT"
},
"node_modules/@types/lodash": {
"version": "4.17.6",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.6.tgz",
"integrity": "sha512-OpXEVoCKSS3lQqjx9GGGOapBeuW5eUboYHRlHP9urXPX25IKZ6AnP5ZRxtVf63iieUbsHxLn8NQ5Nlftc6yzAA==",
"dev": true
},
"node_modules/@types/markdown-it": {
"version": "14.1.2",
"resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz",
@@ -7991,15 +7998,6 @@
"node": ">= 0.4"
}
},
"node_modules/es-toolkit": {
"version": "1.39.9",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.39.9.tgz",
"integrity": "sha512-9OtbkZmTA2Qc9groyA1PUNeb6knVTkvB2RSdr/LcJXDL8IdEakaxwXLHXa7VX/Wj0GmdMJPR3WhnPGhiP3E+qg==",
"workspaces": [
"docs",
"benchmarks"
]
},
"node_modules/esbuild": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
@@ -11452,8 +11450,7 @@
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"node_modules/lodash-es": {
"version": "4.17.21",

View File

@@ -21,10 +21,8 @@
"test:component": "vitest run src/components/",
"prepare": "husky || true",
"preview": "vite preview",
"lint": "eslint src --cache",
"lint:fix": "eslint src --cache --fix",
"lint:no-cache": "eslint src",
"lint:fix:no-cache": "eslint src --fix",
"lint": "eslint src",
"lint:fix": "eslint src --fix",
"knip": "knip",
"locale": "lobe-i18n locale",
"collect-i18n": "playwright test --config=playwright.i18n.config.ts",
@@ -41,6 +39,7 @@
"@trivago/prettier-plugin-sort-imports": "^5.2.0",
"@types/dompurify": "^3.0.5",
"@types/fs-extra": "^11.0.4",
"@types/lodash": "^4.17.6",
"@types/node": "^20.14.8",
"@types/semver": "^7.7.0",
"@types/three": "^0.169.0",
@@ -99,12 +98,12 @@
"axios": "^1.8.2",
"dompurify": "^3.2.5",
"dotenv": "^16.4.5",
"es-toolkit": "^1.39.9",
"extendable-media-recorder": "^9.2.27",
"extendable-media-recorder-wav-encoder": "^7.0.129",
"firebase": "^11.6.0",
"fuse.js": "^7.0.0",
"jsondiffpatch": "^0.6.0",
"lodash": "^4.17.21",
"loglevel": "^1.9.2",
"marked": "^15.0.11",
"pinia": "^2.1.7",

View File

@@ -51,7 +51,7 @@ const template = await fetch('/templates/default.json')
## General Guidelines
- Use es-toolkit for utility functions
- Use lodash for utility functions
- Implement proper TypeScript types
- Follow Vue 3 composition API style guide
- Use vue-i18n for ALL user-facing strings in `src/locales/en/main.json`

View File

@@ -20,7 +20,7 @@ import {
useLocalStorage,
watchDebounced
} from '@vueuse/core'
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import Panel from 'primevue/panel'
import { Ref, computed, inject, nextTick, onMounted, ref, watch } from 'vue'

View File

@@ -42,7 +42,7 @@
</template>
<script setup lang="ts" generic="TFilter extends SearchFilter">
import { debounce } from 'es-toolkit/compat'
import { debounce } from 'lodash'
import Button from 'primevue/button'
import IconField from 'primevue/iconfield'
import InputIcon from 'primevue/inputicon'

View File

@@ -16,7 +16,7 @@
<script setup lang="ts" generic="T">
import { useElementSize, useScroll, whenever } from '@vueuse/core'
import { clamp, debounce } from 'es-toolkit/compat'
import { clamp, debounce } from 'lodash'
import { type CSSProperties, computed, onBeforeUnmount, ref, watch } from 'vue'
type GridState = {

View File

@@ -169,8 +169,8 @@ import { Form, FormField, type FormSubmitEvent } from '@primevue/forms'
import { zodResolver } from '@primevue/forms/resolvers/zod'
import type { CaptureContext, User } from '@sentry/core'
import { captureMessage } from '@sentry/core'
import _ from 'es-toolkit/compat'
import { cloneDeep } from 'es-toolkit/compat'
import _ from 'lodash'
import cloneDeep from 'lodash/cloneDeep'
import Button from 'primevue/button'
import Checkbox from 'primevue/checkbox'
import Dropdown from 'primevue/dropdown'

View File

@@ -93,7 +93,7 @@
<script setup lang="ts">
import { whenever } from '@vueuse/core'
import { merge } from 'es-toolkit/compat'
import { merge } from 'lodash'
import Button from 'primevue/button'
import {
computed,

View File

@@ -12,7 +12,7 @@ import { useComfyManagerStore } from '@/stores/comfyManagerStore'
import PackEnableToggle from './PackEnableToggle.vue'
// Mock debounce to execute immediately
vi.mock('es-toolkit/compat', () => ({
vi.mock('lodash', () => ({
debounce: <T extends (...args: any[]) => any>(fn: T) => fn
}))

View File

@@ -10,7 +10,7 @@
</template>
<script setup lang="ts">
import { debounce } from 'es-toolkit/compat'
import { debounce } from 'lodash'
import ToggleSwitch from 'primevue/toggleswitch'
import { computed, ref } from 'vue'

View File

@@ -57,7 +57,7 @@
</template>
<script setup lang="ts">
import { stubTrue } from 'es-toolkit/compat'
import { stubTrue } from 'lodash'
import AutoComplete, {
AutoCompleteOptionSelectEvent
} from 'primevue/autocomplete'

View File

@@ -15,9 +15,9 @@
<script setup lang="ts">
import Tag from 'primevue/tag'
// Global variable from vite build defined in global.d.ts
// eslint-disable-next-line no-undef
const isStaging = !__USE_PROD_CONFIG__
import { isProductionEnvironment } from '@/config/environment'
const isStaging = !isProductionEnvironment()
</script>
<style scoped>

View File

@@ -1,20 +1,6 @@
<template>
<Button
v-if="isUnpackVisible"
v-tooltip.top="{
value: t('commands.Comfy_Graph_UnpackSubgraph.label'),
showDelay: 1000
}"
severity="secondary"
text
@click="() => commandStore.execute('Comfy.Graph.UnpackSubgraph')"
>
<template #icon>
<i-lucide:expand />
</template>
</Button>
<Button
v-else-if="isConvertVisible"
v-show="isVisible"
v-tooltip.top="{
value: t('commands.Comfy_Graph_ConvertToSubgraph.label'),
showDelay: 1000
@@ -34,7 +20,6 @@ import Button from 'primevue/button'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { LGraphGroup, SubgraphNode } from '@/lib/litegraph/src/litegraph'
import { useCommandStore } from '@/stores/commandStore'
import { useCanvasStore } from '@/stores/graphStore'
@@ -42,31 +27,7 @@ const { t } = useI18n()
const commandStore = useCommandStore()
const canvasStore = useCanvasStore()
const isUnpackVisible = computed(() => {
return (
canvasStore.selectedItems?.length === 1 &&
canvasStore.selectedItems[0] instanceof SubgraphNode
)
})
const isConvertVisible = computed(() => {
const items = canvasStore.selectedItems
if (!items || items.length === 0) {
return false
}
// Unpack button takes precedence for single subgraph node
if (items.length === 1 && items[0] instanceof SubgraphNode) {
return false
}
// Hide if ALL selected items are groups
const allAreGroups = items.every((item) => item instanceof LGraphGroup)
if (allAreGroups) {
return false
}
// Otherwise, show it, assuming there's some selection
const isVisible = computed(() => {
return (
canvasStore.groupSelected ||
canvasStore.rerouteSelected ||

View File

@@ -82,7 +82,7 @@ https://github.com/Nuked88/ComfyUI-N-Sidebar/blob/7ae7da4a9761009fb6629bc04c6830
</template>
<script setup lang="ts">
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { computed } from 'vue'
import type { ComfyNodeDef as ComfyNodeDefV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'

View File

@@ -106,8 +106,8 @@ import NoResultsPlaceholder from '@/components/common/NoResultsPlaceholder.vue'
import VirtualGrid from '@/components/common/VirtualGrid.vue'
import { ComfyNode } from '@/schemas/comfyWorkflowSchema'
import { api } from '@/scripts/api'
import { app } from '@/scripts/app'
import { useLitegraphService } from '@/services/litegraphService'
import { useWorkflowService } from '@/services/workflowService'
import { useCommandStore } from '@/stores/commandStore'
import {
ResultItemImpl,
@@ -126,6 +126,7 @@ const toast = useToast()
const queueStore = useQueueStore()
const settingStore = useSettingStore()
const commandStore = useCommandStore()
const workflowService = useWorkflowService()
const { t } = useI18n()
// Expanded view: show all outputs in a flat list.
@@ -208,8 +209,16 @@ const menuItems = computed<MenuItem[]>(() => {
{
label: t('g.loadWorkflow'),
icon: 'pi pi-file-export',
command: () => menuTargetTask.value?.loadWorkflow(app),
disabled: !menuTargetTask.value?.workflow
command: () => {
if (menuTargetTask.value) {
void workflowService.loadTaskWorkflow(menuTargetTask.value)
}
},
disabled: !(
menuTargetTask.value?.workflow ||
(menuTargetTask.value?.isHistory &&
menuTargetTask.value?.prompt.prompt_id)
)
},
{
label: t('g.goToNode'),

View File

@@ -265,14 +265,6 @@ const renderTreeNode = (
const workflow = node.data
await workflowService.insertWorkflow(workflow)
}
},
{
label: t('g.duplicate'),
icon: 'pi pi-file-export',
command: async () => {
const workflow = node.data
await workflowService.duplicateWorkflow(workflow)
}
}
]
},

View File

@@ -1,7 +1,7 @@
import { FitAddon } from '@xterm/addon-fit'
import { Terminal } from '@xterm/xterm'
import '@xterm/xterm/css/xterm.css'
import { debounce } from 'es-toolkit/compat'
import { debounce } from 'lodash'
import { Ref, markRaw, onMounted, onUnmounted } from 'vue'
export function useTerminal(element: Ref<HTMLElement | undefined>) {

View File

@@ -1,5 +1,5 @@
import { useMutationObserver, useResizeObserver } from '@vueuse/core'
import { debounce } from 'es-toolkit/compat'
import { debounce } from 'lodash'
import { readonly, ref } from 'vue'
/**

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { computed, onMounted, watch } from 'vue'
import { useNodePricing } from '@/composables/node/useNodePricing'

View File

@@ -418,12 +418,7 @@ const apiNodeCosts: Record<string, { displayPrice: string | PricingFunction }> =
const modeValue = String(modeWidget.value)
// Pricing matrix from CSV data based on mode string content
if (modeValue.includes('v2-1-master')) {
if (modeValue.includes('10s')) {
return '$2.80/Run' // price is the same as for v2-master model
}
return '$1.40/Run' // price is the same as for v2-master model
} else if (modeValue.includes('v2-master')) {
if (modeValue.includes('v2-master')) {
if (modeValue.includes('10s')) {
return '$2.80/Run'
}
@@ -563,32 +558,6 @@ const apiNodeCosts: Record<string, { displayPrice: string | PricingFunction }> =
MinimaxTextToVideoNode: {
displayPrice: '$0.43/Run'
},
MinimaxHailuoVideoNode: {
displayPrice: (node: LGraphNode): string => {
const resolutionWidget = node.widgets?.find(
(w) => w.name === 'resolution'
) as IComboWidget
const durationWidget = node.widgets?.find(
(w) => w.name === 'duration'
) as IComboWidget
if (!resolutionWidget || !durationWidget) {
return '$0.28-0.56/Run (varies with resolution & duration)'
}
const resolution = String(resolutionWidget.value)
const duration = String(durationWidget.value)
if (resolution.includes('768P')) {
if (duration.includes('6')) return '$0.28/Run'
if (duration.includes('10')) return '$0.56/Run'
} else if (resolution.includes('1080P')) {
if (duration.includes('6')) return '$0.49/Run'
}
return '$0.43/Run' // default median
}
},
OpenAIDalle2: {
displayPrice: (node: LGraphNode): string => {
const sizeWidget = node.widgets?.find(
@@ -1309,13 +1278,9 @@ const apiNodeCosts: Record<string, { displayPrice: string | PricingFunction }> =
// Google Veo video generation
if (model.includes('veo-2.0')) {
return '$0.5/second'
} else if (model.includes('gemini-2.5-flash-preview-04-17')) {
return '$0.0003/$0.0025 per 1K tokens'
} else if (model.includes('gemini-2.5-flash')) {
return '$0.0003/$0.0025 per 1K tokens'
} else if (model.includes('gemini-2.5-pro-preview-05-06')) {
return '$0.00125/$0.01 per 1K tokens'
} else if (model.includes('gemini-2.5-pro')) {
return '$0.00016/$0.0006 per 1K tokens'
} else if (model.includes('gemini-2.5-flash-preview-04-17')) {
return '$0.00125/$0.01 per 1K tokens'
}
// For other Gemini models, show token-based pricing info
@@ -1393,7 +1358,6 @@ export const useNodePricing = () => {
KlingDualCharacterVideoEffectNode: ['mode', 'model_name', 'duration'],
KlingSingleImageVideoEffectNode: ['effect_scene'],
KlingStartEndFrameNode: ['mode', 'model_name', 'duration'],
MinimaxHailuoVideoNode: ['resolution', 'duration'],
OpenAIDalle3: ['size', 'quality'],
OpenAIDalle2: ['size', 'n'],
OpenAIGPTImage1: ['quality', 'n'],

View File

@@ -1,4 +1,4 @@
import { groupBy } from 'es-toolkit/compat'
import { groupBy } from 'lodash'
import { computed, onMounted } from 'vue'
import { useWorkflowPacks } from '@/composables/nodePack/useWorkflowPacks'

View File

@@ -21,7 +21,6 @@ import { useWorkflowService } from '@/services/workflowService'
import type { ComfyCommand } from '@/stores/commandStore'
import { useExecutionStore } from '@/stores/executionStore'
import { useCanvasStore, useTitleEditorStore } from '@/stores/graphStore'
import { useNodeOutputStore } from '@/stores/imagePreviewStore'
import { useQueueSettingsStore, useQueueStore } from '@/stores/queueStore'
import { useSettingStore } from '@/stores/settingStore'
import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore'
@@ -798,22 +797,6 @@ export function useCoreCommands(): ComfyCommand[] {
canvas.select(node)
}
},
{
id: 'Comfy.Graph.UnpackSubgraph',
icon: 'pi pi-sitemap',
label: 'Unpack the selected Subgraph',
versionAdded: '1.20.1',
category: 'essentials' as const,
function: () => {
const canvas = canvasStore.getCanvas()
const graph = canvas.subgraph ?? canvas.graph
if (!graph) throw new TypeError('Canvas has no graph or subgraph set.')
const subgraphNode = app.canvas.selectedItems.values().next().value
useNodeOutputStore().revokeSubgraphPreviews(subgraphNode)
graph.unpackSubgraph(subgraphNode)
}
},
{
id: 'Workspace.ToggleBottomPanel.Shortcuts',
icon: 'pi pi-key',

View File

@@ -1,5 +1,5 @@
import { watchDebounced } from '@vueuse/core'
import { orderBy } from 'es-toolkit/compat'
import { orderBy } from 'lodash'
import { computed, ref, watch } from 'vue'
import { DEFAULT_PAGE_SIZE } from '@/constants/searchConstants'

View File

@@ -1,4 +1,3 @@
import { tryOnScopeDispose } from '@vueuse/core'
import { computed, watch } from 'vue'
import { api } from '@/scripts/api'
@@ -89,11 +88,6 @@ export function useWorkflowPersistence() {
)
api.addEventListener('graphChanged', persistCurrentWorkflow)
// Clean up event listener when component unmounts
tryOnScopeDispose(() => {
api.removeEventListener('graphChanged', persistCurrentWorkflow)
})
// Restore workflow tabs states
const openWorkflows = computed(() => workflowStore.openWorkflows)
const activeWorkflow = computed(() => workflowStore.activeWorkflow)

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
import type { INumericWidget } from '@/lib/litegraph/src/types/widgets'

View File

@@ -5,6 +5,7 @@ import { LGraphNode } from '@/lib/litegraph/src/litegraph'
import { IWidget } from '@/lib/litegraph/src/litegraph'
import type { RemoteWidgetConfig } from '@/schemas/nodeDefSchema'
import { api } from '@/scripts/api'
import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'
const MAX_RETRIES = 5
const TIMEOUT = 4096
@@ -58,10 +59,21 @@ const fetchData = async (
controller: AbortController
) => {
const { route, response_key, query_params, timeout = TIMEOUT } = config
// Get auth header from Firebase
const authStore = useFirebaseAuthStore()
const authHeader = await authStore.getAuthHeader()
const headers: Record<string, string> = {}
if (authHeader) {
Object.assign(headers, authHeader)
}
const res = await axios.get(route, {
params: query_params,
signal: controller.signal,
timeout
timeout,
headers
})
return response_key ? res.data[response_key] : res.data
}

View File

@@ -1,7 +1,9 @@
export const COMFY_API_BASE_URL = __USE_PROD_CONFIG__
import { isProductionEnvironment } from './environment'
export const COMFY_API_BASE_URL = isProductionEnvironment()
? 'https://api.comfy.org'
: 'https://stagingapi.comfy.org'
export const COMFY_PLATFORM_BASE_URL = __USE_PROD_CONFIG__
export const COMFY_PLATFORM_BASE_URL = isProductionEnvironment()
? 'https://platform.comfy.org'
: 'https://stagingplatform.comfy.org'

18
src/config/environment.ts Normal file
View File

@@ -0,0 +1,18 @@
/**
* Runtime environment configuration that determines if we're in production or staging
* based on the hostname. Replaces the build-time __USE_PROD_CONFIG__ constant.
*/
/**
* Checks if the application is running in production environment
* @returns true if hostname is cloud.comfy.org (production), false otherwise (staging)
*/
export function isProductionEnvironment(): boolean {
// In SSR/Node.js environments or during build, use the environment variable
if (typeof window === 'undefined') {
return process.env.USE_PROD_CONFIG === 'true'
}
// In browser, check the hostname
return window.location.hostname === 'cloud.comfy.org'
}

View File

@@ -1,5 +1,7 @@
import { FirebaseOptions } from 'firebase/app'
import { isProductionEnvironment } from './environment'
const DEV_CONFIG: FirebaseOptions = {
apiKey: 'AIzaSyDa_YMeyzV0SkVe92vBZ1tVikWBmOU5KVE',
authDomain: 'dreamboothy-dev.firebaseapp.com',
@@ -23,6 +25,6 @@ const PROD_CONFIG: FirebaseOptions = {
}
// To test with prod config while using dev server, set USE_PROD_CONFIG=true in .env
export const FIREBASE_CONFIG: FirebaseOptions = __USE_PROD_CONFIG__
export const FIREBASE_CONFIG: FirebaseOptions = isProductionEnvironment()
? PROD_CONFIG
: DEV_CONFIG

View File

@@ -1,5 +1,5 @@
import { debounce } from 'es-toolkit/compat'
import _ from 'es-toolkit/compat'
import { debounce } from 'lodash'
import _ from 'lodash'
import { t } from '@/i18n'

View File

@@ -43,19 +43,6 @@ export class CanvasPointer {
/** {@link maxClickDrift} squared. Used to calculate click drift without `sqrt`. */
static #maxClickDrift2 = this.#maxClickDrift ** 2
/** Assume that "wheel" events with both deltaX and deltaY less than this value are trackpad gestures. */
static trackpadThreshold = 60
/**
* The minimum time between "wheel" events to allow switching between trackpad
* and mouse modes.
*
* This prevents trackpad "flick" panning from registering as regular mouse wheel.
* After a flick gesture is complete, the automatic wheel events are sent with
* reduced frequency, but much higher deltaX and deltaY values.
*/
static trackpadMaxGap = 200
/** The element this PointerState should capture input against when dragging. */
element: Element
/** Pointer ID used by drag capture. */
@@ -90,9 +77,6 @@ export class CanvasPointer {
/** The last pointerup event for the primary button */
eUp?: CanvasPointerEvent
/** The last pointermove event that was treated as a trackpad gesture. */
lastTrackpadEvent?: WheelEvent
/**
* If set, as soon as the mouse moves outside the click drift threshold, this action is run once.
* @param pointer [DEPRECATED] This parameter will be removed in a future release.
@@ -273,35 +257,6 @@ export class CanvasPointer {
delete this.onDragStart
}
/**
* Checks if the given wheel event is part of a continued trackpad gesture.
* @param e The wheel event to check
* @returns `true` if the event is part of a continued trackpad gesture, otherwise `false`
*/
#isContinuationOfGesture(e: WheelEvent): boolean {
const { lastTrackpadEvent } = this
if (!lastTrackpadEvent) return false
return (
e.timeStamp - lastTrackpadEvent.timeStamp < CanvasPointer.trackpadMaxGap
)
}
/**
* Checks if the given wheel event is part of a trackpad gesture.
* @param e The wheel event to check
* @returns `true` if the event is part of a trackpad gesture, otherwise `false`
*/
isTrackpadGesture(e: WheelEvent): boolean {
if (this.#isContinuationOfGesture(e)) {
this.lastTrackpadEvent = e
return true
}
const threshold = CanvasPointer.trackpadThreshold
return Math.abs(e.deltaX) < threshold && Math.abs(e.deltaY) < threshold
}
/**
* Resets the state of this {@link CanvasPointer} instance.
*

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import type { Point, Rect } from './interfaces'
import { LGraphCanvas } from './litegraph'

View File

@@ -1,4 +1,4 @@
import { toString } from 'es-toolkit/compat'
import { toString } from 'lodash'
import {
SUBGRAPH_INPUT_ID,
@@ -1664,254 +1664,6 @@ export class LGraph
return { subgraph, node: subgraphNode as SubgraphNode }
}
unpackSubgraph(subgraphNode: SubgraphNode) {
if (!(subgraphNode instanceof SubgraphNode))
throw new Error('Can only unpack Subgraph Nodes')
this.beforeChange()
const center = [0, 0]
for (const node of subgraphNode.subgraph.nodes) {
center[0] += node.pos[0] + node.size[0] / 2
center[1] += node.pos[1] + node.size[1] / 2
}
center[0] /= subgraphNode.subgraph.nodes.length
center[1] /= subgraphNode.subgraph.nodes.length
const offsetX = subgraphNode.pos[0] - center[0] + subgraphNode.size[0] / 2
const offsetY = subgraphNode.pos[1] - center[1] + subgraphNode.size[1] / 2
const movedNodes = multiClone(subgraphNode.subgraph.nodes)
const nodeIdMap = new Map<NodeId, NodeId>()
for (const n_info of movedNodes) {
const node = LiteGraph.createNode(String(n_info.type), n_info.title)
if (!node) {
throw new Error('Node not found')
}
nodeIdMap.set(n_info.id, ++this.last_node_id)
node.id = this.last_node_id
n_info.id = this.last_node_id
this.add(node, true)
node.configure(n_info)
node.pos[0] += offsetX
node.pos[1] += offsetY
for (const input of node.inputs) {
input.link = null
}
}
//cleanup reoute.linkIds now, but leave link.parentIds dangling
for (const islot of subgraphNode.inputs) {
if (!islot.link) continue
const link = this.links.get(islot.link)
if (!link) {
console.warn('Broken link', islot, islot.link)
continue
}
for (const reroute of LLink.getReroutes(this, link)) {
reroute.linkIds.delete(link.id)
}
}
for (const oslot of subgraphNode.outputs) {
for (const linkId of oslot.links ?? []) {
const link = this.links.get(linkId)
if (!link) {
console.warn('Broken link', oslot, linkId)
continue
}
for (const reroute of LLink.getReroutes(this, link)) {
reroute.linkIds.delete(link.id)
}
}
}
const newLinks: [
NodeId,
number,
NodeId,
number,
LinkId,
RerouteId | undefined,
RerouteId | undefined,
boolean
][] = []
for (const [, link] of subgraphNode.subgraph._links) {
let externalParentId: RerouteId | undefined
if (link.origin_id === SUBGRAPH_INPUT_ID) {
const outerLinkId = subgraphNode.inputs[link.origin_slot].link
if (!outerLinkId) {
console.error('Missing Link ID when unpacking')
continue
}
const outerLink = this.links[outerLinkId]
link.origin_id = outerLink.origin_id
link.origin_slot = outerLink.origin_slot
externalParentId = outerLink.parentId
} else {
const origin_id = nodeIdMap.get(link.origin_id)
if (!origin_id) {
console.error('Missing Link ID when unpacking')
continue
}
link.origin_id = origin_id
}
if (link.target_id === SUBGRAPH_OUTPUT_ID) {
for (const linkId of subgraphNode.outputs[link.target_slot].links ??
[]) {
const sublink = this.links[linkId]
newLinks.push([
link.origin_id,
link.origin_slot,
sublink.target_id,
sublink.target_slot,
link.id,
link.parentId,
sublink.parentId,
true
])
sublink.parentId = undefined
}
continue
} else {
const target_id = nodeIdMap.get(link.target_id)
if (!target_id) {
console.error('Missing Link ID when unpacking')
continue
}
link.target_id = target_id
}
newLinks.push([
link.origin_id,
link.origin_slot,
link.target_id,
link.target_slot,
link.id,
link.parentId,
externalParentId,
false
])
}
this.remove(subgraphNode)
this.subgraphs.delete(subgraphNode.subgraph.id)
const linkIdMap = new Map<LinkId, LinkId[]>()
for (const newLink of newLinks) {
let created: LLink | null | undefined
if (newLink[0] == SUBGRAPH_INPUT_ID) {
if (!(this instanceof Subgraph)) {
console.error('Ignoring link to subgraph outside subgraph')
continue
}
const tnode = this._nodes_by_id[newLink[2]]
created = this.inputNode.slots[newLink[1]].connect(
tnode.inputs[newLink[3]],
tnode
)
} else if (newLink[2] == SUBGRAPH_OUTPUT_ID) {
if (!(this instanceof Subgraph)) {
console.error('Ignoring link to subgraph outside subgraph')
continue
}
const tnode = this._nodes_by_id[newLink[0]]
created = this.outputNode.slots[newLink[3]].connect(
tnode.outputs[newLink[1]],
tnode
)
} else {
created = this._nodes_by_id[newLink[0]].connect(
newLink[1],
this._nodes_by_id[newLink[2]],
newLink[3]
)
}
if (!created) {
console.error('Failed to create link')
continue
}
//This is a little unwieldy since Map.has isn't a type guard
const linkIds = linkIdMap.get(newLink[4]) ?? []
linkIds.push(created.id)
if (!linkIdMap.has(newLink[4])) {
linkIdMap.set(newLink[4], linkIds)
}
newLink[4] = created.id
}
const rerouteIdMap = new Map<RerouteId, RerouteId>()
for (const reroute of subgraphNode.subgraph.reroutes.values()) {
if (
reroute.parentId !== undefined &&
rerouteIdMap.get(reroute.parentId) === undefined
) {
console.error('Missing Parent ID')
}
const migratedReroute = new Reroute(++this.state.lastRerouteId, this, [
reroute.pos[0] + offsetX,
reroute.pos[1] + offsetY
])
rerouteIdMap.set(reroute.id, migratedReroute.id)
this.reroutes.set(migratedReroute.id, migratedReroute)
}
//iterate over newly created links to update reroute parentIds
for (const newLink of newLinks) {
const linkInstance = this.links.get(newLink[4])
if (!linkInstance) {
continue
}
let instance: Reroute | LLink | undefined = linkInstance
let parentId: RerouteId | undefined = newLink[6]
if (newLink[7]) {
parentId = newLink[6]
//TODO: recursion check/helper method? Probably exists, but wouldn't mesh with the reference tracking used by this implementation
while (parentId) {
instance.parentId = parentId
instance = this.reroutes.get(parentId)
if (!instance) throw new Error('Broken Id link when unpacking')
if (instance.linkIds.has(linkInstance.id))
throw new Error('Infinite parentId loop')
instance.linkIds.add(linkInstance.id)
parentId = instance.parentId
}
}
parentId = newLink[5]
while (parentId) {
const migratedId = rerouteIdMap.get(parentId)
if (!migratedId) throw new Error('Broken Id link when unpacking')
instance.parentId = migratedId
instance = this.reroutes.get(migratedId)
if (!instance) throw new Error('Broken Id link when unpacking')
if (instance.linkIds.has(linkInstance.id))
throw new Error('Infinite parentId loop')
instance.linkIds.add(linkInstance.id)
const oldReroute = subgraphNode.subgraph.reroutes.get(parentId)
if (!oldReroute) throw new Error('Broken Id link when unpacking')
parentId = oldReroute.parentId
}
if (!newLink[7]) {
parentId = newLink[6]
while (parentId) {
instance.parentId = parentId
instance = this.reroutes.get(parentId)
if (!instance) throw new Error('Broken Id link when unpacking')
if (instance.linkIds.has(linkInstance.id))
throw new Error('Infinite parentId loop')
instance.linkIds.add(linkInstance.id)
parentId = instance.parentId
}
}
}
const nodes: LGraphNode[] = []
for (const nodeId of nodeIdMap.values()) {
const node = this._nodes_by_id[nodeId]
nodes.push(node)
node._setConcreteSlots()
node.arrange()
}
const reroutes = [...rerouteIdMap.values()]
.map((i) => this.reroutes.get(i))
.filter((x): x is Reroute => !!x)
this.canvasAction((c) => c.selectItems([...nodes, ...reroutes]))
this.afterChange()
}
/**
* Resolve a path of subgraph node IDs into a list of subgraph nodes.
* Not intended to be run from subgraphs.

View File

@@ -1,4 +1,4 @@
import { toString } from 'es-toolkit/compat'
import { toString } from 'lodash'
import { LinkConnector } from '@/lib/litegraph/src/canvas/LinkConnector'
@@ -3456,6 +3456,10 @@ export class LGraphCanvas
processMouseWheel(e: WheelEvent): void {
if (!this.graph || !this.allow_dragcanvas) return
// TODO: Mouse wheel zoom rewrite
// @ts-expect-error wheelDeltaY is non-standard property on WheelEvent
const delta = e.wheelDeltaY ?? e.detail * -60
this.adjustMouseEvent(e)
const pos: Point = [e.clientX, e.clientY]
@@ -3463,34 +3467,35 @@ export class LGraphCanvas
let { scale } = this.ds
// Detect if this is a trackpad gesture or mouse wheel
const isTrackpad = this.pointer.isTrackpadGesture(e)
if (e.ctrlKey || LiteGraph.canvasNavigationMode === 'legacy') {
// Legacy mode or standard mode with ctrl - use wheel for zoom
if (isTrackpad) {
// Trackpad gesture - use smooth scaling
scale *= 1 + e.deltaY * (1 - this.zoom_speed) * 0.18
this.ds.changeScale(scale, [e.clientX, e.clientY], false)
} else {
// Mouse wheel - use stepped scaling
if (e.deltaY < 0) {
scale *= this.zoom_speed
} else if (e.deltaY > 0) {
if (
LiteGraph.canvasNavigationMode === 'legacy' ||
(LiteGraph.canvasNavigationMode === 'standard' && e.ctrlKey)
) {
if (delta > 0) {
scale *= this.zoom_speed
} else if (delta < 0) {
scale *= 1 / this.zoom_speed
}
this.ds.changeScale(scale, [e.clientX, e.clientY])
} else if (
LiteGraph.macTrackpadGestures &&
(!LiteGraph.macGesturesRequireMac || navigator.userAgent.includes('Mac'))
) {
if (e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) {
if (e.deltaY > 0) {
scale *= 1 / this.zoom_speed
} else if (e.deltaY < 0) {
scale *= this.zoom_speed
}
this.ds.changeScale(scale, [e.clientX, e.clientY])
}
} else {
// Standard mode without ctrl - use wheel / gestures to pan
// Trackpads and mice work on significantly different scales
const factor = isTrackpad ? 0.18 : 0.008_333
if (!isTrackpad && e.shiftKey && e.deltaX === 0) {
this.ds.offset[0] -= e.deltaY * (1 + factor) * (1 / scale)
} else if (e.ctrlKey) {
scale *= 1 + e.deltaY * (1 - this.zoom_speed) * 0.18
this.ds.changeScale(scale, [e.clientX, e.clientY], false)
} else if (e.shiftKey) {
this.ds.offset[0] -= e.deltaY * 1.18 * (1 / scale)
} else {
this.ds.offset[0] -= e.deltaX * (1 + factor) * (1 / scale)
this.ds.offset[1] -= e.deltaY * (1 + factor) * (1 / scale)
this.ds.offset[0] -= e.deltaX * 1.18 * (1 / scale)
this.ds.offset[1] -= e.deltaY * 1.18 * (1 / scale)
}
}

View File

@@ -284,7 +284,6 @@ export class LiteGraphGlobal {
]
/**
* @deprecated Removed; has no effect.
* If `true`, mouse wheel events will be interpreted as trackpad gestures.
* Tested on MacBook M4 Pro.
* @default false
@@ -293,7 +292,6 @@ export class LiteGraphGlobal {
macTrackpadGestures: boolean = false
/**
* @deprecated Removed; has no effect.
* If both this setting and {@link macTrackpadGestures} are `true`, trackpad gestures will
* only be enabled when the browser user agent includes "Mac".
* @default true

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import type {
ReadOnlyRect,

View File

@@ -1,4 +1,4 @@
import { pull } from 'es-toolkit/compat'
import { pull } from 'lodash'
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
import { LLink } from '@/lib/litegraph/src/LLink'

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
import { LiteGraph } from '@/lib/litegraph/src/litegraph'

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import type { IKnobWidget } from '@/lib/litegraph/src/types/widgets'
import { getWidgetStep } from '@/lib/litegraph/src/utils/widget'

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import type { ISliderWidget } from '@/lib/litegraph/src/types/widgets'

View File

@@ -1,4 +1,4 @@
import { clamp } from 'es-toolkit/compat'
import { clamp } from 'lodash'
import { beforeEach, describe, expect, vi } from 'vitest'
import { LiteGraphGlobal } from '@/lib/litegraph/src/LiteGraphGlobal'

View File

@@ -1,197 +0,0 @@
import { assert, describe, expect, it } from 'vitest'
import {
ISlotType,
LGraph,
LGraphNode,
LiteGraph
} from '@/lib/litegraph/src/litegraph'
import {
createTestSubgraph,
createTestSubgraphNode
} from './fixtures/subgraphHelpers'
function createNode(
graph: LGraph,
inputs: ISlotType[] = [],
outputs: ISlotType[] = [],
title?: string
) {
const type = JSON.stringify({ inputs, outputs })
if (!LiteGraph.registered_node_types[type]) {
class testnode extends LGraphNode {
constructor(title: string) {
super(title)
let i_count = 0
for (const input of inputs) this.addInput('input_' + i_count++, input)
let o_count = 0
for (const output of outputs)
this.addOutput('output_' + o_count++, output)
}
}
LiteGraph.registered_node_types[type] = testnode
}
const node = LiteGraph.createNode(type, title)
if (!node) {
throw new Error('Failed to create node')
}
graph.add(node)
return node
}
describe('SubgraphConversion', () => {
describe('Subgraph Unpacking Functionality', () => {
it('Should keep interior nodes and links', () => {
const subgraph = createTestSubgraph()
const subgraphNode = createTestSubgraphNode(subgraph)
const graph = subgraphNode.graph
graph.add(subgraphNode)
const node1 = createNode(subgraph, [], ['number'])
const node2 = createNode(subgraph, ['number'])
node1.connect(0, node2, 0)
graph.unpackSubgraph(subgraphNode)
expect(graph.nodes.length).toBe(2)
expect(graph.links.size).toBe(1)
})
it('Should merge boundry links', () => {
const subgraph = createTestSubgraph({
inputs: [{ name: 'value', type: 'number' }],
outputs: [{ name: 'value', type: 'number' }]
})
const subgraphNode = createTestSubgraphNode(subgraph)
const graph = subgraphNode.graph
graph.add(subgraphNode)
const innerNode1 = createNode(subgraph, [], ['number'])
const innerNode2 = createNode(subgraph, ['number'], [])
subgraph.inputNode.slots[0].connect(innerNode2.inputs[0], innerNode2)
subgraph.outputNode.slots[0].connect(innerNode1.outputs[0], innerNode1)
const outerNode1 = createNode(graph, [], ['number'])
const outerNode2 = createNode(graph, ['number'])
outerNode1.connect(0, subgraphNode, 0)
subgraphNode.connect(0, outerNode2, 0)
graph.unpackSubgraph(subgraphNode)
expect(graph.nodes.length).toBe(4)
expect(graph.links.size).toBe(2)
})
it('Should keep reroutes', () => {
const subgraph = createTestSubgraph({
outputs: [{ name: 'value', type: 'number' }]
})
const subgraphNode = createTestSubgraphNode(subgraph)
const graph = subgraphNode.graph
graph.add(subgraphNode)
const inner = createNode(subgraph, [], ['number'])
const innerLink = subgraph.outputNode.slots[0].connect(
inner.outputs[0],
inner
)
assert(innerLink)
const outer = createNode(graph, ['number'])
const outerLink = subgraphNode.connect(0, outer, 0)
assert(outerLink)
subgraph.createReroute([10, 10], innerLink)
graph.createReroute([10, 10], outerLink)
graph.unpackSubgraph(subgraphNode)
expect(graph.reroutes.size).toBe(2)
})
it('Should map reroutes onto split outputs', () => {
const subgraph = createTestSubgraph({
outputs: [
{ name: 'value1', type: 'number' },
{ name: 'value2', type: 'number' }
]
})
const subgraphNode = createTestSubgraphNode(subgraph)
const graph = subgraphNode.graph
graph.add(subgraphNode)
const inner = createNode(subgraph, [], ['number', 'number'])
const innerLink1 = subgraph.outputNode.slots[0].connect(
inner.outputs[0],
inner
)
const innerLink2 = subgraph.outputNode.slots[1].connect(
inner.outputs[1],
inner
)
const outer1 = createNode(graph, ['number'])
const outer2 = createNode(graph, ['number'])
const outer3 = createNode(graph, ['number'])
const outerLink1 = subgraphNode.connect(0, outer1, 0)
assert(innerLink1 && innerLink2 && outerLink1)
subgraphNode.connect(0, outer2, 0)
subgraphNode.connect(1, outer3, 0)
subgraph.createReroute([10, 10], innerLink1)
subgraph.createReroute([10, 20], innerLink2)
graph.createReroute([10, 10], outerLink1)
graph.unpackSubgraph(subgraphNode)
expect(graph.reroutes.size).toBe(3)
expect(graph.links.size).toBe(3)
let linkRefCount = 0
for (const reroute of graph.reroutes.values()) {
linkRefCount += reroute.linkIds.size
}
expect(linkRefCount).toBe(4)
})
it('Should map reroutes onto split inputs', () => {
const subgraph = createTestSubgraph({
inputs: [
{ name: 'value1', type: 'number' },
{ name: 'value2', type: 'number' }
]
})
const subgraphNode = createTestSubgraphNode(subgraph)
const graph = subgraphNode.graph
graph.add(subgraphNode)
const inner1 = createNode(subgraph, ['number', 'number'])
const inner2 = createNode(subgraph, ['number'])
const innerLink1 = subgraph.inputNode.slots[0].connect(
inner1.inputs[0],
inner1
)
const innerLink2 = subgraph.inputNode.slots[1].connect(
inner1.inputs[1],
inner1
)
const innerLink3 = subgraph.inputNode.slots[1].connect(
inner2.inputs[0],
inner2
)
assert(innerLink1 && innerLink2 && innerLink3)
const outer = createNode(graph, [], ['number'])
const outerLink1 = outer.connect(0, subgraphNode, 0)
const outerLink2 = outer.connect(0, subgraphNode, 1)
assert(outerLink1 && outerLink2)
graph.createReroute([10, 10], outerLink1)
graph.createReroute([10, 20], outerLink2)
subgraph.createReroute([10, 10], innerLink1)
graph.unpackSubgraph(subgraphNode)
expect(graph.reroutes.size).toBe(3)
expect(graph.links.size).toBe(3)
let linkRefCount = 0
for (const reroute of graph.reroutes.values()) {
linkRefCount += reroute.linkIds.size
}
expect(linkRefCount).toBe(4)
})
})
})

View File

@@ -299,7 +299,6 @@
"disabling": "جارٍ التعطيل",
"dismiss": "تجاهل",
"download": "تنزيل",
"duplicate": "تكرار",
"edit": "تعديل",
"empty": "فارغ",
"enableAll": "تمكين الكل",

View File

@@ -125,9 +125,6 @@
"Comfy_Graph_ExitSubgraph": {
"label": "Exit Subgraph"
},
"Comfy_Graph_UnpackSubgraph": {
"label": "Unpack the selected Subgraph"
},
"Comfy_Graph_FitGroupToContents": {
"label": "Fit Group To Contents"
},

View File

@@ -145,8 +145,7 @@
"stopRecording": "Stop Recording",
"micPermissionDenied": "Microphone permission denied",
"noAudioRecorded": "No audio recorded",
"nodesRunning": "nodes running",
"duplicate": "Duplicate"
"nodesRunning": "nodes running"
},
"manager": {
"title": "Custom Nodes Manager",

View File

@@ -299,7 +299,6 @@
"disabling": "Deshabilitando",
"dismiss": "Descartar",
"download": "Descargar",
"duplicate": "Duplicar",
"edit": "Editar",
"empty": "Vacío",
"enableAll": "Habilitar todo",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "Advertencia de compatibilidad de versión",
"versionMismatchWarningMessage": "{warning}: {detail} Visita https://docs.comfy.org/installation/update_comfyui#common-update-issues para obtener instrucciones de actualización.",
"videoFailedToLoad": "Falló la carga del video",
"workflow": "Flujo de trabajo",
"duplicate": "Duplicar"
"workflow": "Flujo de trabajo"
},
"graphCanvasMenu": {
"fitView": "Ajustar vista",

View File

@@ -299,7 +299,6 @@
"disabling": "Désactivation",
"dismiss": "Fermer",
"download": "Télécharger",
"duplicate": "Dupliquer",
"edit": "Modifier",
"empty": "Vide",
"enableAll": "Activer tout",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "Avertissement de compatibilité de version",
"versionMismatchWarningMessage": "{warning} : {detail} Consultez https://docs.comfy.org/installation/update_comfyui#common-update-issues pour les instructions de mise à jour.",
"videoFailedToLoad": "Échec du chargement de la vidéo",
"workflow": "Flux de travail",
"duplicate": "Dupliquer"
"workflow": "Flux de travail"
},
"graphCanvasMenu": {
"fitView": "Adapter la vue",

View File

@@ -299,7 +299,6 @@
"disabling": "無効化",
"dismiss": "閉じる",
"download": "ダウンロード",
"duplicate": "複製",
"edit": "編集",
"empty": "空",
"enableAll": "すべて有効にする",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "バージョン互換性の警告",
"versionMismatchWarningMessage": "{warning}: {detail} 更新手順については https://docs.comfy.org/installation/update_comfyui#common-update-issues をご覧ください。",
"videoFailedToLoad": "ビデオの読み込みに失敗しました",
"workflow": "ワークフロー",
"duplicate": "複製"
"workflow": "ワークフロー"
},
"graphCanvasMenu": {
"fitView": "ビューに合わせる",

View File

@@ -299,7 +299,6 @@
"disabling": "비활성화 중",
"dismiss": "닫기",
"download": "다운로드",
"duplicate": "복제",
"edit": "편집",
"empty": "비어 있음",
"enableAll": "모두 활성화",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "버전 호환성 경고",
"versionMismatchWarningMessage": "{warning}: {detail} 업데이트 지침은 https://docs.comfy.org/installation/update_comfyui#common-update-issues 를 방문하세요.",
"videoFailedToLoad": "비디오를 로드하지 못했습니다.",
"workflow": "워크플로",
"duplicate": "복제"
"workflow": "워크플로"
},
"graphCanvasMenu": {
"fitView": "보기 맞춤",

View File

@@ -299,7 +299,6 @@
"disabling": "Отключение",
"dismiss": "Закрыть",
"download": "Скачать",
"duplicate": "Дублировать",
"edit": "Редактировать",
"empty": "Пусто",
"enableAll": "Включить все",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "Предупреждение о несовместимости версий",
"versionMismatchWarningMessage": "{warning}: {detail} Посетите https://docs.comfy.org/installation/update_comfyui#common-update-issues для инструкций по обновлению.",
"videoFailedToLoad": "Не удалось загрузить видео",
"workflow": "Рабочий процесс",
"duplicate": "Дублировать"
"workflow": "Рабочий процесс"
},
"graphCanvasMenu": {
"fitView": "Подгонять под выделенные",

View File

@@ -299,7 +299,6 @@
"disabling": "停用中",
"dismiss": "關閉",
"download": "下載",
"duplicate": "複製",
"edit": "編輯",
"empty": "空",
"enableAll": "全部啟用",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "版本相容性警告",
"versionMismatchWarningMessage": "{warning}{detail} 請參閱 https://docs.comfy.org/installation/update_comfyui#common-update-issues 以取得更新說明。",
"videoFailedToLoad": "無法載入影片",
"workflow": "工作流程",
"duplicate": "複製"
"workflow": "工作流程"
},
"graphCanvasMenu": {
"fitView": "適合視窗",

View File

@@ -299,7 +299,6 @@
"disabling": "禁用中",
"dismiss": "關閉",
"download": "下载",
"duplicate": "复制",
"edit": "编辑",
"empty": "空",
"enableAll": "启用全部",
@@ -403,8 +402,7 @@
"versionMismatchWarning": "版本相容性警告",
"versionMismatchWarningMessage": "{warning}{detail} 請參閱 https://docs.comfy.org/installation/update_comfyui#common-update-issues 以取得更新說明。",
"videoFailedToLoad": "视频加载失败",
"workflow": "工作流",
"duplicate": "复制"
"workflow": "工作流"
},
"graphCanvasMenu": {
"fitView": "适应视图",

View File

@@ -36,11 +36,8 @@ Sentry.init({
dsn: __SENTRY_DSN__,
enabled: __SENTRY_ENABLED__,
release: __COMFYUI_FRONTEND_VERSION__,
integrations: [],
autoSessionTracking: false,
defaultIntegrations: false,
normalizeDepth: 8,
tracesSampleRate: 0
tracesSampleRate: 1.0
})
app.directive('tooltip', Tooltip)
app

View File

@@ -6,11 +6,12 @@ import {
createWebHistory
} from 'vue-router'
import { useDialogService } from '@/services/dialogService'
import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'
import { useUserStore } from '@/stores/userStore'
import { isElectron } from '@/utils/envUtil'
import LayoutDefault from '@/views/layouts/LayoutDefault.vue'
import { useUserStore } from './stores/userStore'
import { isElectron } from './utils/envUtil'
const isFileProtocol = window.location.protocol === 'file:'
const basePath = isElectron() ? '/' : window.location.pathname
@@ -130,4 +131,41 @@ const router = createRouter({
}
})
// Global authentication guard
router.beforeEach(async (_to, _from, next) => {
const authStore = useFirebaseAuthStore()
// Wait for Firebase auth to initialize
if (!authStore.isInitialized) {
await new Promise<void>((resolve) => {
const unwatch = authStore.$subscribe((_, state) => {
if (state.isInitialized) {
unwatch()
resolve()
}
})
})
}
// Check if user is authenticated (Firebase or API key)
const authHeader = await authStore.getAuthHeader()
if (!authHeader) {
// User is not authenticated, show sign-in dialog
const dialogService = useDialogService()
const loginSuccess = await dialogService.showSignInDialog()
if (loginSuccess) {
// After successful login, proceed to the intended route
next()
} else {
// User cancelled login, stay on current page or redirect to home
next(false)
}
} else {
// User is authenticated, proceed
next()
}
})
export default router

View File

@@ -112,6 +112,11 @@ const zDisplayComponentWsMessage = z.object({
props: z.record(z.string(), z.any()).optional()
})
const zNotificationWsMessage = z.object({
value: z.string(),
id: z.string().optional()
})
const zTerminalSize = z.object({
cols: z.number(),
row: z.number()
@@ -153,15 +158,9 @@ export type DisplayComponentWsMessage = z.infer<
export type NodeProgressState = z.infer<typeof zNodeProgressState>
export type ProgressStateWsMessage = z.infer<typeof zProgressStateWsMessage>
export type FeatureFlagsWsMessage = z.infer<typeof zFeatureFlagsWsMessage>
export type NotificationWsMessage = z.infer<typeof zNotificationWsMessage>
// 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
@@ -173,7 +172,6 @@ const zExtraData = z.object({
extra_pnginfo: zExtraPngInfo.optional(),
client_id: z.string()
})
const zOutputsToExecute = z.array(zNodeId)
const zExecutionStartMessage = z.tuple([
z.literal('execution_start'),
@@ -214,13 +212,11 @@ const zStatus = z.object({
messages: z.array(zStatusMessage)
})
const zTaskPrompt = z.tuple([
zQueueIndex,
zPromptId,
zPromptInputs,
zExtraData,
zOutputsToExecute
])
const zTaskPrompt = z.object({
priority: zQueueIndex,
prompt_id: zPromptId,
extra_data: zExtraData
})
const zRunningTaskItem = z.object({
taskType: z.literal('Running'),
@@ -256,6 +252,20 @@ const zHistoryTaskItem = z.object({
meta: zTaskMeta.optional()
})
// Raw history item from backend (without taskType)
const zRawHistoryItem = z.object({
prompt_id: zPromptId,
prompt: zTaskPrompt,
status: zStatus.optional(),
outputs: zTaskOutput,
meta: zTaskMeta.optional()
})
// New API response format: { history: [{prompt_id: "...", ...}, ...] }
const zHistoryResponse = z.object({
history: z.array(zRawHistoryItem)
})
const zTaskItem = z.union([
zRunningTaskItem,
zPendingTaskItem,
@@ -278,6 +288,8 @@ export type RunningTaskItem = z.infer<typeof zRunningTaskItem>
export type PendingTaskItem = z.infer<typeof zPendingTaskItem>
// `/history`
export type HistoryTaskItem = z.infer<typeof zHistoryTaskItem>
export type RawHistoryItem = z.infer<typeof zRawHistoryItem>
export type HistoryResponse = z.infer<typeof zHistoryResponse>
export type TaskItem = z.infer<typeof zTaskItem>
export function validateTaskItem(taskItem: unknown) {

View File

@@ -1,4 +1,5 @@
import axios from 'axios'
import { debounce } from 'lodash'
import defaultClientFeatureFlags from '@/config/clientFeatureFlags.json'
import type {
@@ -13,9 +14,11 @@ import type {
ExecutionSuccessWsMessage,
ExtensionsResponse,
FeatureFlagsWsMessage,
HistoryResponse,
HistoryTaskItem,
LogsRawResponse,
LogsWsMessage,
NotificationWsMessage,
PendingTaskItem,
ProgressStateWsMessage,
ProgressTextWsMessage,
@@ -26,6 +29,7 @@ import type {
StatusWsMessage,
StatusWsMessageStatus,
SystemStats,
TaskPrompt,
User,
UserDataFullInfo
} from '@/schemas/apiSchema'
@@ -35,6 +39,8 @@ import type {
NodeId
} from '@/schemas/comfyWorkflowSchema'
import type { ComfyNodeDef } from '@/schemas/nodeDefSchema'
import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'
import { useToastStore } from '@/stores/toastStore'
import type { NodeExecutionId } from '@/types/nodeIdentification'
import { WorkflowTemplates } from '@/types/workflowTemplateTypes'
@@ -130,6 +136,7 @@ interface BackendApiCalls {
progress_state: ProgressStateWsMessage
display_component: DisplayComponentWsMessage
feature_flags: FeatureFlagsWsMessage
notification: NotificationWsMessage
}
/** Dictionary of all api calls */
@@ -272,6 +279,81 @@ export class ComfyApi extends EventTarget {
*/
serverFeatureFlags: Record<string, unknown> = {}
/**
* Map of notification toasts by ID
*/
#notificationToasts = new Map<string, any>()
/**
* Map of timers for auto-hiding notifications by ID
*/
#notificationTimers = new Map<string, number>()
/**
* Handle notification messages (with optional ID for multiple parallel notifications)
*/
#handleNotification(value: string, id?: string) {
try {
const toastStore = useToastStore()
const notificationId = id || 'default'
console.log(`Updating notification (${notificationId}):`, value)
// Get existing toast for this ID
const existingToast = this.#notificationToasts.get(notificationId)
if (existingToast) {
// Update existing toast by removing and re-adding with new content
console.log(`Updating existing notification toast: ${notificationId}`)
toastStore.remove(existingToast)
// Update the detail text
existingToast.detail = value
toastStore.add(existingToast)
} else {
// Create new persistent notification toast
console.log(`Creating new notification toast: ${notificationId}`)
const newToast = {
severity: 'info' as const,
summary: 'Notification',
detail: value,
closable: true
// No 'life' property means it won't auto-hide
}
this.#notificationToasts.set(notificationId, newToast)
toastStore.add(newToast)
}
// Clear existing timer for this ID and set new one
const existingTimer = this.#notificationTimers.get(notificationId)
if (existingTimer) {
clearTimeout(existingTimer)
}
const timer = window.setTimeout(() => {
const toast = this.#notificationToasts.get(notificationId)
if (toast) {
console.log(`Auto-hiding notification toast: ${notificationId}`)
toastStore.remove(toast)
this.#notificationToasts.delete(notificationId)
this.#notificationTimers.delete(notificationId)
}
}, 3000)
this.#notificationTimers.set(notificationId, timer)
console.log('Toast updated successfully')
} catch (error) {
console.error('Error handling notification:', error)
}
}
/**
* Debounced notification handler to avoid rapid toast updates
*/
#debouncedNotificationHandler = debounce((value: string, id?: string) => {
this.#handleNotification(value, id)
}, 300) // 300ms debounce delay
/**
* The auth token for the comfy org account if the user is logged in.
* This is only used for {@link queuePrompt} now. It is not directly
@@ -311,7 +393,27 @@ export class ComfyApi extends EventTarget {
return this.api_base + route
}
fetchApi(route: string, options?: RequestInit) {
/**
* Waits for Firebase auth to be initialized before proceeding
*/
async #waitForAuthInitialization(): Promise<void> {
const authStore = useFirebaseAuthStore()
if (authStore.isInitialized) {
return
}
return new Promise<void>((resolve) => {
const unwatch = authStore.$subscribe((_, state) => {
if (state.isInitialized) {
unwatch()
resolve()
}
})
})
}
async fetchApi(route: string, options?: RequestInit) {
if (!options) {
options = {}
}
@@ -322,6 +424,30 @@ export class ComfyApi extends EventTarget {
options.cache = 'no-cache'
}
// Wait for Firebase auth to be initialized before making any API request
await this.#waitForAuthInitialization()
// Add Firebase JWT token if user is logged in
try {
const authHeader = await useFirebaseAuthStore().getAuthHeader()
if (authHeader) {
if (Array.isArray(options.headers)) {
for (const [key, value] of Object.entries(authHeader)) {
options.headers.push([key, value])
}
} else if (options.headers instanceof Headers) {
for (const [key, value] of Object.entries(authHeader)) {
options.headers.set(key, value)
}
} else {
Object.assign(options.headers, authHeader)
}
}
} catch (error) {
// Silently ignore auth errors to avoid breaking API calls
console.warn('Failed to get auth header:', error)
}
if (Array.isArray(options.headers)) {
options.headers.push(['Comfy-User', this.user])
} else if (options.headers instanceof Headers) {
@@ -551,6 +677,16 @@ export class ComfyApi extends EventTarget {
this.serverFeatureFlags
)
break
case 'notification':
// Display notification in toast with debouncing
console.log(
'Received notification message:',
msg.data.value,
msg.data.id ? `(ID: ${msg.data.id})` : ''
)
this.#debouncedNotificationHandler(msg.data.value, msg.data.id)
this.dispatchCustomEvent(msg.type, msg.data)
break
default:
if (this.#registered.has(msg.type)) {
// Fallback for custom types - calls super direct.
@@ -576,6 +712,35 @@ export class ComfyApi extends EventTarget {
this.#createSocket()
}
/**
* Test method to simulate a notification message (for development/testing)
*/
testNotification(message: string = 'Test notification message', id?: string) {
console.log(
'Testing notification with message:',
message,
id ? `(ID: ${id})` : ''
)
const mockEvent = {
data: JSON.stringify({
type: 'notification',
data: { value: message, id }
})
}
// Simulate the websocket message handler
const msg = JSON.parse(mockEvent.data)
if (msg.type === 'notification') {
console.log(
'Received notification message:',
msg.data.value,
msg.data.id ? `(ID: ${msg.data.id})` : ''
)
this.#debouncedNotificationHandler(msg.data.value, msg.data.id)
this.dispatchCustomEvent(msg.type, msg.data)
}
}
/**
* Gets a list of extension urls
*/
@@ -739,6 +904,28 @@ export class ComfyApi extends EventTarget {
return this.getHistory()
}
/**
* Parses queue prompt data from array or object format
* @param rawPrompt The raw prompt data from the API
* @returns Normalized TaskPrompt object
*/
private parseQueuePrompt(rawPrompt: any): TaskPrompt {
if (Array.isArray(rawPrompt)) {
// Queue format: [priority, prompt_id, workflow, outputs]
const [priority, prompt_id, workflow] = rawPrompt
return {
priority,
prompt_id,
extra_data: workflow?.extra_data || {
client_id: '',
extra_pnginfo: workflow
}
}
}
return rawPrompt as TaskPrompt
}
/**
* Gets the current state of the queue
* @returns The currently running and queued items
@@ -752,15 +939,17 @@ export class ComfyApi extends EventTarget {
const data = await res.json()
return {
// Running action uses a different endpoint for cancelling
Running: data.queue_running.map((prompt: Record<number, any>) => ({
Running: data.queue_running.map((prompt: any) => ({
taskType: 'Running',
prompt,
// prompt[1] is the prompt id
remove: { name: 'Cancel', cb: () => api.interrupt(prompt[1]) }
prompt: this.parseQueuePrompt(prompt),
remove: {
name: 'Cancel',
cb: () => api.interrupt(this.parseQueuePrompt(prompt).prompt_id)
}
})),
Pending: data.queue_pending.map((prompt: Record<number, any>) => ({
Pending: data.queue_pending.map((prompt: any) => ({
taskType: 'Pending',
prompt
prompt: this.parseQueuePrompt(prompt)
}))
}
} catch (error) {
@@ -777,13 +966,17 @@ export class ComfyApi extends EventTarget {
max_items: number = 200
): Promise<{ History: HistoryTaskItem[] }> {
try {
const res = await this.fetchApi(`/history?max_items=${max_items}`)
const json: Promise<HistoryTaskItem[]> = await res.json()
const res = await this.fetchApi(`/history_v2?max_items=${max_items}`)
const json: HistoryResponse = await res.json()
// Extract history data from new format: { history: [{prompt_id: "...", ...}, ...] }
return {
History: Object.values(json).map((item) => ({
...item,
taskType: 'History'
}))
History: json.history.map(
(item): HistoryTaskItem => ({
...item,
taskType: 'History'
})
)
}
} catch (error) {
console.error(error)
@@ -791,6 +984,33 @@ export class ComfyApi extends EventTarget {
}
}
/**
* Gets workflow data for a specific prompt from history
* @param prompt_id The prompt ID to fetch workflow for
* @returns Workflow data for the specific prompt
*/
async getWorkflowFromHistory(
prompt_id: string
): Promise<ComfyWorkflowJSON | null> {
try {
const res = await this.fetchApi(`/history_v2/${prompt_id}`)
const json = await res.json()
// The /history_v2/{prompt_id} endpoint returns data for a specific prompt
// The response format is: { prompt_id: { prompt: {priority, prompt_id, extra_data}, outputs: {...}, status: {...} } }
const historyItem = json[prompt_id]
if (!historyItem) return null
// Extract workflow from the prompt object
// prompt.extra_data contains extra_pnginfo.workflow
const workflow = historyItem.prompt?.extra_data?.extra_pnginfo?.workflow
return workflow || null
} catch (error) {
console.error(`Failed to fetch workflow for prompt ${prompt_id}:`, error)
return null
}
}
/**
* Gets system & device stats
* @returns System stats such as python version, OS, per device info

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import type { ToastMessageOptions } from 'primevue/toast'
import { reactive } from 'vue'
@@ -323,6 +323,14 @@ export class ComfyApp {
return '&rand=' + Math.random()
}
getClientIdParam() {
const clientId = window.name
if (clientId) {
return '&client_id=' + clientId
}
return ''
}
static onClipspaceEditorSave() {
if (ComfyApp.clipspace_return_node) {
ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)

View File

@@ -1,5 +1,5 @@
import _ from 'es-toolkit/compat'
import * as jsondiffpatch from 'jsondiffpatch'
import _ from 'lodash'
import log from 'loglevel'
import { LGraphCanvas, LiteGraph } from '@/lib/litegraph/src/litegraph'

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { type Component, toRaw } from 'vue'
import { useChainCallback } from '@/composables/functional/useChainCallback'

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import {
type INodeOutputSlot,

View File

@@ -264,15 +264,21 @@ class ComfyList {
? item.remove
: {
name: 'Delete',
cb: () => api.deleteItem(this.#type, item.prompt[1])
cb: () =>
api.deleteItem(
this.#type,
Array.isArray(item.prompt)
? item.prompt[1]
: item.prompt.prompt_id
)
}
return $el('div', { textContent: item.prompt[0] + ': ' }, [
return $el('div', { textContent: item.prompt.priority + ': ' }, [
$el('button', {
textContent: 'Load',
onclick: async () => {
await app.loadGraphData(
// @ts-expect-error fixme ts strict error
item.prompt[3].extra_pnginfo.workflow,
item.prompt.extra_data.extra_pnginfo.workflow,
true,
false
)

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { useNodeAnimatedImage } from '@/composables/node/useNodeAnimatedImage'
import { useNodeCanvasImagePreview } from '@/composables/node/useNodeCanvasImagePreview'
@@ -805,15 +805,6 @@ export const useLitegraphService = () => {
})
}
}
if (this instanceof SubgraphNode) {
options.unshift({
content: 'Unpack Subgraph',
callback: () => {
useNodeOutputStore().revokeSubgraphPreviews(this)
this.graph.unpackSubgraph(this)
}
})
}
return []
}

View File

@@ -4,7 +4,7 @@ import type {
SearchResponse
} from 'algoliasearch/dist/lite/browser'
import { liteClient as algoliasearch } from 'algoliasearch/dist/lite/builds/browser'
import { memoize, omit } from 'es-toolkit/compat'
import { memoize, omit } from 'lodash'
import {
MIN_CHARS_FOR_SUGGESTIONS_ALGOLIA,

View File

@@ -5,10 +5,12 @@ import { t } from '@/i18n'
import { LGraph, LGraphCanvas } from '@/lib/litegraph/src/litegraph'
import type { SerialisableGraph, Vector2 } from '@/lib/litegraph/src/litegraph'
import { ComfyWorkflowJSON } from '@/schemas/comfyWorkflowSchema'
import { api } from '@/scripts/api'
import { app } from '@/scripts/app'
import { blankGraph, defaultGraph } from '@/scripts/defaultGraph'
import { downloadBlob } from '@/scripts/utils'
import { useDomWidgetStore } from '@/stores/domWidgetStore'
import { TaskItemImpl } from '@/stores/queueStore'
import { useSettingStore } from '@/stores/settingStore'
import { useToastStore } from '@/stores/toastStore'
import { ComfyWorkflow, useWorkflowStore } from '@/stores/workflowStore'
@@ -154,6 +156,32 @@ export const useWorkflowService = () => {
await app.loadGraphData(blankGraph)
}
/**
* Load a workflow from a task item (queue/history)
* For history items, fetches workflow data from /history_v2/{prompt_id}
* @param task The task item to load the workflow from
*/
const loadTaskWorkflow = async (task: TaskItemImpl) => {
let workflowData = task.workflow
// History items don't include workflow data - fetch from API
if (task.isHistory) {
const promptId = task.prompt.prompt_id
if (promptId) {
workflowData = (await api.getWorkflowFromHistory(promptId)) || undefined
}
}
if (!workflowData) {
return
}
await app.loadGraphData(toRaw(workflowData))
if (task.outputs) {
app.nodeOutputs = toRaw(task.outputs)
}
}
/**
* Reload the current workflow
* This is used to refresh the node definitions update, e.g. when the locale changes.
@@ -402,6 +430,7 @@ export const useWorkflowService = () => {
saveWorkflow,
loadDefaultWorkflow,
loadBlankWorkflow,
loadTaskWorkflow,
reloadCurrentWorkflow,
openWorkflow,
closeWorkflow,

View File

@@ -1,5 +1,5 @@
import QuickLRU from '@alloc/quick-lru'
import { partition } from 'es-toolkit/compat'
import { partition } from 'lodash'
import { defineStore } from 'pinia'
import { useCachedRequest } from '@/composables/useCachedRequest'

View File

@@ -1,6 +1,6 @@
// We should consider moving to https://primevue.org/dynamicdialog/ once everything is in Vue.
// Currently we need to bridge between legacy app code and Vue app with a Pinia store.
import { merge } from 'es-toolkit/compat'
import { merge } from 'lodash'
import { defineStore } from 'pinia'
import type { DialogPassThroughOptions } from 'primevue/dialog'
import { type Component, markRaw, ref } from 'vue'

View File

@@ -83,6 +83,16 @@ export const useFirebaseAuthStore = defineStore('firebaseAuth', () => {
currentUser.value = user
isInitialized.value = true
if (user && (window as any).mixpanel) {
;(window as any).mixpanel
.identify(user.uid)(window as any)
.mixpanel.people.set({
$email: user.email,
$name: user.displayName,
$created: user.metadata.creationTime
})
}
// Reset balance when auth state changes
balance.value = null
lastBalanceUpdateTime.value = null

View File

@@ -1,6 +1,6 @@
import { defineStore } from 'pinia'
import { LGraphNode, SubgraphNode } from '@/lib/litegraph/src/litegraph'
import { LGraphNode } from '@/lib/litegraph/src/litegraph'
import {
ExecutedWsMessage,
ResultItem,
@@ -90,10 +90,13 @@ export const useNodeOutputStore = defineStore('nodeOutput', () => {
const rand = app.getRandParam()
const previewParam = getPreviewParam(node, outputs)
const clientIdParam = app.getClientIdParam()
return outputs.images.map((image) => {
const imgUrlPart = new URLSearchParams(image)
return api.apiURL(`/view?${imgUrlPart}${previewParam}${rand}`)
return api.apiURL(
`/view?${imgUrlPart}${previewParam}${rand}${clientIdParam}`
)
})
}
@@ -268,20 +271,6 @@ export const useNodeOutputStore = defineStore('nodeOutput', () => {
app.nodePreviewImages = {}
}
/**
* Revoke all preview of a subgraph node and the graph it contains.
* Does not recurse to contents of nested subgraphs.
*/
function revokeSubgraphPreviews(subgraphNode: SubgraphNode) {
const graphId = subgraphNode.graph.isRootGraph
? ''
: subgraphNode.graph.id + ':'
revokePreviewsByLocatorId(graphId + subgraphNode.id)
for (const node of subgraphNode.subgraph.nodes) {
revokePreviewsByLocatorId(subgraphNode.subgraph.id + node.id)
}
}
return {
getNodeOutputs,
getNodeImageUrls,
@@ -293,7 +282,6 @@ export const useNodeOutputStore = defineStore('nodeOutput', () => {
setNodePreviewsByNodeId,
revokePreviewsByExecutionId,
revokeAllPreviews,
revokeSubgraphPreviews,
getPreviewParam
}
})

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { Ref, computed, ref, toRaw } from 'vue'

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { computed } from 'vue'

View File

@@ -1,5 +1,5 @@
import axios from 'axios'
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { computed, ref, toRaw } from 'vue'
@@ -59,6 +59,11 @@ export class ResultItemImpl {
params.set('type', this.type)
params.set('subfolder', this.subfolder)
const clientId = window.name
if (clientId) {
params.set('client_id', clientId)
}
if (this.format) {
params.set('format', this.format)
}
@@ -271,23 +276,15 @@ export class TaskItemImpl {
}
get queueIndex() {
return this.prompt[0]
return this.prompt.priority
}
get promptId() {
return this.prompt[1]
}
get promptInputs() {
return this.prompt[2]
return this.prompt.prompt_id
}
get extraData() {
return this.prompt[3]
}
get outputsToExecute() {
return this.prompt[4]
return this.prompt.extra_data
}
get extraPngInfo() {
@@ -403,13 +400,11 @@ export class TaskItemImpl {
(output: ResultItemImpl, i: number) =>
new TaskItemImpl(
this.taskType,
[
this.queueIndex,
`${this.promptId}-${i}`,
this.promptInputs,
this.extraData,
this.outputsToExecute
],
{
priority: this.queueIndex,
prompt_id: `${this.promptId}-${i}`,
extra_data: this.extraData
},
this.status,
{
[output.nodeId]: {
@@ -474,11 +469,11 @@ export const useQueueStore = defineStore('queue', () => {
pendingTasks.value = toClassAll(queue.Pending)
const allIndex = new Set<number>(
history.History.map((item: TaskItem) => item.prompt[0])
history.History.map((item: TaskItem) => item.prompt.priority)
)
const newHistoryItems = toClassAll(
history.History.filter(
(item) => item.prompt[0] > lastHistoryQueueIndex.value
(item) => item.prompt.priority > lastHistoryQueueIndex.value
)
)
const existingHistoryItems = historyTasks.value.filter((item) =>
@@ -486,7 +481,11 @@ export const useQueueStore = defineStore('queue', () => {
)
historyTasks.value = [...newHistoryItems, ...existingHistoryItems]
.slice(0, maxHistoryItems.value)
.sort((a, b) => b.queueIndex - a.queueIndex)
.sort((a, b) => {
const aTime = a.executionStartTimestamp ?? 0
const bTime = b.executionStartTimestamp ?? 0
return bTime - aTime
})
} finally {
isLoading.value = false
}

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { ref } from 'vue'

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { defineStore } from 'pinia'
import { type Raw, computed, markRaw, ref, shallowRef, watch } from 'vue'

View File

@@ -1,4 +1,4 @@
import { groupBy } from 'es-toolkit/compat'
import { groupBy } from 'lodash'
import { defineStore } from 'pinia'
import { computed, ref, shallowRef } from 'vue'

View File

@@ -1,4 +1,4 @@
import { memoize } from 'es-toolkit/compat'
import { memoize } from 'lodash'
type RGB = { r: number; g: number; b: number }
type HSL = { h: number; s: number; l: number }

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import { ColorOption, LGraph, Reroute } from '@/lib/litegraph/src/litegraph'
import {

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import type {
ComfyLinkObject,

View File

@@ -1,4 +1,4 @@
import _ from 'es-toolkit/compat'
import _ from 'lodash'
import type {
ComboInputSpec,

View File

@@ -15,7 +15,7 @@ interface ColorTestCase {
type ColorFormat = 'hex' | 'rgb' | 'rgba' | 'hsl' | 'hsla'
vi.mock('es-toolkit/compat', () => ({
vi.mock('lodash', () => ({
memoize: (fn: any) => fn
}))

View File

@@ -64,16 +64,6 @@ describe('useNodePricing', () => {
})
describe('dynamic pricing - KlingTextToVideoNode', () => {
it('should return high price for kling-v2-1-master model', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('KlingTextToVideoNode', [
{ name: 'mode', value: 'standard / 5s / v2-1-master' }
])
const price = getNodeDisplayPrice(node)
expect(price).toBe('$1.40/Run')
})
it('should return high price for kling-v2-master model', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('KlingTextToVideoNode', [
@@ -229,49 +219,6 @@ describe('useNodePricing', () => {
})
})
describe('dynamic pricing - MinimaxHailuoVideoNode', () => {
it('should return $0.28 for 6s duration and 768P resolution', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('MinimaxHailuoVideoNode', [
{ name: 'duration', value: '6' },
{ name: 'resolution', value: '768P' }
])
const price = getNodeDisplayPrice(node)
expect(price).toBe('$0.28/Run')
})
it('should return $0.60 for 10s duration and 768P resolution', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('MinimaxHailuoVideoNode', [
{ name: 'duration', value: '10' },
{ name: 'resolution', value: '768P' }
])
const price = getNodeDisplayPrice(node)
expect(price).toBe('$0.56/Run')
})
it('should return $0.49 for 6s duration and 1080P resolution', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('MinimaxHailuoVideoNode', [
{ name: 'duration', value: '6' },
{ name: 'resolution', value: '1080P' }
])
const price = getNodeDisplayPrice(node)
expect(price).toBe('$0.49/Run')
})
it('should return range when duration widget is missing', () => {
const { getNodeDisplayPrice } = useNodePricing()
const node = createMockNode('MinimaxHailuoVideoNode', [])
const price = getNodeDisplayPrice(node)
expect(price).toBe('$0.28-0.56/Run (varies with resolution & duration)')
})
})
describe('dynamic pricing - OpenAIDalle2', () => {
it('should return $0.02 for 1024x1024 size', () => {
const { getNodeDisplayPrice } = useNodePricing()
@@ -1437,19 +1384,11 @@ describe('useNodePricing', () => {
const testCases = [
{
model: 'gemini-2.5-pro-preview-05-06',
expected: '$0.00125/$0.01 per 1K tokens'
},
{
model: 'gemini-2.5-pro',
expected: '$0.00125/$0.01 per 1K tokens'
expected: '$0.00016/$0.0006 per 1K tokens'
},
{
model: 'gemini-2.5-flash-preview-04-17',
expected: '$0.0003/$0.0025 per 1K tokens'
},
{
model: 'gemini-2.5-flash',
expected: '$0.0003/$0.0025 per 1K tokens'
expected: '$0.00125/$0.01 per 1K tokens'
},
{ model: 'unknown-gemini-model', expected: 'Token-based' }
]

View File

@@ -0,0 +1,248 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type {
HistoryResponse,
RawHistoryItem
} from '../../../src/schemas/apiSchema'
import type { ComfyWorkflowJSON } from '../../../src/schemas/comfyWorkflowSchema'
import { ComfyApi } from '../../../src/scripts/api'
describe('ComfyApi getHistory', () => {
let api: ComfyApi
beforeEach(() => {
api = new ComfyApi()
})
const mockHistoryItem: RawHistoryItem = {
prompt_id: 'test_prompt_id',
prompt: {
priority: 0,
prompt_id: 'test_prompt_id',
extra_data: {
extra_pnginfo: {
workflow: {
last_node_id: 1,
last_link_id: 0,
nodes: [],
links: [],
groups: [],
config: {},
extra: {},
version: 0.4
}
},
client_id: 'test_client_id'
}
},
outputs: {},
status: {
status_str: 'success',
completed: true,
messages: []
}
}
describe('history v2 API format', () => {
it('should handle history array format from /history_v2', async () => {
const historyResponse: HistoryResponse = {
history: [
{ ...mockHistoryItem, prompt_id: 'prompt_id_1' },
{ ...mockHistoryItem, prompt_id: 'prompt_id_2' }
]
}
// Mock fetchApi to return the v2 format
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(historyResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getHistory(10)
expect(result.History).toHaveLength(2)
expect(result.History[0]).toEqual({
...mockHistoryItem,
prompt_id: 'prompt_id_1',
taskType: 'History'
})
expect(result.History[1]).toEqual({
...mockHistoryItem,
prompt_id: 'prompt_id_2',
taskType: 'History'
})
})
it('should handle empty history array', async () => {
const historyResponse: HistoryResponse = {
history: []
}
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(historyResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getHistory(10)
expect(result.History).toHaveLength(0)
expect(result.History).toEqual([])
})
})
describe('error handling', () => {
it('should return empty history on error', async () => {
const mockFetchApi = vi.fn().mockRejectedValue(new Error('Network error'))
api.fetchApi = mockFetchApi
const result = await api.getHistory()
expect(result.History).toEqual([])
})
})
describe('API call parameters', () => {
it('should call fetchApi with correct v2 endpoint and parameters', async () => {
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue({ history: [] })
})
api.fetchApi = mockFetchApi
await api.getHistory(50)
expect(mockFetchApi).toHaveBeenCalledWith('/history_v2?max_items=50')
})
it('should use default max_items parameter with v2 endpoint', async () => {
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue({ history: [] })
})
api.fetchApi = mockFetchApi
await api.getHistory()
expect(mockFetchApi).toHaveBeenCalledWith('/history_v2?max_items=200')
})
})
})
describe('ComfyApi getWorkflowFromHistory', () => {
let api: ComfyApi
beforeEach(() => {
api = new ComfyApi()
})
const mockWorkflow: ComfyWorkflowJSON = {
last_node_id: 1,
last_link_id: 0,
nodes: [],
links: [],
groups: [],
config: {},
extra: {},
version: 0.4
}
it('should fetch workflow data for a specific prompt', async () => {
const promptId = 'test_prompt_id'
const mockResponse = {
[promptId]: {
prompt: {
priority: 0,
prompt_id: promptId,
extra_data: {
extra_pnginfo: {
workflow: mockWorkflow
}
}
},
outputs: {},
status: {
status_str: 'success',
completed: true,
messages: []
}
}
}
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getWorkflowFromHistory(promptId)
expect(mockFetchApi).toHaveBeenCalledWith(`/history_v2/${promptId}`)
expect(result).toEqual(mockWorkflow)
})
it('should return null when prompt_id is not found', async () => {
const promptId = 'non_existent_prompt'
const mockResponse = {}
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getWorkflowFromHistory(promptId)
expect(mockFetchApi).toHaveBeenCalledWith(`/history_v2/${promptId}`)
expect(result).toBeNull()
})
it('should return null when workflow data is missing', async () => {
const promptId = 'test_prompt_id'
const mockResponse = {
[promptId]: {
prompt: {
priority: 0,
prompt_id: promptId,
extra_data: {}
},
outputs: {},
status: {
status_str: 'success',
completed: true,
messages: []
}
}
}
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getWorkflowFromHistory(promptId)
expect(result).toBeNull()
})
it('should handle API errors gracefully', async () => {
const promptId = 'test_prompt_id'
const mockFetchApi = vi.fn().mockRejectedValue(new Error('Network error'))
api.fetchApi = mockFetchApi
const result = await api.getWorkflowFromHistory(promptId)
expect(result).toBeNull()
})
it('should handle malformed response gracefully', async () => {
const promptId = 'test_prompt_id'
const mockResponse = {
[promptId]: null
}
const mockFetchApi = vi.fn().mockResolvedValue({
json: vi.fn().mockResolvedValue(mockResponse)
})
api.fetchApi = mockFetchApi
const result = await api.getWorkflowFromHistory(promptId)
expect(result).toBeNull()
})
})

View File

@@ -3,10 +3,94 @@ import { describe, expect, it } from 'vitest'
import { TaskItemImpl } from '@/stores/queueStore'
describe('TaskItemImpl', () => {
describe('prompt property accessors', () => {
it('should correctly access queueIndex from priority', () => {
const taskItem = new TaskItemImpl('Pending', {
priority: 5,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
})
expect(taskItem.queueIndex).toBe(5)
})
it('should correctly access promptId from prompt_id', () => {
const taskItem = new TaskItemImpl('History', {
priority: 0,
prompt_id: 'unique-prompt-id',
extra_data: { client_id: 'client-id' }
})
expect(taskItem.promptId).toBe('unique-prompt-id')
})
it('should correctly access extraData', () => {
const extraData = {
client_id: 'client-id',
extra_pnginfo: {
workflow: {
last_node_id: 1,
last_link_id: 0,
nodes: [],
links: [],
groups: [],
config: {},
extra: {},
version: 0.4
}
}
}
const taskItem = new TaskItemImpl('Running', {
priority: 1,
prompt_id: 'test-id',
extra_data: extraData
})
expect(taskItem.extraData).toEqual(extraData)
})
it('should correctly access workflow from extraPngInfo', () => {
const workflow = {
last_node_id: 1,
last_link_id: 0,
nodes: [],
links: [],
groups: [],
config: {},
extra: {},
version: 0.4
}
const taskItem = new TaskItemImpl('History', {
priority: 0,
prompt_id: 'test-id',
extra_data: {
client_id: 'client-id',
extra_pnginfo: { workflow }
}
})
expect(taskItem.workflow).toEqual(workflow)
})
it('should return undefined workflow when extraPngInfo is missing', () => {
const taskItem = new TaskItemImpl('History', {
priority: 0,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
})
expect(taskItem.workflow).toBeUndefined()
})
})
it('should remove animated property from outputs during construction', () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -26,7 +110,11 @@ describe('TaskItemImpl', () => {
it('should handle outputs without animated property', () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -42,7 +130,11 @@ describe('TaskItemImpl', () => {
it('should recognize webm video from core', () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -64,7 +156,11 @@ describe('TaskItemImpl', () => {
it('should recognize webm video from VHS', () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -93,7 +189,11 @@ describe('TaskItemImpl', () => {
it('should recognize mp4 video from core', () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -128,7 +228,11 @@ describe('TaskItemImpl', () => {
it(`should recognize ${extension} audio`, () => {
const taskItem = new TaskItemImpl(
'History',
[0, 'prompt-id', {}, { client_id: 'client-id' }, []],
{
priority: 0,
prompt_id: 'prompt-id',
extra_data: { client_id: 'client-id' }
},
{ status_str: 'success', messages: [], completed: true },
{
'node-1': {
@@ -153,4 +257,193 @@ describe('TaskItemImpl', () => {
})
})
})
describe('execution timestamp properties', () => {
it('should extract execution start timestamp from messages', () => {
const taskItem = new TaskItemImpl(
'History',
{
priority: 0,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
[
'execution_start',
{ prompt_id: 'test-id', timestamp: 1234567890 }
],
[
'execution_success',
{ prompt_id: 'test-id', timestamp: 1234567900 }
]
]
}
)
expect(taskItem.executionStartTimestamp).toBe(1234567890)
})
it('should return undefined when no execution_start message exists', () => {
const taskItem = new TaskItemImpl(
'History',
{
priority: 0,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
[
'execution_success',
{ prompt_id: 'test-id', timestamp: 1234567900 }
]
]
}
)
expect(taskItem.executionStartTimestamp).toBeUndefined()
})
it('should return undefined when status has no messages', () => {
const taskItem = new TaskItemImpl(
'History',
{
priority: 0,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: []
}
)
expect(taskItem.executionStartTimestamp).toBeUndefined()
})
it('should return undefined when status is undefined', () => {
const taskItem = new TaskItemImpl('History', {
priority: 0,
prompt_id: 'test-id',
extra_data: { client_id: 'client-id' }
})
expect(taskItem.executionStartTimestamp).toBeUndefined()
})
})
describe('sorting by execution start time', () => {
it('should sort history tasks by execution start timestamp descending', () => {
const task1 = new TaskItemImpl(
'History',
{
priority: 1,
prompt_id: 'old-task',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
['execution_start', { prompt_id: 'old-task', timestamp: 1000 }]
]
}
)
const task2 = new TaskItemImpl(
'History',
{
priority: 2,
prompt_id: 'new-task',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
['execution_start', { prompt_id: 'new-task', timestamp: 3000 }]
]
}
)
const task3 = new TaskItemImpl(
'History',
{
priority: 3,
prompt_id: 'middle-task',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
['execution_start', { prompt_id: 'middle-task', timestamp: 2000 }]
]
}
)
const tasks = [task1, task2, task3]
// Sort using the same logic as queueStore
tasks.sort((a, b) => {
const aTime = a.executionStartTimestamp ?? 0
const bTime = b.executionStartTimestamp ?? 0
return bTime - aTime
})
expect(tasks[0].promptId).toBe('new-task')
expect(tasks[1].promptId).toBe('middle-task')
expect(tasks[2].promptId).toBe('old-task')
})
it('should place tasks without execution start timestamp at end', () => {
const taskWithTime = new TaskItemImpl(
'History',
{
priority: 1,
prompt_id: 'with-time',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: [
['execution_start', { prompt_id: 'with-time', timestamp: 2000 }]
]
}
)
const taskWithoutTime = new TaskItemImpl(
'History',
{
priority: 2,
prompt_id: 'without-time',
extra_data: { client_id: 'client-id' }
},
{
status_str: 'success',
completed: true,
messages: []
}
)
const tasks = [taskWithoutTime, taskWithTime]
// Sort using the same logic as queueStore
tasks.sort((a, b) => {
const aTime = a.executionStartTimestamp ?? 0
const bTime = b.executionStartTimestamp ?? 0
return bTime - aTime
})
expect(tasks[0].promptId).toBe('with-time')
expect(tasks[1].promptId).toBe('without-time')
})
})
})

View File

@@ -8,7 +8,7 @@ This guide covers patterns and examples for unit testing utilities, composables,
2. [Working with LiteGraph and Nodes](#working-with-litegraph-and-nodes)
3. [Working with Workflow JSON Files](#working-with-workflow-json-files)
4. [Mocking the API Object](#mocking-the-api-object)
5. [Mocking Utility Functions](#mocking-utility-functions)
5. [Mocking Lodash Functions](#mocking-lodash-functions)
6. [Testing with Debounce and Throttle](#testing-with-debounce-and-throttle)
7. [Mocking Node Definitions](#mocking-node-definitions)
@@ -147,17 +147,17 @@ it('should subscribe to logs API', () => {
## Mocking Lodash Functions
Mocking utility functions like debounce:
Mocking lodash functions like debounce:
```typescript
// Mock debounce to execute immediately
import { debounce } from 'es-toolkit/compat'
import { debounce } from 'lodash-es'
vi.mock('es-toolkit/compat', () => ({
vi.mock('lodash-es', () => ({
debounce: vi.fn((fn) => {
// Return function that calls the input function immediately
const mockDebounced = (...args: any[]) => fn(...args)
// Add cancel method that debounced functions have
// Add cancel method that lodash debounced functions have
mockDebounced.cancel = vi.fn()
return mockDebounced
})