Compare commits

..

2 Commits

Author SHA1 Message Date
bymyself
560c15dd6f [fix] use relative import path in subgraph browser tests 2025-07-15 15:00:27 -07:00
bymyself
3ce6bbd567 [feat] sync node library when subgraph titles change
When a subgraph node is renamed, the node library sidebar now immediately reflects the updated display name. This ensures consistency between the canvas, breadcrumb navigation, and node library.

Key changes:
- Add updateNodeDefDisplayName method to nodeDefStore with reference preservation
- Update TitleEditor to call nodeDefStore for subgraph title changes
- Organize subgraph browser tests into dedicated folder
- Add comprehensive unit test coverage for nodeDefStore
2025-07-15 12:39:30 -07:00
29 changed files with 1355 additions and 2441 deletions

27
.github/workflows/danger.yaml vendored Normal file
View File

@@ -0,0 +1,27 @@
name: Danger PR Review
on:
pull_request:
types: [opened, edited, synchronize]
jobs:
danger:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 'lts/*'
- name: Install dependencies
run: npm ci
- name: Run Danger
run: npx danger ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DANGER_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,154 +0,0 @@
name: PR Checks
on:
pull_request:
types: [opened, edited, synchronize, reopened]
permissions:
contents: read
pull-requests: read
jobs:
analyze:
runs-on: ubuntu-latest
outputs:
should_run: ${{ steps.check-changes.outputs.should_run }}
has_browser_tests: ${{ steps.check-coverage.outputs.has_browser_tests }}
has_screen_recording: ${{ steps.check-recording.outputs.has_recording }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Ensure base branch is available
run: |
# Fetch the specific base commit to ensure it's available for git diff
git fetch origin ${{ github.event.pull_request.base.sha }}
- name: Check if significant changes exist
id: check-changes
run: |
# Get list of changed files
CHANGED_FILES=$(git diff --name-only ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }})
# Filter for src/ files
SRC_FILES=$(echo "$CHANGED_FILES" | grep '^src/' || true)
if [ -z "$SRC_FILES" ]; then
echo "No src/ files changed"
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# Count lines changed in src files
TOTAL_LINES=0
for file in $SRC_FILES; do
if [ -f "$file" ]; then
# Count added lines (non-empty)
ADDED=$(git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- "$file" | grep '^+' | grep -v '^+++' | grep -v '^+$' | wc -l)
# Count removed lines (non-empty)
REMOVED=$(git diff ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} -- "$file" | grep '^-' | grep -v '^---' | grep -v '^-$' | wc -l)
TOTAL_LINES=$((TOTAL_LINES + ADDED + REMOVED))
fi
done
echo "Total lines changed in src/: $TOTAL_LINES"
if [ $TOTAL_LINES -gt 3 ]; then
echo "should_run=true" >> "$GITHUB_OUTPUT"
else
echo "should_run=false" >> "$GITHUB_OUTPUT"
fi
- name: Check browser test coverage
id: check-coverage
if: steps.check-changes.outputs.should_run == 'true'
run: |
# Check if browser tests were updated
BROWSER_TEST_CHANGES=$(git diff --name-only ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }} | grep '^browser_tests/.*\.ts$' || true)
if [ -n "$BROWSER_TEST_CHANGES" ]; then
echo "has_browser_tests=true" >> "$GITHUB_OUTPUT"
else
echo "has_browser_tests=false" >> "$GITHUB_OUTPUT"
fi
- name: Check for screen recording
id: check-recording
if: steps.check-changes.outputs.should_run == 'true'
run: |
# Check PR body for screen recording
PR_BODY="${{ github.event.pull_request.body }}"
# Check for GitHub user attachments or YouTube links
if echo "$PR_BODY" | grep -qiE 'github\.com/user-attachments/assets/[a-f0-9-]+|youtube\.com/watch|youtu\.be/'; then
echo "has_recording=true" >> "$GITHUB_OUTPUT"
else
echo "has_recording=false" >> "$GITHUB_OUTPUT"
fi
- name: Final check and create results
id: final-check
if: always()
run: |
# Initialize results
WARNINGS_JSON=""
# Only run checks if should_run is true
if [ "${{ steps.check-changes.outputs.should_run }}" == "true" ]; then
# Check browser test coverage
if [ "${{ steps.check-coverage.outputs.has_browser_tests }}" != "true" ]; then
if [ -n "$WARNINGS_JSON" ]; then
WARNINGS_JSON="${WARNINGS_JSON},"
fi
WARNINGS_JSON="${WARNINGS_JSON}{\"message\":\"⚠️ **Warning: E2E Test Coverage Missing**\\n\\nIf this PR modifies behavior that can be covered by browser-based E2E tests, those tests are required. PRs lacking applicable test coverage may not be reviewed until added. Please add or update browser tests to ensure code quality and prevent regressions.\"}"
fi
# Check screen recording
if [ "${{ steps.check-recording.outputs.has_recording }}" != "true" ]; then
if [ -n "$WARNINGS_JSON" ]; then
WARNINGS_JSON="${WARNINGS_JSON},"
fi
WARNINGS_JSON="${WARNINGS_JSON}{\"message\":\"⚠️ **Warning: Visual Documentation Missing**\\n\\nIf this PR changes user-facing behavior, visual proof (screen recording or screenshot) is required. PRs without applicable visual documentation may not be reviewed until provided.\\nYou can add it by:\\n\\n- GitHub: Drag & drop media directly into the PR description\\n\\n- YouTube: Include a link to a short demo\"}"
fi
fi
# Create results JSON
if [ -n "$WARNINGS_JSON" ]; then
# Create JSON with warnings
cat > pr-check-results.json << EOF
{
"fails": [],
"warnings": [$WARNINGS_JSON],
"messages": [],
"markdowns": []
}
EOF
echo "failed=false" >> "$GITHUB_OUTPUT"
else
# Create JSON with success
cat > pr-check-results.json << 'EOF'
{
"fails": [],
"warnings": [],
"messages": [],
"markdowns": []
}
EOF
echo "failed=false" >> "$GITHUB_OUTPUT"
fi
# Write PR metadata
echo "${{ github.event.pull_request.number }}" > pr-number.txt
echo "${{ github.event.pull_request.head.sha }}" > pr-sha.txt
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: pr-check-results-${{ github.run_id }}
path: |
pr-check-results.json
pr-number.txt
pr-sha.txt
retention-days: 1

View File

@@ -1,149 +0,0 @@
name: PR Comment
on:
workflow_run:
workflows: ["PR Checks"]
types: [completed]
permissions:
pull-requests: write
issues: write
statuses: write
jobs:
comment:
if: github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v4
with:
name: pr-check-results-${{ github.event.workflow_run.id }}
path: /tmp/pr-artifacts
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ github.event.workflow_run.id }}
- name: Post results
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const path = require('path');
// Helper function to safely read files
function safeReadFile(filePath) {
try {
if (!fs.existsSync(filePath)) return null;
return fs.readFileSync(filePath, 'utf8').trim();
} catch (e) {
console.error(`Error reading ${filePath}:`, e);
return null;
}
}
// Read artifact files
const artifactDir = '/tmp/pr-artifacts';
const prNumber = safeReadFile(path.join(artifactDir, 'pr-number.txt'));
const prSha = safeReadFile(path.join(artifactDir, 'pr-sha.txt'));
const resultsJson = safeReadFile(path.join(artifactDir, 'pr-check-results.json'));
// Validate PR number
if (!prNumber || isNaN(parseInt(prNumber))) {
throw new Error('Invalid or missing PR number');
}
// Parse and validate results
let results;
try {
results = JSON.parse(resultsJson || '{}');
} catch (e) {
console.error('Failed to parse check results:', e);
// Post error comment
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: parseInt(prNumber),
body: `⚠️ PR checks failed to complete properly. Error parsing results: ${e.message}`
});
return;
}
// Format check messages
const messages = [];
if (results.fails && results.fails.length > 0) {
messages.push('### ❌ Failures\n' + results.fails.map(f => f.message).join('\n\n'));
}
if (results.warnings && results.warnings.length > 0) {
messages.push('### ⚠️ Warnings\n' + results.warnings.map(w => w.message).join('\n\n'));
}
if (results.messages && results.messages.length > 0) {
messages.push('### 💬 Messages\n' + results.messages.map(m => m.message).join('\n\n'));
}
if (results.markdowns && results.markdowns.length > 0) {
messages.push(...results.markdowns.map(m => m.message));
}
// Find existing bot comment
const comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: parseInt(prNumber)
});
const botComment = comments.data.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('<!-- pr-checks-comment -->')
);
// Post comment if there are any messages
if (messages.length > 0) {
const body = messages.join('\n\n');
const commentBody = `<!-- pr-checks-comment -->\n${body}`;
if (botComment) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
body: commentBody
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: parseInt(prNumber),
body: commentBody
});
}
} else {
// No messages - delete existing comment if present
if (botComment) {
await github.rest.issues.deleteComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id
});
}
}
// Set commit status based on failures
if (prSha) {
const hasFailures = results.fails && results.fails.length > 0;
const hasWarnings = results.warnings && results.warnings.length > 0;
await github.rest.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
sha: prSha,
state: hasFailures ? 'failure' : 'success',
context: 'pr-checks',
description: hasFailures
? `${results.fails.length} check(s) failed`
: hasWarnings
? `${results.warnings.length} warning(s)`
: 'All checks passed'
});
}

View File

@@ -1,382 +0,0 @@
import { expect } from '@playwright/test'
import { comfyPageFixture as test } from '../fixtures/ComfyPage'
test.describe('Feature Flags', () => {
test('Client and server exchange feature flags on connection', async ({
comfyPage
}) => {
// Navigate to a new page to capture the initial WebSocket connection
const newPage = await comfyPage.page.context().newPage()
// Set up monitoring before navigation
await newPage.addInitScript(() => {
// This runs before any page scripts
window.__capturedMessages = {
clientFeatureFlags: null,
serverFeatureFlags: null
}
// Capture outgoing client messages
const originalSend = WebSocket.prototype.send
WebSocket.prototype.send = function (data) {
try {
const parsed = JSON.parse(data)
if (parsed.type === 'feature_flags') {
window.__capturedMessages.clientFeatureFlags = parsed
}
} catch (e) {
// Not JSON, ignore
}
return originalSend.call(this, data)
}
// Monitor for server feature flags
const checkInterval = setInterval(() => {
if (
window['app']?.api?.serverFeatureFlags &&
Object.keys(window['app'].api.serverFeatureFlags).length > 0
) {
window.__capturedMessages.serverFeatureFlags =
window['app'].api.serverFeatureFlags
clearInterval(checkInterval)
}
}, 100)
// Clear after 10 seconds
setTimeout(() => clearInterval(checkInterval), 10000)
})
// Navigate to the app
await newPage.goto(comfyPage.url)
// Wait for both client and server feature flags
await newPage.waitForFunction(
() =>
window.__capturedMessages.clientFeatureFlags !== null &&
window.__capturedMessages.serverFeatureFlags !== null,
{ timeout: 10000 }
)
// Get the captured messages
const messages = await newPage.evaluate(() => window.__capturedMessages)
// Verify client sent feature flags
expect(messages.clientFeatureFlags).toBeTruthy()
expect(messages.clientFeatureFlags).toHaveProperty('type', 'feature_flags')
expect(messages.clientFeatureFlags).toHaveProperty('data')
expect(messages.clientFeatureFlags.data).toHaveProperty(
'supports_preview_metadata'
)
expect(
typeof messages.clientFeatureFlags.data.supports_preview_metadata
).toBe('boolean')
// Verify server sent feature flags back
expect(messages.serverFeatureFlags).toBeTruthy()
expect(messages.serverFeatureFlags).toHaveProperty(
'supports_preview_metadata'
)
expect(typeof messages.serverFeatureFlags.supports_preview_metadata).toBe(
'boolean'
)
expect(messages.serverFeatureFlags).toHaveProperty('max_upload_size')
expect(typeof messages.serverFeatureFlags.max_upload_size).toBe('number')
expect(Object.keys(messages.serverFeatureFlags).length).toBeGreaterThan(0)
await newPage.close()
})
test('Server feature flags are received and accessible', async ({
comfyPage
}) => {
// Wait for connection to establish
await comfyPage.page.waitForTimeout(1000)
// Get the actual server feature flags from the backend
const serverFlags = await comfyPage.page.evaluate(() => {
return window['app'].api.serverFeatureFlags
})
// Verify we received real feature flags from the backend
expect(serverFlags).toBeTruthy()
expect(Object.keys(serverFlags).length).toBeGreaterThan(0)
// The backend should send feature flags
expect(serverFlags).toHaveProperty('supports_preview_metadata')
expect(typeof serverFlags.supports_preview_metadata).toBe('boolean')
expect(serverFlags).toHaveProperty('max_upload_size')
expect(typeof serverFlags.max_upload_size).toBe('number')
})
test('serverSupportsFeature method works with real backend flags', async ({
comfyPage
}) => {
// Wait for connection
await comfyPage.page.waitForTimeout(1000)
// Test serverSupportsFeature with real backend flags
const supportsPreviewMetadata = await comfyPage.page.evaluate(() => {
return window['app'].api.serverSupportsFeature(
'supports_preview_metadata'
)
})
// The method should return a boolean based on the backend's value
expect(typeof supportsPreviewMetadata).toBe('boolean')
// Test non-existent feature - should always return false
const supportsNonExistent = await comfyPage.page.evaluate(() => {
return window['app'].api.serverSupportsFeature('non_existent_feature_xyz')
})
expect(supportsNonExistent).toBe(false)
// Test that the method only returns true for boolean true values
const testResults = await comfyPage.page.evaluate(() => {
// Temporarily modify serverFeatureFlags to test behavior
const original = window['app'].api.serverFeatureFlags
window['app'].api.serverFeatureFlags = {
bool_true: true,
bool_false: false,
string_value: 'yes',
number_value: 1,
null_value: null
}
const results = {
bool_true: window['app'].api.serverSupportsFeature('bool_true'),
bool_false: window['app'].api.serverSupportsFeature('bool_false'),
string_value: window['app'].api.serverSupportsFeature('string_value'),
number_value: window['app'].api.serverSupportsFeature('number_value'),
null_value: window['app'].api.serverSupportsFeature('null_value')
}
// Restore original
window['app'].api.serverFeatureFlags = original
return results
})
// serverSupportsFeature should only return true for boolean true values
expect(testResults.bool_true).toBe(true)
expect(testResults.bool_false).toBe(false)
expect(testResults.string_value).toBe(false)
expect(testResults.number_value).toBe(false)
expect(testResults.null_value).toBe(false)
})
test('getServerFeature method works with real backend data', async ({
comfyPage
}) => {
// Wait for connection
await comfyPage.page.waitForTimeout(1000)
// Test getServerFeature method
const previewMetadataValue = await comfyPage.page.evaluate(() => {
return window['app'].api.getServerFeature('supports_preview_metadata')
})
expect(typeof previewMetadataValue).toBe('boolean')
// Test getting max_upload_size
const maxUploadSize = await comfyPage.page.evaluate(() => {
return window['app'].api.getServerFeature('max_upload_size')
})
expect(typeof maxUploadSize).toBe('number')
expect(maxUploadSize).toBeGreaterThan(0)
// Test getServerFeature with default value for non-existent feature
const defaultValue = await comfyPage.page.evaluate(() => {
return window['app'].api.getServerFeature(
'non_existent_feature_xyz',
'default'
)
})
expect(defaultValue).toBe('default')
})
test('getServerFeatures returns all backend feature flags', async ({
comfyPage
}) => {
// Wait for connection
await comfyPage.page.waitForTimeout(1000)
// Test getServerFeatures returns all flags
const allFeatures = await comfyPage.page.evaluate(() => {
return window['app'].api.getServerFeatures()
})
expect(allFeatures).toBeTruthy()
expect(allFeatures).toHaveProperty('supports_preview_metadata')
expect(typeof allFeatures.supports_preview_metadata).toBe('boolean')
expect(allFeatures).toHaveProperty('max_upload_size')
expect(Object.keys(allFeatures).length).toBeGreaterThan(0)
})
test('Client feature flags are immutable', async ({ comfyPage }) => {
// Test that getClientFeatureFlags returns a copy
const immutabilityTest = await comfyPage.page.evaluate(() => {
const flags1 = window['app'].api.getClientFeatureFlags()
const flags2 = window['app'].api.getClientFeatureFlags()
// Modify the first object
flags1.test_modification = true
// Get flags again to check if original was modified
const flags3 = window['app'].api.getClientFeatureFlags()
return {
areEqual: flags1 === flags2,
hasModification: flags3.test_modification !== undefined,
hasSupportsPreview: flags1.supports_preview_metadata !== undefined,
supportsPreviewValue: flags1.supports_preview_metadata
}
})
// Verify they are different objects (not the same reference)
expect(immutabilityTest.areEqual).toBe(false)
// Verify modification didn't affect the original
expect(immutabilityTest.hasModification).toBe(false)
// Verify the flags contain expected properties
expect(immutabilityTest.hasSupportsPreview).toBe(true)
expect(typeof immutabilityTest.supportsPreviewValue).toBe('boolean') // From clientFeatureFlags.json
})
test('Server features are immutable when accessed via getServerFeatures', async ({
comfyPage
}) => {
// Wait for connection to establish
await comfyPage.page.waitForTimeout(1000)
const immutabilityTest = await comfyPage.page.evaluate(() => {
// Get a copy of server features
const features1 = window['app'].api.getServerFeatures()
// Try to modify it
features1.supports_preview_metadata = false
features1.new_feature = 'added'
// Get another copy
const features2 = window['app'].api.getServerFeatures()
return {
modifiedValue: features1.supports_preview_metadata,
originalValue: features2.supports_preview_metadata,
hasNewFeature: features2.new_feature !== undefined,
hasSupportsPreview: features2.supports_preview_metadata !== undefined
}
})
// The modification should only affect the copy
expect(immutabilityTest.modifiedValue).toBe(false)
expect(typeof immutabilityTest.originalValue).toBe('boolean') // Backend sends boolean for supports_preview_metadata
expect(immutabilityTest.hasNewFeature).toBe(false)
expect(immutabilityTest.hasSupportsPreview).toBe(true)
})
test('Feature flags are negotiated early in connection lifecycle', async ({
comfyPage
}) => {
// This test verifies that feature flags are available early in the app lifecycle
// which is important for protocol negotiation
// Create a new page to ensure clean state
const newPage = await comfyPage.page.context().newPage()
// Set up monitoring before navigation
await newPage.addInitScript(() => {
// Track when various app components are ready
;(window as any).__appReadiness = {
featureFlagsReceived: false,
apiInitialized: false,
appInitialized: false
}
// Monitor when feature flags arrive by checking periodically
const checkFeatureFlags = setInterval(() => {
if (
window['app']?.api?.serverFeatureFlags?.supports_preview_metadata !==
undefined
) {
;(window as any).__appReadiness.featureFlagsReceived = true
clearInterval(checkFeatureFlags)
}
}, 10)
// Monitor API initialization
const checkApi = setInterval(() => {
if (window['app']?.api) {
;(window as any).__appReadiness.apiInitialized = true
clearInterval(checkApi)
}
}, 10)
// Monitor app initialization
const checkApp = setInterval(() => {
if (window['app']?.graph) {
;(window as any).__appReadiness.appInitialized = true
clearInterval(checkApp)
}
}, 10)
// Clean up after 10 seconds
setTimeout(() => {
clearInterval(checkFeatureFlags)
clearInterval(checkApi)
clearInterval(checkApp)
}, 10000)
})
// Navigate to the app
await newPage.goto(comfyPage.url)
// Wait for feature flags to be received
await newPage.waitForFunction(
() =>
window['app']?.api?.serverFeatureFlags?.supports_preview_metadata !==
undefined,
{
timeout: 10000
}
)
// Get readiness state
const readiness = await newPage.evaluate(() => {
return {
...(window as any).__appReadiness,
currentFlags: window['app'].api.serverFeatureFlags
}
})
// Verify feature flags are available
expect(readiness.currentFlags).toHaveProperty('supports_preview_metadata')
expect(typeof readiness.currentFlags.supports_preview_metadata).toBe(
'boolean'
)
expect(readiness.currentFlags).toHaveProperty('max_upload_size')
// Verify feature flags were received (we detected them via polling)
expect(readiness.featureFlagsReceived).toBe(true)
// Verify API was initialized (feature flags require API)
expect(readiness.apiInitialized).toBe(true)
await newPage.close()
})
test('Backend /features endpoint returns feature flags', async ({
comfyPage
}) => {
// Test the HTTP endpoint directly
const response = await comfyPage.page.request.get(
`${comfyPage.url}/api/features`
)
expect(response.ok()).toBe(true)
const features = await response.json()
expect(features).toBeTruthy()
expect(features).toHaveProperty('supports_preview_metadata')
expect(typeof features.supports_preview_metadata).toBe('boolean')
expect(features).toHaveProperty('max_upload_size')
expect(Object.keys(features).length).toBeGreaterThan(0)
})
})

View File

@@ -336,4 +336,54 @@ test.describe('Node library sidebar', () => {
await comfyPage.page.waitForTimeout(1000)
expect(await tab.getNode('KSampler (Advanced)').count()).toBe(2)
})
test('Subgraph node display name updates in library when renamed', async ({
comfyPage
}) => {
// Load a workflow with subgraphs to populate the node library
await comfyPage.loadWorkflow('nested-subgraph')
await comfyPage.nextFrame()
const tab = comfyPage.menu.nodeLibraryTab
// Navigate to subgraph folder in node library
await tab.getFolder('subgraph').click()
await comfyPage.nextFrame()
// Get initial subgraph node name in the library
const initialSubgraphNodeCount = await tab.getNode('Subgraph Node').count()
expect(initialSubgraphNodeCount).toBeGreaterThan(0)
// Get the subgraph node by ID (node 10 is the subgraph)
const subgraphNode = await comfyPage.getNodeRefById('10')
const nodePos = await subgraphNode.getPosition()
const nodeSize = await subgraphNode.getSize()
// Double-click on the title area of the subgraph node to edit
await comfyPage.canvas.dblclick({
position: {
x: nodePos.x + nodeSize.width / 2,
y: nodePos.y - 10 // Title area is above the node body
},
delay: 5
})
// Wait for title editor to appear
await expect(comfyPage.page.locator('.node-title-editor')).toBeVisible()
// Clear existing text and type new title
await comfyPage.page.keyboard.press('Control+a')
const newTitle = 'Renamed Subgraph Node'
await comfyPage.page.keyboard.type(newTitle)
await comfyPage.page.keyboard.press('Enter')
// Wait a frame for the update to complete
await comfyPage.nextFrame()
// Verify the node library shows the updated title
expect(await tab.getNode(newTitle).count()).toBeGreaterThan(0)
// Verify the old node name is no longer in the library
expect(await tab.getNode('Subgraph Node').count()).toBe(0)
})
})

View File

@@ -0,0 +1,55 @@
import { expect } from '@playwright/test'
import { comfyPageFixture as test } from '../fixtures/ComfyPage'
test.describe('Subgraph Persistence', () => {
test('Node library updates when subgraph title changes', async ({
comfyPage
}) => {
// Load a workflow with subgraphs to populate the node library
await comfyPage.loadWorkflow('nested-subgraph')
await comfyPage.nextFrame()
const tab = comfyPage.menu.nodeLibraryTab
// Navigate to subgraph folder in node library
await tab.getFolder('subgraph').click()
await comfyPage.nextFrame()
// Get initial subgraph node name in the library
const initialSubgraphNodeCount = await tab.getNode('Subgraph Node').count()
expect(initialSubgraphNodeCount).toBeGreaterThan(0)
// Get the subgraph node by ID (node 10 is the subgraph)
const subgraphNode = await comfyPage.getNodeRefById('10')
const nodePos = await subgraphNode.getPosition()
const nodeSize = await subgraphNode.getSize()
// Double-click on the title area of the subgraph node to edit
await comfyPage.canvas.dblclick({
position: {
x: nodePos.x + nodeSize.width / 2,
y: nodePos.y - 10 // Title area is above the node body
},
delay: 5
})
// Wait for title editor to appear
await expect(comfyPage.page.locator('.node-title-editor')).toBeVisible()
// Clear existing text and type new title
await comfyPage.page.keyboard.press('Control+a')
const newTitle = 'Renamed Subgraph Node'
await comfyPage.page.keyboard.type(newTitle)
await comfyPage.page.keyboard.press('Enter')
// Wait a frame for the update to complete
await comfyPage.nextFrame()
// Verify the node library shows the updated title
expect(await tab.getNode(newTitle).count()).toBeGreaterThan(0)
// Verify the old node name is no longer in the library
expect(await tab.getNode('Subgraph Node').count()).toBe(0)
})
})

View File

@@ -1,117 +0,0 @@
import { expect } from '@playwright/test'
import { SystemStats } from '../../src/schemas/apiSchema'
import { comfyPageFixture as test } from '../fixtures/ComfyPage'
test.describe('Version Mismatch Warnings', () => {
const ALWAYS_AHEAD_OF_INSTALLED_VERSION = '100.100.100'
const ALWAYS_BEHIND_INSTALLED_VERSION = '0.0.0'
const createMockSystemStatsRes = (
requiredFrontendVersion: string
): SystemStats => {
return {
system: {
os: 'posix',
ram_total: 67235385344,
ram_free: 13464207360,
comfyui_version: '0.3.46',
required_frontend_version: requiredFrontendVersion,
python_version: '3.12.3 (main, Jun 18 2025, 17:59:45) [GCC 13.3.0]',
pytorch_version: '2.6.0+cu124',
embedded_python: false,
argv: ['main.py']
},
devices: [
{
name: 'cuda:0 NVIDIA GeForce RTX 4070 : cudaMallocAsync',
type: 'cuda',
index: 0,
vram_total: 12557156352,
vram_free: 2439249920,
torch_vram_total: 0,
torch_vram_free: 0
}
]
}
}
test.beforeEach(async ({ comfyPage }) => {
await comfyPage.setSetting('Comfy.UseNewMenu', 'Top')
})
test('should show version mismatch warnings when installed version lower than required', async ({
comfyPage
}) => {
// Mock system_stats route to indicate that the installed version is always ahead of the required version
await comfyPage.page.route('**/system_stats**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
createMockSystemStatsRes(ALWAYS_AHEAD_OF_INSTALLED_VERSION)
)
})
})
await comfyPage.setup()
// Expect a warning toast to be shown
await expect(
comfyPage.page.getByText('Version Compatibility Warning')
).toBeVisible()
})
test('should not show version mismatch warnings when installed version is ahead of required', async ({
comfyPage
}) => {
// Mock system_stats route to indicate that the installed version is always ahead of the required version
await comfyPage.page.route('**/system_stats**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
createMockSystemStatsRes(ALWAYS_BEHIND_INSTALLED_VERSION)
)
})
})
await comfyPage.setup()
// Expect no warning toast to be shown
await expect(
comfyPage.page.getByText('Version Compatibility Warning')
).not.toBeVisible()
})
test('should persist dismissed state across sessions', async ({
comfyPage
}) => {
// Mock system_stats route to indicate that the installed version is always ahead of the required version
await comfyPage.page.route('**/system_stats**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(
createMockSystemStatsRes(ALWAYS_AHEAD_OF_INSTALLED_VERSION)
)
})
})
await comfyPage.setup()
// Locate the warning toast and dismiss it
const warningToast = comfyPage.page
.locator('div')
.filter({ hasText: 'Version Compatibility' })
.nth(3)
await warningToast.waitFor({ state: 'visible' })
const dismissButton = warningToast.getByRole('button', { name: 'Close' })
await dismissButton.click()
// Reload the page, keeping local storage
await comfyPage.setup({ clearStorage: false })
// The same warning from same versions should not be shown to the user again
await expect(
comfyPage.page.getByText('Version Compatibility Warning')
).not.toBeVisible()
})
})

72
dangerfile.ts Normal file
View File

@@ -0,0 +1,72 @@
import { danger, fail } from 'danger'
// Check if we should run the checks
const shouldRunChecks = async () => {
const allChangedFiles = [
...danger.git.modified_files,
...danger.git.created_files
]
const srcChanges = allChangedFiles.filter((file) => file.startsWith('src/'))
if (srcChanges.length === 0) {
return false
}
// Check total lines changed in src files
let totalLinesChanged = 0
for (const file of srcChanges) {
const diff = await danger.git.diffForFile(file)
if (diff) {
// Count only lines with actual content (non-empty after trimming whitespace)
// This excludes empty lines and lines containing only spaces/tabs
const additions =
diff.added?.split('\n').filter((line) => line.trim()).length || 0
const deletions =
diff.removed?.split('\n').filter((line) => line.trim()).length || 0
totalLinesChanged += additions + deletions
}
}
return totalLinesChanged > 3
}
// Check if browser tests were updated
const checkBrowserTestCoverage = () => {
const allChangedFiles = [
...danger.git.modified_files,
...danger.git.created_files
]
const hasBrowserTestChanges = allChangedFiles.some(
(file) => file.startsWith('browser_tests/') && file.endsWith('.ts')
)
if (!hasBrowserTestChanges) {
fail(`🧪 **E2E Test Coverage Missing**
All changes should be covered under E2E testing. Please add or update browser tests.`)
}
}
// Check for screen recording in PR description
const checkScreenRecording = () => {
const description = danger.github.pr.body || ''
const hasRecording =
/github\.com\/user-attachments\/assets\/[a-f0-9-]+/i.test(description) ||
/youtube\.com\/watch|youtu\.be\//i.test(description)
if (!hasRecording) {
fail(`📹 **Visual Documentation Missing**
Please add a screen recording or screenshot:
- GitHub: Drag & drop media to PR description
- YouTube: Add YouTube link`)
}
}
// Run the checks only if conditions are met
shouldRunChecks().then((shouldRun) => {
if (shouldRun) {
checkBrowserTestCoverage()
checkScreenRecording()
}
})

1004
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -40,12 +40,12 @@
"@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",
"@vitejs/plugin-vue": "^5.1.4",
"@vue/test-utils": "^2.4.6",
"autoprefixer": "^10.4.19",
"chalk": "^5.3.0",
"danger": "^13.0.4",
"eslint": "^9.12.0",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-prettier": "^5.2.6",
@@ -106,7 +106,6 @@
"pinia": "^2.1.7",
"primeicons": "^7.0.0",
"primevue": "^4.2.5",
"semver": "^7.7.2",
"three": "^0.170.0",
"tiptap-markdown": "^0.8.10",
"vue": "^3.5.13",

View File

@@ -22,9 +22,11 @@ import EditableText from '@/components/common/EditableText.vue'
import { useAbsolutePosition } from '@/composables/element/useAbsolutePosition'
import { app } from '@/scripts/app'
import { useCanvasStore, useTitleEditorStore } from '@/stores/graphStore'
import { useNodeDefStore } from '@/stores/nodeDefStore'
import { useSettingStore } from '@/stores/settingStore'
const settingStore = useSettingStore()
const nodeDefStore = useNodeDefStore()
const showInput = ref(false)
const editedTitle = ref('')
@@ -48,6 +50,9 @@ const onEdit = (newValue: string) => {
const target = titleEditorStore.titleEditorTarget
if (target instanceof LGraphNode && target.isSubgraphNode?.()) {
target.subgraph.name = trimmedTitle
// Also update the node definition display name in the store
nodeDefStore.updateNodeDefDisplayName(target.type, trimmedTitle)
}
app.graph.setDirtyCanvas(true, true)

View File

@@ -217,8 +217,7 @@ defineExpose({
display: flex;
flex-direction: column;
gap: 24px;
max-height: 80vh;
overflow-y: auto;
overflow: hidden;
padding: 32px 32px 24px;
border-radius: 12px;
}

View File

@@ -1,94 +0,0 @@
import { whenever } from '@vueuse/core'
import { computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useToastStore } from '@/stores/toastStore'
import { useVersionCompatibilityStore } from '@/stores/versionCompatibilityStore'
export interface UseFrontendVersionMismatchWarningOptions {
immediate?: boolean
}
/**
* Composable for handling frontend version mismatch warnings.
*
* Displays toast notifications when the frontend version is incompatible with the backend,
* either because the frontend is outdated or newer than the backend expects.
* Automatically dismisses warnings when shown and persists dismissal state for 7 days.
*
* @param options - Configuration options
* @param options.immediate - If true, automatically shows warning when version mismatch is detected
* @returns Object with methods and computed properties for managing version warnings
*
* @example
* ```ts
* // Show warning immediately when mismatch detected
* const { showWarning, shouldShowWarning } = useFrontendVersionMismatchWarning({ immediate: true })
*
* // Manual control
* const { showWarning } = useFrontendVersionMismatchWarning()
* showWarning() // Call when needed
* ```
*/
export function useFrontendVersionMismatchWarning(
options: UseFrontendVersionMismatchWarningOptions = {}
) {
const { immediate = false } = options
const { t } = useI18n()
const toastStore = useToastStore()
const versionCompatibilityStore = useVersionCompatibilityStore()
// Track if we've already shown the warning
let hasShownWarning = false
const showWarning = () => {
// Prevent showing the warning multiple times
if (hasShownWarning) return
const message = versionCompatibilityStore.warningMessage
if (!message) return
const detailMessage = t('g.frontendOutdated', {
frontendVersion: message.frontendVersion,
requiredVersion: message.requiredVersion
})
const fullMessage = t('g.versionMismatchWarningMessage', {
warning: t('g.versionMismatchWarning'),
detail: detailMessage
})
toastStore.addAlert(fullMessage)
hasShownWarning = true
// Automatically dismiss the warning so it won't show again for 7 days
versionCompatibilityStore.dismissWarning()
}
onMounted(() => {
// Only set up the watcher if immediate is true
if (immediate) {
whenever(
() => versionCompatibilityStore.shouldShowWarning,
() => {
showWarning()
},
{
immediate: true,
once: true
}
)
}
})
return {
showWarning,
shouldShowWarning: computed(
() => versionCompatibilityStore.shouldShowWarning
),
dismissWarning: versionCompatibilityStore.dismissWarning,
hasVersionMismatch: computed(
() => versionCompatibilityStore.hasVersionMismatch
)
}
}

View File

@@ -1,3 +0,0 @@
{
"supports_preview_metadata": false
}

View File

@@ -884,11 +884,5 @@ export const CORE_SETTINGS: SettingParams[] = [
name: 'Release seen timestamp',
type: 'hidden',
defaultValue: 0
},
{
id: 'Comfy.VersionMismatch.DismissedVersion',
name: 'Dismissed version mismatch warning',
type: 'hidden',
defaultValue: ''
}
]

View File

@@ -98,12 +98,6 @@
"nodes": "Nodes",
"community": "Community",
"all": "All",
"versionMismatchWarning": "Version Compatibility Warning",
"versionMismatchWarningMessage": "{warning}: {detail} Visit https://docs.comfy.org/installation/update_comfyui#common-update-issues for update instructions.",
"frontendOutdated": "Frontend version {frontendVersion} is outdated. Backend requires {requiredVersion} or higher.",
"frontendNewer": "Frontend version {frontendVersion} may not be compatible with backend version {backendVersion}.",
"updateFrontend": "Update Frontend",
"dismiss": "Dismiss",
"update": "Update",
"updated": "Updated",
"resultsCount": "Found {count} Results",
@@ -1343,13 +1337,6 @@
"outdatedVersionGeneric": "Some nodes require a newer version of ComfyUI. Please update to use all nodes.",
"coreNodesFromVersion": "Requires ComfyUI {version}:"
},
"versionMismatchWarning": {
"title": "Version Compatibility Warning",
"frontendOutdated": "Frontend version {frontendVersion} is outdated. Backend requires version {requiredVersion} or higher.",
"frontendNewer": "Frontend version {frontendVersion} may not be compatible with backend version {backendVersion}.",
"updateFrontend": "Update Frontend",
"dismiss": "Dismiss"
},
"errorDialog": {
"defaultTitle": "An error occurred",
"loadWorkflowTitle": "Loading aborted due to error reloading workflow data",

View File

@@ -113,8 +113,6 @@ const zLogRawResponse = z.object({
entries: z.array(zLogEntry)
})
const zFeatureFlagsWsMessage = z.record(z.string(), z.any())
export type StatusWsMessageStatus = z.infer<typeof zStatusWsMessageStatus>
export type StatusWsMessage = z.infer<typeof zStatusWsMessage>
export type ProgressWsMessage = z.infer<typeof zProgressWsMessage>
@@ -134,7 +132,6 @@ export type ProgressTextWsMessage = z.infer<typeof zProgressTextWsMessage>
export type DisplayComponentWsMessage = z.infer<
typeof zDisplayComponentWsMessage
>
export type FeatureFlagsWsMessage = z.infer<typeof zFeatureFlagsWsMessage>
// End of ws messages
const zPromptInputItem = z.object({
@@ -320,7 +317,6 @@ export const zSystemStats = z.object({
embedded_python: z.boolean(),
comfyui_version: z.string(),
pytorch_version: z.string(),
required_frontend_version: z.string().optional(),
argv: z.array(z.string()),
ram_total: z.number(),
ram_free: z.number()
@@ -486,8 +482,6 @@ const zSettings = z.object({
"what's new seen"
]),
'Comfy.Release.Timestamp': z.number(),
/** Version compatibility settings */
'Comfy.VersionMismatch.DismissedVersion': z.string(),
/** Settings used for testing */
'test.setting': z.any(),
'main.sub.setting.name': z.any(),

View File

@@ -1,6 +1,5 @@
import axios from 'axios'
import defaultClientFeatureFlags from '@/config/clientFeatureFlags.json'
import type {
DisplayComponentWsMessage,
EmbeddingsResponse,
@@ -12,7 +11,6 @@ import type {
ExecutionStartWsMessage,
ExecutionSuccessWsMessage,
ExtensionsResponse,
FeatureFlagsWsMessage,
HistoryTaskItem,
LogsRawResponse,
LogsWsMessage,
@@ -107,7 +105,6 @@ interface BackendApiCalls {
b_preview: Blob
progress_text: ProgressTextWsMessage
display_component: DisplayComponentWsMessage
feature_flags: FeatureFlagsWsMessage
}
/** Dictionary of all api calls */
@@ -237,19 +234,6 @@ export class ComfyApi extends EventTarget {
reportedUnknownMessageTypes = new Set<string>()
/**
* Get feature flags supported by this frontend client.
* Returns a copy to prevent external modification.
*/
getClientFeatureFlags(): Record<string, unknown> {
return { ...defaultClientFeatureFlags }
}
/**
* Feature flags received from the backend server.
*/
serverFeatureFlags: Record<string, unknown> = {}
/**
* 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
@@ -391,15 +375,6 @@ export class ComfyApi extends EventTarget {
this.socket.addEventListener('open', () => {
opened = true
// Send feature flags as the first message
this.socket!.send(
JSON.stringify({
type: 'feature_flags',
data: this.getClientFeatureFlags()
})
)
if (isReconnect) {
this.dispatchCustomEvent('reconnected')
}
@@ -493,14 +468,6 @@ export class ComfyApi extends EventTarget {
case 'b_preview':
this.dispatchCustomEvent(msg.type, msg.data)
break
case 'feature_flags':
// Store server feature flags
this.serverFeatureFlags = msg.data
console.log(
'Server feature flags received:',
this.serverFeatureFlags
)
break
default:
if (this.#registered.has(msg.type)) {
// Fallback for custom types - calls super direct.
@@ -995,33 +962,6 @@ export class ComfyApi extends EventTarget {
async getCustomNodesI18n(): Promise<Record<string, any>> {
return (await axios.get(this.apiURL('/i18n'))).data
}
/**
* Checks if the server supports a specific feature.
* @param featureName The name of the feature to check
* @returns true if the feature is supported, false otherwise
*/
serverSupportsFeature(featureName: string): boolean {
return this.serverFeatureFlags[featureName] === true
}
/**
* Gets a server feature flag value.
* @param featureName The name of the feature to get
* @param defaultValue The default value if the feature is not found
* @returns The feature value or default
*/
getServerFeature<T = unknown>(featureName: string, defaultValue?: T): T {
return (this.serverFeatureFlags[featureName] ?? defaultValue) as T
}
/**
* Gets all server feature flags.
* @returns Copy of all server feature flags
*/
getServerFeatures(): Record<string, unknown> {
return { ...this.serverFeatureFlags }
}
}
export const api = new ComfyApi()

View File

@@ -135,7 +135,6 @@ The following table lists ALL stores in the system as of 2025-01-30:
| toastStore.ts | Manages toast notifications | UI |
| userFileStore.ts | Manages user file operations | Files |
| userStore.ts | Manages user data and preferences | User |
| versionCompatibilityStore.ts | Manages frontend/backend version compatibility warnings | Core |
| widgetStore.ts | Manages widget configurations | Widgets |
| workflowStore.ts | Handles workflow data and operations | Workflows |
| workflowTemplatesStore.ts | Manages workflow templates | Workflows |

View File

@@ -1,4 +1,4 @@
import type { LGraphNode } from '@comfyorg/litegraph'
import { type LGraphNode, LiteGraph } from '@comfyorg/litegraph'
import axios from 'axios'
import _ from 'lodash'
import { defineStore } from 'pinia'
@@ -304,6 +304,28 @@ export const useNodeDefStore = defineStore('nodeDef', () => {
nodeDefsByName.value[nodeDef.name] = nodeDefImpl
nodeDefsByDisplayName.value[nodeDef.display_name] = nodeDefImpl
}
function updateNodeDefDisplayName(nodeType: string, newDisplayName: string) {
const existingNodeDef = nodeDefsByName.value[nodeType]
if (!existingNodeDef) return
// Remove old display name mapping
delete nodeDefsByDisplayName.value[existingNodeDef.display_name]
// Clone and mutate like bookmark store does to preserve references
const clonedNodeDef = _.clone(existingNodeDef) as any
clonedNodeDef.display_name = newDisplayName
// Update both mappings
nodeDefsByName.value[nodeType] = clonedNodeDef
nodeDefsByDisplayName.value[newDisplayName] = clonedNodeDef
// Also update the LiteGraph registered node type's static title
// This is necessary for new instances to use the updated display name
const RegisteredNodeClass = LiteGraph.registered_node_types[nodeType]
if (RegisteredNodeClass) {
RegisteredNodeClass.title = newDisplayName
}
}
function fromLGraphNode(node: LGraphNode): ComfyNodeDefImpl | null {
// Frontend-only nodes don't have nodeDef
// @ts-expect-error Optional chaining used in index
@@ -324,6 +346,7 @@ export const useNodeDefStore = defineStore('nodeDef', () => {
updateNodeDefs,
addNodeDef,
updateNodeDefDisplayName,
fromLGraphNode
}
})

View File

@@ -1,138 +0,0 @@
import { useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'
import * as semver from 'semver'
import { computed } from 'vue'
import config from '@/config'
import { useSystemStatsStore } from '@/stores/systemStatsStore'
const DISMISSAL_DURATION_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
export const useVersionCompatibilityStore = defineStore(
'versionCompatibility',
() => {
const systemStatsStore = useSystemStatsStore()
const frontendVersion = computed(() => config.app_version)
const backendVersion = computed(
() => systemStatsStore.systemStats?.system?.comfyui_version ?? ''
)
const requiredFrontendVersion = computed(
() =>
systemStatsStore.systemStats?.system?.required_frontend_version ?? ''
)
const isFrontendOutdated = computed(() => {
if (
!frontendVersion.value ||
!requiredFrontendVersion.value ||
!semver.valid(frontendVersion.value) ||
!semver.valid(requiredFrontendVersion.value)
) {
return false
}
// Returns true if required version is greater than frontend version
return semver.gt(requiredFrontendVersion.value, frontendVersion.value)
})
const isFrontendNewer = computed(() => {
// We don't warn about frontend being newer than backend
// Only warn when frontend is outdated (behind required version)
return false
})
const hasVersionMismatch = computed(() => {
return isFrontendOutdated.value
})
const versionKey = computed(() => {
if (
!frontendVersion.value ||
!backendVersion.value ||
!requiredFrontendVersion.value
) {
return null
}
return `${frontendVersion.value}-${backendVersion.value}-${requiredFrontendVersion.value}`
})
// Use reactive storage for dismissals - creates a reactive ref that syncs with localStorage
// All version mismatch dismissals are stored in a single object for clean localStorage organization
const dismissalStorage = useStorage(
'comfy.versionMismatch.dismissals',
{} as Record<string, number>,
localStorage,
{
serializer: {
read: (value: string) => {
try {
return JSON.parse(value)
} catch {
return {}
}
},
write: (value: Record<string, number>) => JSON.stringify(value)
}
}
)
const isDismissed = computed(() => {
if (!versionKey.value) return false
const dismissedUntil = dismissalStorage.value[versionKey.value]
if (!dismissedUntil) return false
// Check if dismissal has expired
return Date.now() < dismissedUntil
})
const shouldShowWarning = computed(() => {
return hasVersionMismatch.value && !isDismissed.value
})
const warningMessage = computed(() => {
if (isFrontendOutdated.value) {
return {
type: 'outdated' as const,
frontendVersion: frontendVersion.value,
requiredVersion: requiredFrontendVersion.value
}
}
return null
})
async function checkVersionCompatibility() {
if (!systemStatsStore.systemStats) {
await systemStatsStore.fetchSystemStats()
}
}
function dismissWarning() {
if (!versionKey.value) return
const dismissUntil = Date.now() + DISMISSAL_DURATION_MS
dismissalStorage.value = {
...dismissalStorage.value,
[versionKey.value]: dismissUntil
}
}
async function initialize() {
await checkVersionCompatibility()
}
return {
frontendVersion,
backendVersion,
requiredFrontendVersion,
hasVersionMismatch,
shouldShowWarning,
warningMessage,
isFrontendOutdated,
isFrontendNewer,
checkVersionCompatibility,
dismissWarning,
initialize
}
}
)

View File

@@ -699,27 +699,6 @@ export interface paths {
patch?: never
trace?: never
}
'/publishers/{publisherId}/nodes/{nodeId}/claim-my-node': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
get?: never
put?: never
/**
* Claim nodeId into publisherId for the authenticated publisher
* @description This endpoint allows a publisher to claim an unclaimed node that they own the repo, which is identified by the nodeId. The unclaimed node's repository must be owned by the authenticated user.
*
*/
post: operations['claimMyNode']
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
'/publishers/{publisherId}/nodes/v2': {
parameters: {
query?: never
@@ -1082,23 +1061,6 @@ export interface paths {
patch?: never
trace?: never
}
'/bulk/nodes/versions': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
get?: never
put?: never
/** Retrieve multiple node versions in a single request */
post: operations['getBulkNodeVersions']
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
'/versions': {
parameters: {
query?: never
@@ -1133,26 +1095,6 @@ export interface paths {
patch?: never
trace?: never
}
'/admin/nodes/{nodeId}': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
get?: never
/**
* Admin Update Node
* @description Only admins can update a node with admin privileges.
*/
put: operations['adminUpdateNode']
post?: never
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
'/admin/nodes/{nodeId}/versions/{versionNumber}': {
parameters: {
query?: never
@@ -3009,7 +2951,7 @@ export interface paths {
patch?: never
trace?: never
}
'/proxy/moonvalley/prompts/text-to-video': {
'/proxy/moonvalley/text-to-video': {
parameters: {
query?: never
header?: never
@@ -3026,7 +2968,7 @@ export interface paths {
patch?: never
trace?: never
}
'/proxy/moonvalley/prompts/text-to-image': {
'/proxy/moonvalley/text-to-image': {
parameters: {
query?: never
header?: never
@@ -3115,37 +3057,6 @@ export interface paths {
export type webhooks = Record<string, never>
export interface components {
schemas: {
ClaimMyNodeRequest: {
/** @description GitHub token to verify if the user owns the repo of the node */
GH_TOKEN: string
}
BulkNodeVersionsRequest: {
/** @description List of node ID and version pairs to retrieve */
node_versions: components['schemas']['NodeVersionIdentifier'][]
}
NodeVersionIdentifier: {
/** @description The unique identifier of the node */
node_id: string
/** @description The version of the node */
version: string
}
BulkNodeVersionsResponse: {
/** @description List of retrieved node versions with their status */
node_versions: components['schemas']['BulkNodeVersionResult'][]
}
BulkNodeVersionResult: {
/** @description The node and version identifier */
identifier: components['schemas']['NodeVersionIdentifier']
/**
* @description Status of the retrieval operation
* @enum {string}
*/
status: 'success' | 'not_found' | 'error'
/** @description The retrieved node version data (only present if status is success) */
node_version?: components['schemas']['NodeVersion']
/** @description Error message if retrieval failed (only present if status is error) */
error_message?: string
}
PersonalAccessToken: {
/**
* Format: uuid
@@ -8802,212 +8713,71 @@ export interface components {
| 'computer-use-preview'
| 'computer-use-preview-2025-03-11'
| 'chatgpt-4o-latest'
MoonvalleyTextToVideoInferenceParams: {
/**
* @description Height of the generated video in pixels
* @default 1080
*/
MoonvalleyInferenceParams: {
/** @default 1080 */
height: number
/**
* @description Width of the generated video in pixels
* @default 1920
*/
/** @default 1920 */
width: number
/**
* @description Number of frames to generate
* @default 64
*/
/** @default 64 */
num_frames: number
/**
* @description Frames per second of the generated video
* @default 24
*/
/** @default 24 */
fps: number
/**
* Format: float
* @description Guidance scale for generation control
* @default 10
* @default 12.5
*/
guidance_scale: number
/** @description Random seed for generation (default: random) */
seed?: number
/**
* @description Number of denoising steps
* @default 80
*/
/** @default 80 */
steps: number
/**
* @description Whether to use timestep transformation
* @default true
*/
/** @default true */
use_timestep_transform: boolean
/**
* Format: float
* @description Shift value for generation control
* @default 3
*/
shift_value: number
/**
* @description Whether to use guidance scheduling
* @default true
*/
/** @default true */
use_guidance_schedule: boolean
/**
* @description Whether to add quality guidance
* @default true
*/
/** @default true */
add_quality_guidance: boolean
/**
* Format: float
* @description CLIP value for generation control
* @default 3
*/
clip_value: number
/**
* @description Whether to use negative prompts
* @default false
*/
/** @default false */
use_negative_prompts: boolean
/** @description Negative prompt text */
negative_prompt?: string
/**
* @description Number of warmup steps (calculated based on num_frames)
* @default 0
*/
warmup_steps: number
/**
* @description Number of cooldown steps (calculated based on num_frames)
* @default 75
*/
cooldown_steps: number
warmup_steps?: number
cooldown_steps?: number
/**
* Format: float
* @description Caching coefficient for optimization
* @default 0.3
*/
caching_coefficient: number
/**
* @description Number of caching warmup steps
* @default 3
*/
/** @default 3 */
caching_warmup: number
/**
* @description Number of caching cooldown steps
* @default 3
*/
/** @default 3 */
caching_cooldown: number
/**
* @description Index of the conditioning frame
* @default 0
*/
conditioning_frame_index: number
}
MoonvalleyVideoToVideoInferenceParams: {
/**
* Format: float
* @description Guidance scale for generation control
* @default 15
*/
guidance_scale: number
/** @description Random seed for generation (default: random) */
seed?: number
/**
* @description Number of denoising steps
* @default 80
*/
steps: number
/**
* @description Whether to use timestep transformation
* @default true
*/
use_timestep_transform: boolean
/**
* Format: float
* @description Shift value for generation control
* @default 3
*/
shift_value: number
/**
* @description Whether to use guidance scheduling
* @default true
*/
use_guidance_schedule: boolean
/**
* @description Whether to add quality guidance
* @default true
*/
add_quality_guidance: boolean
/**
* Format: float
* @description CLIP value for generation control
* @default 3
*/
clip_value: number
/**
* @description Whether to use negative prompts
* @default false
*/
use_negative_prompts: boolean
/** @description Negative prompt text */
negative_prompt?: string
/**
* @description Number of warmup steps (calculated based on num_frames)
* @default 24
*/
warmup_steps: number
/**
* @description Number of cooldown steps (calculated based on num_frames)
* @default 36
*/
cooldown_steps: number
/**
* Format: float
* @description Caching coefficient for optimization
* @default 0.3
*/
caching_coefficient: number
/**
* @description Number of caching warmup steps
* @default 3
*/
caching_warmup: number
/**
* @description Number of caching cooldown steps
* @default 3
*/
caching_cooldown: number
/**
* @description Index of the conditioning frame
* @default 0
*/
/** @default 0 */
conditioning_frame_index: number
}
MoonvalleyTextToImageRequest: {
prompt_text?: string
image_url?: string
inference_params?: components['schemas']['MoonvalleyTextToVideoInferenceParams']
inference_params?: components['schemas']['MoonvalleyInferenceParams']
webhook_url?: string
}
MoonvalleyTextToVideoRequest: {
prompt_text?: string
image_url?: string
inference_params?: components['schemas']['MoonvalleyTextToVideoInferenceParams']
inference_params?: components['schemas']['MoonvalleyInferenceParams']
webhook_url?: string
}
MoonvalleyVideoToVideoRequest: {
/** @description Describes the video to generate */
prompt_text: string
/** @description Url to control video */
MoonvalleyVideoToVideoRequest: components['schemas']['MoonvalleyTextToVideoRequest'] & {
video_url: string
/**
* @description Supported types for video control
* @enum {string}
*/
control_type: 'motion_control' | 'pose_control'
/** @description Parameters for video-to-video generation inference */
inference_params?: components['schemas']['MoonvalleyVideoToVideoInferenceParams']
/** @description Optional webhook URL for notifications */
webhook_url?: string
control_type: string
}
MoonvalleyPromptResponse: {
id?: string
@@ -10651,89 +10421,6 @@ export interface operations {
}
}
}
claimMyNode: {
parameters: {
query?: never
header?: never
path: {
publisherId: string
nodeId: string
}
cookie?: never
}
requestBody: {
content: {
'application/json': components['schemas']['ClaimMyNodeRequest']
}
}
responses: {
/** @description Node claimed successfully */
204: {
headers: {
[name: string]: unknown
}
content?: never
}
/** @description Bad request, invalid input data */
400: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Unauthorized */
401: {
headers: {
[name: string]: unknown
}
content?: never
}
/** @description Forbidden - various authorization and permission issues
* Includes:
* - The authenticated user does not have permission to claim the node
* - The node is already claimed by another publisher
* - The GH_TOKEN is invalid
* - The repository is not owned by the authenticated GitHub user
* */
403: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Too many requests - GitHub API rate limit exceeded */
429: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Internal server error */
500: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Service unavailable - GitHub API is currently unavailable */
503: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
}
}
listNodesForPublisherV2: {
parameters: {
query?: {
@@ -12022,48 +11709,6 @@ export interface operations {
}
}
}
getBulkNodeVersions: {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
requestBody: {
content: {
'application/json': components['schemas']['BulkNodeVersionsRequest']
}
}
responses: {
/** @description Successfully retrieved node versions */
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['BulkNodeVersionsResponse']
}
}
/** @description Bad request, invalid input */
400: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Internal server error */
500: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
}
}
listAllNodeVersions: {
parameters: {
query?: {
@@ -12189,75 +11834,6 @@ export interface operations {
}
}
}
adminUpdateNode: {
parameters: {
query?: never
header?: never
path: {
nodeId: string
}
cookie?: never
}
requestBody: {
content: {
'application/json': components['schemas']['Node']
}
}
responses: {
/** @description Node updated successfully */
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Node']
}
}
/** @description Bad request, invalid input data. */
400: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Unauthorized */
401: {
headers: {
[name: string]: unknown
}
content?: never
}
/** @description Forbidden */
403: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Node not found */
404: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
/** @description Internal server error */
500: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['ErrorResponse']
}
}
}
}
adminUpdateNodeVersion: {
parameters: {
query?: never

View File

@@ -23,14 +23,7 @@
import { useBreakpoints, useEventListener } from '@vueuse/core'
import type { ToastMessageOptions } from 'primevue/toast'
import { useToast } from 'primevue/usetoast'
import {
computed,
nextTick,
onBeforeUnmount,
onMounted,
watch,
watchEffect
} from 'vue'
import { computed, onBeforeUnmount, onMounted, watch, watchEffect } from 'vue'
import { useI18n } from 'vue-i18n'
import MenuHamburger from '@/components/MenuHamburger.vue'
@@ -42,7 +35,6 @@ import TopMenubar from '@/components/topbar/TopMenubar.vue'
import { useBrowserTabTitle } from '@/composables/useBrowserTabTitle'
import { useCoreCommands } from '@/composables/useCoreCommands'
import { useErrorHandling } from '@/composables/useErrorHandling'
import { useFrontendVersionMismatchWarning } from '@/composables/useFrontendVersionMismatchWarning'
import { useProgressFavicon } from '@/composables/useProgressFavicon'
import { SERVER_CONFIG_ITEMS } from '@/constants/serverConfig'
import { i18n } from '@/i18n'
@@ -62,7 +54,6 @@ import {
} from '@/stores/queueStore'
import { useServerConfigStore } from '@/stores/serverConfigStore'
import { useSettingStore } from '@/stores/settingStore'
import { useVersionCompatibilityStore } from '@/stores/versionCompatibilityStore'
import { useBottomPanelStore } from '@/stores/workspace/bottomPanelStore'
import { useColorPaletteStore } from '@/stores/workspace/colorPaletteStore'
import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore'
@@ -79,8 +70,6 @@ const settingStore = useSettingStore()
const executionStore = useExecutionStore()
const colorPaletteStore = useColorPaletteStore()
const queueStore = useQueueStore()
const versionCompatibilityStore = useVersionCompatibilityStore()
const breakpoints = useBreakpoints({ md: 961 })
const isMobile = breakpoints.smaller('md')
const showTopMenu = computed(() => isMobile.value || useNewMenu.value === 'Top')
@@ -235,22 +224,6 @@ onBeforeUnmount(() => {
useEventListener(window, 'keydown', useKeybindingService().keybindHandler)
const { wrapWithErrorHandling, wrapWithErrorHandlingAsync } = useErrorHandling()
// Initialize version mismatch warning in setup context
// It will be triggered automatically when the store is ready
useFrontendVersionMismatchWarning({ immediate: true })
// Initialize version compatibility check completely independently of app setup
// This runs asynchronously after component setup and won't block the main application
void nextTick(() => {
// Use setTimeout to ensure this happens after all other immediate tasks
setTimeout(() => {
versionCompatibilityStore.initialize().catch((error) => {
console.warn('Version compatibility check failed:', error)
})
}, 100) // Small delay to ensure app is fully loaded
})
const onGraphReady = () => {
requestIdleCallback(
() => {

View File

@@ -1,208 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { api } from '@/scripts/api'
describe('API Feature Flags', () => {
let mockWebSocket: any
const wsEventHandlers: { [key: string]: (event: any) => void } = {}
beforeEach(() => {
// Use fake timers
vi.useFakeTimers()
// Mock WebSocket
mockWebSocket = {
readyState: 1, // WebSocket.OPEN
send: vi.fn(),
close: vi.fn(),
addEventListener: vi.fn(
(event: string, handler: (event: any) => void) => {
wsEventHandlers[event] = handler
}
),
removeEventListener: vi.fn()
}
// Mock WebSocket constructor
global.WebSocket = vi.fn().mockImplementation(() => mockWebSocket) as any
// Reset API state
api.serverFeatureFlags = {}
// Mock getClientFeatureFlags to return test feature flags
vi.spyOn(api, 'getClientFeatureFlags').mockReturnValue({
supports_preview_metadata: true,
api_version: '1.0.0',
capabilities: ['bulk_operations', 'async_nodes']
})
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
describe('Feature flags negotiation', () => {
it('should send client feature flags as first message on connection', async () => {
// Initialize API connection
const initPromise = api.init()
// Simulate connection open
wsEventHandlers['open'](new Event('open'))
// Check that feature flags were sent as first message
expect(mockWebSocket.send).toHaveBeenCalledTimes(1)
const sentMessage = JSON.parse(mockWebSocket.send.mock.calls[0][0])
expect(sentMessage).toEqual({
type: 'feature_flags',
data: {
supports_preview_metadata: true,
api_version: '1.0.0',
capabilities: ['bulk_operations', 'async_nodes']
}
})
// Simulate server response with status message
wsEventHandlers['message']({
data: JSON.stringify({
type: 'status',
data: {
status: { exec_info: { queue_remaining: 0 } },
sid: 'test-sid'
}
})
})
// Simulate server feature flags response
wsEventHandlers['message']({
data: JSON.stringify({
type: 'feature_flags',
data: {
supports_preview_metadata: true,
async_execution: true,
supported_formats: ['webp', 'jpeg', 'png'],
api_version: '1.0.0',
max_upload_size: 104857600,
capabilities: ['isolated_nodes', 'dynamic_models']
}
})
})
await initPromise
// Check that server features were stored
expect(api.serverFeatureFlags).toEqual({
supports_preview_metadata: true,
async_execution: true,
supported_formats: ['webp', 'jpeg', 'png'],
api_version: '1.0.0',
max_upload_size: 104857600,
capabilities: ['isolated_nodes', 'dynamic_models']
})
})
it('should handle server without feature flags support', async () => {
// Initialize API connection
const initPromise = api.init()
// Simulate connection open
wsEventHandlers['open'](new Event('open'))
// Clear the send mock to reset
mockWebSocket.send.mockClear()
// Simulate server response with status but no feature flags
wsEventHandlers['message']({
data: JSON.stringify({
type: 'status',
data: {
status: { exec_info: { queue_remaining: 0 } },
sid: 'test-sid'
}
})
})
// Simulate some other message (not feature flags)
wsEventHandlers['message']({
data: JSON.stringify({
type: 'execution_start',
data: {}
})
})
await initPromise
// Server features should remain empty
expect(api.serverFeatureFlags).toEqual({})
})
})
describe('Feature checking methods', () => {
beforeEach(() => {
// Set up some test features
api.serverFeatureFlags = {
supports_preview_metadata: true,
async_execution: false,
capabilities: ['isolated_nodes', 'dynamic_models']
}
})
it('should check if server supports a boolean feature', () => {
expect(api.serverSupportsFeature('supports_preview_metadata')).toBe(true)
expect(api.serverSupportsFeature('async_execution')).toBe(false)
expect(api.serverSupportsFeature('non_existent_feature')).toBe(false)
})
it('should get server feature value', () => {
expect(api.getServerFeature('supports_preview_metadata')).toBe(true)
expect(api.getServerFeature('capabilities')).toEqual([
'isolated_nodes',
'dynamic_models'
])
expect(api.getServerFeature('non_existent_feature')).toBeUndefined()
})
})
describe('Client feature flags configuration', () => {
it('should use mocked client feature flags', () => {
// Verify mocked flags are returned
const clientFlags = api.getClientFeatureFlags()
expect(clientFlags).toEqual({
supports_preview_metadata: true,
api_version: '1.0.0',
capabilities: ['bulk_operations', 'async_nodes']
})
})
it('should return a copy of client feature flags', () => {
// Temporarily restore the real implementation for this test
vi.mocked(api.getClientFeatureFlags).mockRestore()
// Verify that modifications to returned object don't affect original
const clientFlags1 = api.getClientFeatureFlags()
const clientFlags2 = api.getClientFeatureFlags()
// Should be different objects
expect(clientFlags1).not.toBe(clientFlags2)
// But with same content
expect(clientFlags1).toEqual(clientFlags2)
// Modifying one should not affect the other
clientFlags1.test_flag = true
expect(api.getClientFeatureFlags()).not.toHaveProperty('test_flag')
})
})
describe('Integration with preview messages', () => {
it('should affect preview message handling based on feature support', () => {
// Test with metadata support
api.serverFeatureFlags = { supports_preview_metadata: true }
expect(api.serverSupportsFeature('supports_preview_metadata')).toBe(true)
// Test without metadata support
api.serverFeatureFlags = {}
expect(api.serverSupportsFeature('supports_preview_metadata')).toBe(false)
})
})
})

View File

@@ -1,234 +0,0 @@
import { createPinia, setActivePinia } from 'pinia'
import { vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { nextTick } from 'vue'
import { useFrontendVersionMismatchWarning } from '@/composables/useFrontendVersionMismatchWarning'
import { useToastStore } from '@/stores/toastStore'
import { useVersionCompatibilityStore } from '@/stores/versionCompatibilityStore'
// Mock globals
//@ts-expect-error Define global for the test
global.__COMFYUI_FRONTEND_VERSION__ = '1.0.0'
// Mock config first - this needs to be before any imports
vi.mock('@/config', () => ({
default: {
app_title: 'ComfyUI',
app_version: '1.0.0'
}
}))
// Mock app
vi.mock('@/scripts/app', () => ({
app: {
ui: {
settings: {
dispatchChange: vi.fn()
}
}
}
}))
// Mock api
vi.mock('@/scripts/api', () => ({
api: {
getSettings: vi.fn(() => Promise.resolve({})),
storeSetting: vi.fn(() => Promise.resolve(undefined))
}
}))
// Mock vue-i18n
vi.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string, params?: any) => {
if (key === 'g.versionMismatchWarning')
return 'Version Compatibility Warning'
if (key === 'g.versionMismatchWarningMessage' && params) {
return `${params.warning}: ${params.detail} Visit https://docs.comfy.org/installation/update_comfyui#common-update-issues for update instructions.`
}
if (key === 'g.frontendOutdated' && params) {
return `Frontend version ${params.frontendVersion} is outdated. Backend requires ${params.requiredVersion} or higher.`
}
if (key === 'g.frontendNewer' && params) {
return `Frontend version ${params.frontendVersion} may not be compatible with backend version ${params.backendVersion}.`
}
return key
}
}),
createI18n: vi.fn(() => ({
global: {
locale: { value: 'en' },
t: vi.fn()
}
}))
}))
// Mock lifecycle hooks to track their calls
const mockOnMounted = vi.fn()
vi.mock('vue', async (importOriginal) => {
const actual = await importOriginal<typeof import('vue')>()
return {
...actual,
onMounted: (fn: () => void) => {
mockOnMounted()
fn()
}
}
})
describe('useFrontendVersionMismatchWarning', () => {
beforeEach(() => {
vi.clearAllMocks()
setActivePinia(createPinia())
})
afterEach(() => {
vi.restoreAllMocks()
})
it('should not show warning when there is no version mismatch', () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
// Mock no version mismatch
vi.spyOn(versionStore, 'shouldShowWarning', 'get').mockReturnValue(false)
useFrontendVersionMismatchWarning()
expect(addAlertSpy).not.toHaveBeenCalled()
})
it('should show warning immediately when immediate option is true and there is a mismatch', async () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
const dismissWarningSpy = vi.spyOn(versionStore, 'dismissWarning')
// Mock version mismatch
vi.spyOn(versionStore, 'shouldShowWarning', 'get').mockReturnValue(true)
vi.spyOn(versionStore, 'warningMessage', 'get').mockReturnValue({
type: 'outdated',
frontendVersion: '1.0.0',
requiredVersion: '2.0.0'
})
useFrontendVersionMismatchWarning({ immediate: true })
// For immediate: true, the watcher should fire immediately in onMounted
await nextTick()
expect(addAlertSpy).toHaveBeenCalledWith(
expect.stringContaining('Version Compatibility Warning')
)
expect(addAlertSpy).toHaveBeenCalledWith(
expect.stringContaining('Frontend version 1.0.0 is outdated')
)
// Should automatically dismiss the warning
expect(dismissWarningSpy).toHaveBeenCalled()
})
it('should not show warning immediately when immediate option is false', async () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
// Mock version mismatch
vi.spyOn(versionStore, 'shouldShowWarning', 'get').mockReturnValue(true)
vi.spyOn(versionStore, 'warningMessage', 'get').mockReturnValue({
type: 'outdated',
frontendVersion: '1.0.0',
requiredVersion: '2.0.0'
})
const result = useFrontendVersionMismatchWarning({ immediate: false })
await nextTick()
// Should not show automatically
expect(addAlertSpy).not.toHaveBeenCalled()
// But should show when called manually
result.showWarning()
expect(addAlertSpy).toHaveBeenCalledOnce()
})
it('should call showWarning method manually', () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
const dismissWarningSpy = vi.spyOn(versionStore, 'dismissWarning')
vi.spyOn(versionStore, 'warningMessage', 'get').mockReturnValue({
type: 'outdated',
frontendVersion: '1.0.0',
requiredVersion: '2.0.0'
})
const { showWarning } = useFrontendVersionMismatchWarning()
showWarning()
expect(addAlertSpy).toHaveBeenCalledOnce()
expect(dismissWarningSpy).toHaveBeenCalled()
})
it('should expose store methods and computed values', () => {
const versionStore = useVersionCompatibilityStore()
const mockDismissWarning = vi.fn()
vi.spyOn(versionStore, 'dismissWarning').mockImplementation(
mockDismissWarning
)
vi.spyOn(versionStore, 'shouldShowWarning', 'get').mockReturnValue(true)
vi.spyOn(versionStore, 'hasVersionMismatch', 'get').mockReturnValue(true)
const result = useFrontendVersionMismatchWarning()
expect(result.shouldShowWarning.value).toBe(true)
expect(result.hasVersionMismatch.value).toBe(true)
void result.dismissWarning()
expect(mockDismissWarning).toHaveBeenCalled()
})
it('should register onMounted hook', () => {
useFrontendVersionMismatchWarning()
expect(mockOnMounted).toHaveBeenCalledOnce()
})
it('should not show warning when warningMessage is null', () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
vi.spyOn(versionStore, 'warningMessage', 'get').mockReturnValue(null)
const { showWarning } = useFrontendVersionMismatchWarning()
showWarning()
expect(addAlertSpy).not.toHaveBeenCalled()
})
it('should only show warning once even if called multiple times', () => {
const toastStore = useToastStore()
const versionStore = useVersionCompatibilityStore()
const addAlertSpy = vi.spyOn(toastStore, 'addAlert')
vi.spyOn(versionStore, 'warningMessage', 'get').mockReturnValue({
type: 'outdated',
frontendVersion: '1.0.0',
requiredVersion: '2.0.0'
})
const { showWarning } = useFrontendVersionMismatchWarning()
// Call showWarning multiple times
showWarning()
showWarning()
showWarning()
// Should only have been called once
expect(addAlertSpy).toHaveBeenCalledTimes(1)
})
})

View File

@@ -0,0 +1,142 @@
import { LiteGraph } from '@comfyorg/litegraph'
import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ComfyNodeDef as ComfyNodeDefV1 } from '@/schemas/nodeDefSchema'
import { ComfyNodeDefImpl, useNodeDefStore } from '@/stores/nodeDefStore'
// Mock LiteGraph
vi.mock('@comfyorg/litegraph', async () => {
const actual = await vi.importActual('@comfyorg/litegraph')
return {
...actual,
LiteGraph: {
registered_node_types: {}
}
}
})
describe('useNodeDefStore', () => {
let store: ReturnType<typeof useNodeDefStore>
beforeEach(() => {
// Set up Pinia
setActivePinia(createPinia())
// Create fresh store instance
store = useNodeDefStore()
// Clear registered node types
LiteGraph.registered_node_types = {}
})
describe('updateNodeDefDisplayName', () => {
const createTestNodeDef = (
name: string,
displayName: string
): ComfyNodeDefV1 => ({
name,
display_name: displayName,
category: 'test',
python_module: 'test_module',
description: 'Test node',
input: { required: {}, optional: {} },
output: [],
output_node: false
})
it('should update display name in nodeDefsByName mapping', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
store.addNodeDef(nodeDef)
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
const updatedNodeDef = store.nodeDefsByName['TestNode']
expect(updatedNodeDef.display_name).toBe('New Display Name')
})
it('should update nodeDefsByDisplayName mapping', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
store.addNodeDef(nodeDef)
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
// Old display name should be removed
expect(
store.nodeDefsByDisplayName['Original Display Name']
).toBeUndefined()
// New display name should be added
expect(store.nodeDefsByDisplayName['New Display Name']).toBeDefined()
expect(store.nodeDefsByDisplayName['New Display Name'].name).toBe(
'TestNode'
)
})
it('should update the object while preserving clone pattern', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
store.addNodeDef(nodeDef)
const originalRef = store.nodeDefsByName['TestNode']
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
const updatedRef = store.nodeDefsByName['TestNode']
// Clone creates a new reference but preserves properties
expect(updatedRef).not.toBe(originalRef)
expect(updatedRef.display_name).toBe('New Display Name')
expect(updatedRef.name).toBe('TestNode')
expect(updatedRef.category).toBe('test')
})
it('should update LiteGraph registered node type title', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
store.addNodeDef(nodeDef)
// Simulate a registered LiteGraph node type
const mockNodeClass = { title: 'Original Display Name' }
LiteGraph.registered_node_types['TestNode'] = mockNodeClass as any
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
expect(mockNodeClass.title).toBe('New Display Name')
})
it('should handle non-existent node type gracefully', () => {
// Should not throw when updating non-existent node
expect(() => {
store.updateNodeDefDisplayName('NonExistentNode', 'New Display Name')
}).not.toThrow()
})
it('should handle missing LiteGraph registered type gracefully', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
store.addNodeDef(nodeDef)
// No registered LiteGraph type
expect(LiteGraph.registered_node_types['TestNode']).toBeUndefined()
// Should not throw
expect(() => {
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
}).not.toThrow()
// Store should still be updated
expect(store.nodeDefsByName['TestNode'].display_name).toBe(
'New Display Name'
)
})
it('should work with ComfyNodeDefImpl instances', () => {
const nodeDef = createTestNodeDef('TestNode', 'Original Display Name')
const nodeDefImpl = new ComfyNodeDefImpl(nodeDef)
// Manually add to store mappings
store.nodeDefsByName['TestNode'] = nodeDefImpl
store.nodeDefsByDisplayName['Original Display Name'] = nodeDefImpl
store.updateNodeDefDisplayName('TestNode', 'New Display Name')
expect(store.nodeDefsByName['TestNode'].display_name).toBe(
'New Display Name'
)
expect(store.nodeDefsByDisplayName['New Display Name']).toBeDefined()
})
})
})

View File

@@ -41,7 +41,6 @@ describe('useSystemStatsStore', () => {
embedded_python: false,
comfyui_version: '1.0.0',
pytorch_version: '2.0.0',
required_frontend_version: '1.24.0',
argv: [],
ram_total: 16000000000,
ram_free: 8000000000
@@ -93,32 +92,6 @@ describe('useSystemStatsStore', () => {
expect(store.isLoading).toBe(false)
})
it('should handle system stats updates', async () => {
const updatedStats = {
system: {
os: 'Windows',
python_version: '3.11.0',
embedded_python: false,
comfyui_version: '1.1.0',
pytorch_version: '2.1.0',
required_frontend_version: '1.25.0',
argv: [],
ram_total: 16000000000,
ram_free: 7000000000
},
devices: []
}
vi.mocked(api.getSystemStats).mockResolvedValue(updatedStats)
await store.fetchSystemStats()
expect(store.systemStats).toEqual(updatedStats)
expect(store.isLoading).toBe(false)
expect(store.error).toBeNull()
expect(api.getSystemStats).toHaveBeenCalled()
})
})
describe('getFormFactor', () => {

View File

@@ -1,321 +0,0 @@
import { createPinia, setActivePinia } from 'pinia'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ref } from 'vue'
import { useSystemStatsStore } from '@/stores/systemStatsStore'
import { useVersionCompatibilityStore } from '@/stores/versionCompatibilityStore'
vi.mock('@/config', () => ({
default: {
app_version: '1.24.0'
}
}))
vi.mock('@/stores/systemStatsStore')
// Mock useStorage from VueUse
const mockDismissalStorage = ref({} as Record<string, number>)
vi.mock('@vueuse/core', () => ({
useStorage: vi.fn(() => mockDismissalStorage)
}))
describe('useVersionCompatibilityStore', () => {
let store: ReturnType<typeof useVersionCompatibilityStore>
let mockSystemStatsStore: any
beforeEach(() => {
setActivePinia(createPinia())
// Clear the mock dismissal storage
mockDismissalStorage.value = {}
mockSystemStatsStore = {
systemStats: null,
fetchSystemStats: vi.fn()
}
vi.mocked(useSystemStatsStore).mockReturnValue(mockSystemStatsStore)
store = useVersionCompatibilityStore()
})
afterEach(() => {
vi.clearAllMocks()
})
describe('version compatibility detection', () => {
it('should detect frontend is outdated when required version is higher', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(true)
expect(store.isFrontendNewer).toBe(false)
expect(store.hasVersionMismatch).toBe(true)
})
it('should not warn when frontend is newer than backend', async () => {
// Frontend: 1.24.0, Backend: 1.23.0, Required: 1.23.0
// Frontend meets required version, no warning needed
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.23.0',
required_frontend_version: '1.23.0'
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(false)
expect(store.isFrontendNewer).toBe(false)
expect(store.hasVersionMismatch).toBe(false)
})
it('should not detect mismatch when versions are compatible', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.24.0',
required_frontend_version: '1.24.0'
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(false)
expect(store.isFrontendNewer).toBe(false)
expect(store.hasVersionMismatch).toBe(false)
})
it('should handle missing version information gracefully', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '',
required_frontend_version: ''
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(false)
expect(store.isFrontendNewer).toBe(false)
expect(store.hasVersionMismatch).toBe(false)
})
it('should not detect mismatch when versions are not valid semver', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '080e6d4af809a46852d1c4b7ed85f06e8a3a72be', // git hash
required_frontend_version: 'not-a-version' // invalid semver format
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(false)
expect(store.isFrontendNewer).toBe(false)
expect(store.hasVersionMismatch).toBe(false)
})
it('should not warn when frontend exceeds required version', async () => {
// Frontend: 1.24.0 (from mock config)
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.22.0', // Backend is older
required_frontend_version: '1.23.0' // Required is 1.23.0, frontend 1.24.0 meets this
}
}
await store.checkVersionCompatibility()
expect(store.isFrontendOutdated).toBe(false) // Frontend 1.24.0 >= Required 1.23.0
expect(store.isFrontendNewer).toBe(false) // Never warns about being newer
expect(store.hasVersionMismatch).toBe(false)
})
})
describe('warning display logic', () => {
it('should show warning when there is a version mismatch and not dismissed', async () => {
// No dismissals in storage
mockDismissalStorage.value = {}
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.checkVersionCompatibility()
expect(store.shouldShowWarning).toBe(true)
})
it('should not show warning when dismissed', async () => {
const futureTime = Date.now() + 1000000
// Set dismissal in reactive storage
mockDismissalStorage.value = {
'1.24.0-1.25.0-1.25.0': futureTime
}
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.checkVersionCompatibility()
expect(store.shouldShowWarning).toBe(false)
})
it('should not show warning when no version mismatch', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.24.0',
required_frontend_version: '1.24.0'
}
}
await store.checkVersionCompatibility()
expect(store.shouldShowWarning).toBe(false)
})
})
describe('warning messages', () => {
it('should generate outdated message when frontend is outdated', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.checkVersionCompatibility()
expect(store.warningMessage).toEqual({
type: 'outdated',
frontendVersion: '1.24.0',
requiredVersion: '1.25.0'
})
})
it('should return null when no mismatch', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.24.0',
required_frontend_version: '1.24.0'
}
}
await store.checkVersionCompatibility()
expect(store.warningMessage).toBeNull()
})
})
describe('dismissal persistence', () => {
it('should save dismissal to reactive storage with expiration', async () => {
const mockNow = 1000000
vi.spyOn(Date, 'now').mockReturnValue(mockNow)
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.checkVersionCompatibility()
store.dismissWarning()
// Check that the dismissal was added to reactive storage
expect(mockDismissalStorage.value).toEqual({
'1.24.0-1.25.0-1.25.0': mockNow + 7 * 24 * 60 * 60 * 1000
})
})
it('should check dismissal state from reactive storage', async () => {
const futureTime = Date.now() + 1000000 // Still valid
mockDismissalStorage.value = {
'1.24.0-1.25.0-1.25.0': futureTime
}
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.initialize()
expect(store.shouldShowWarning).toBe(false)
})
it('should show warning if dismissal has expired', async () => {
const pastTime = Date.now() - 1000 // Expired
mockDismissalStorage.value = {
'1.24.0-1.25.0-1.25.0': pastTime
}
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.25.0',
required_frontend_version: '1.25.0'
}
}
await store.initialize()
expect(store.shouldShowWarning).toBe(true)
})
it('should show warning for different version combinations even if previous was dismissed', async () => {
const futureTime = Date.now() + 1000000
// Dismissed for different version combination (1.25.0) but current is 1.26.0
mockDismissalStorage.value = {
'1.24.0-1.25.0-1.25.0': futureTime // Different version was dismissed
}
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.26.0',
required_frontend_version: '1.26.0'
}
}
await store.initialize()
expect(store.shouldShowWarning).toBe(true)
})
})
describe('initialization', () => {
it('should fetch system stats if not available', async () => {
mockSystemStatsStore.systemStats = null
await store.initialize()
expect(mockSystemStatsStore.fetchSystemStats).toHaveBeenCalled()
})
it('should not fetch system stats if already available', async () => {
mockSystemStatsStore.systemStats = {
system: {
comfyui_version: '1.24.0',
required_frontend_version: '1.24.0'
}
}
await store.initialize()
expect(mockSystemStatsStore.fetchSystemStats).not.toHaveBeenCalled()
})
})
})