mirror of
https://github.com/Comfy-Org/ComfyUI_frontend.git
synced 2026-04-06 12:29:55 +00:00
Compare commits
23 Commits
v1.41.6
...
feat/repla
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4dc67b375b | ||
|
|
1d8a01cdf8 | ||
|
|
b585dfa4fc | ||
|
|
1be6d27024 | ||
|
|
5aa4baf116 | ||
|
|
7d69a0db5b | ||
|
|
83bb4300e3 | ||
|
|
0d58a92e34 | ||
|
|
45ca1beea2 | ||
|
|
aef299caf8 | ||
|
|
188fafa89a | ||
|
|
3984408d05 | ||
|
|
6034be9a6f | ||
|
|
6a08e4ddde | ||
|
|
9ff985a792 | ||
|
|
5cfd1aa77e | ||
|
|
2cb4c5eff3 | ||
|
|
b8cca4167b | ||
|
|
d99d807c45 | ||
|
|
80fe51bb8c | ||
|
|
c24c4ab607 | ||
|
|
8e215b3174 | ||
|
|
c957841862 |
110
.github/workflows/ci-perf-report.yaml
vendored
Normal file
110
.github/workflows/ci-perf-report.yaml
vendored
Normal file
@@ -0,0 +1,110 @@
|
||||
name: 'CI: Performance Report'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, core/*]
|
||||
paths-ignore: ['**/*.md']
|
||||
pull_request:
|
||||
branches-ignore: [wip/*, draft/*, temp/*]
|
||||
paths-ignore: ['**/*.md']
|
||||
|
||||
concurrency:
|
||||
group: perf-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
perf-tests:
|
||||
if: github.repository == 'Comfy-Org/ComfyUI_frontend'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
container:
|
||||
image: ghcr.io/comfy-org/comfyui-ci-container:0.0.12
|
||||
credentials:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup frontend
|
||||
uses: ./.github/actions/setup-frontend
|
||||
with:
|
||||
include_build_step: true
|
||||
|
||||
- name: Start ComfyUI server
|
||||
uses: ./.github/actions/start-comfyui-server
|
||||
|
||||
- name: Run performance tests
|
||||
id: perf
|
||||
continue-on-error: true
|
||||
run: pnpm exec playwright test --project=performance --workers=1
|
||||
|
||||
- name: Upload perf metrics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: perf-metrics
|
||||
path: test-results/perf-metrics.json
|
||||
retention-days: 30
|
||||
if-no-files-found: warn
|
||||
|
||||
report:
|
||||
needs: perf-tests
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- name: Download PR perf metrics
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: perf-metrics
|
||||
path: test-results/
|
||||
|
||||
- name: Download baseline perf metrics
|
||||
uses: dawidd6/action-download-artifact@0bd50d53a6d7fb5cb921e607957e9cc12b4ce392 # v12
|
||||
with:
|
||||
branch: ${{ github.event.pull_request.base.ref }}
|
||||
workflow: ci-perf-report.yaml
|
||||
event: push
|
||||
name: perf-metrics
|
||||
path: temp/perf-baseline/
|
||||
if_no_artifact_found: warn
|
||||
|
||||
- name: Generate perf report
|
||||
run: npx --yes tsx scripts/perf-report.ts > perf-report.md
|
||||
|
||||
- name: Read perf report
|
||||
id: perf-report
|
||||
uses: juliangruber/read-file-action@b549046febe0fe86f8cb4f93c24e284433f9ab58 # v1.1.7
|
||||
with:
|
||||
path: ./perf-report.md
|
||||
|
||||
- name: Create or update PR comment
|
||||
uses: actions-cool/maintain-one-comment@4b2dbf086015f892dcb5e8c1106f5fccd6c1476b # v3.2.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
number: ${{ github.event.pull_request.number }}
|
||||
body: |
|
||||
${{ steps.perf-report.outputs.content }}
|
||||
<!-- COMFYUI_FRONTEND_PERF -->
|
||||
body-include: '<!-- COMFYUI_FRONTEND_PERF -->'
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from './components/SidebarTab'
|
||||
import { Topbar } from './components/Topbar'
|
||||
import { CanvasHelper } from './helpers/CanvasHelper'
|
||||
import { PerformanceHelper } from './helpers/PerformanceHelper'
|
||||
import { ClipboardHelper } from './helpers/ClipboardHelper'
|
||||
import { CommandHelper } from './helpers/CommandHelper'
|
||||
import { DragDropHelper } from './helpers/DragDropHelper'
|
||||
@@ -185,6 +186,7 @@ export class ComfyPage {
|
||||
public readonly dragDrop: DragDropHelper
|
||||
public readonly command: CommandHelper
|
||||
public readonly bottomPanel: BottomPanel
|
||||
public readonly perf: PerformanceHelper
|
||||
|
||||
/** Worker index to test user ID */
|
||||
public readonly userIds: string[] = []
|
||||
@@ -229,6 +231,7 @@ export class ComfyPage {
|
||||
this.dragDrop = new DragDropHelper(page, this.assetPath.bind(this))
|
||||
this.command = new CommandHelper(page)
|
||||
this.bottomPanel = new BottomPanel(page)
|
||||
this.perf = new PerformanceHelper(page)
|
||||
}
|
||||
|
||||
get visibleToasts() {
|
||||
@@ -436,7 +439,13 @@ export const comfyPageFixture = base.extend<{
|
||||
}
|
||||
|
||||
await comfyPage.setup()
|
||||
|
||||
const isPerf = testInfo.tags.includes('@perf')
|
||||
if (isPerf) await comfyPage.perf.init()
|
||||
|
||||
await use(comfyPage)
|
||||
|
||||
if (isPerf) await comfyPage.perf.dispose()
|
||||
},
|
||||
comfyMouse: async ({ comfyPage }, use) => {
|
||||
const comfyMouse = new ComfyMouse(comfyPage)
|
||||
|
||||
96
browser_tests/fixtures/helpers/PerformanceHelper.ts
Normal file
96
browser_tests/fixtures/helpers/PerformanceHelper.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import type { CDPSession, Page } from '@playwright/test'
|
||||
|
||||
interface PerfSnapshot {
|
||||
RecalcStyleCount: number
|
||||
RecalcStyleDuration: number
|
||||
LayoutCount: number
|
||||
LayoutDuration: number
|
||||
TaskDuration: number
|
||||
JSHeapUsedSize: number
|
||||
Timestamp: number
|
||||
}
|
||||
|
||||
export interface PerfMeasurement {
|
||||
name: string
|
||||
durationMs: number
|
||||
styleRecalcs: number
|
||||
styleRecalcDurationMs: number
|
||||
layouts: number
|
||||
layoutDurationMs: number
|
||||
taskDurationMs: number
|
||||
heapDeltaBytes: number
|
||||
}
|
||||
|
||||
export class PerformanceHelper {
|
||||
private cdp: CDPSession | null = null
|
||||
private snapshot: PerfSnapshot | null = null
|
||||
|
||||
constructor(private readonly page: Page) {}
|
||||
|
||||
async init(): Promise<void> {
|
||||
this.cdp = await this.page.context().newCDPSession(this.page)
|
||||
await this.cdp.send('Performance.enable')
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.snapshot = null
|
||||
if (this.cdp) {
|
||||
try {
|
||||
await this.cdp.send('Performance.disable')
|
||||
} finally {
|
||||
await this.cdp.detach()
|
||||
this.cdp = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getSnapshot(): Promise<PerfSnapshot> {
|
||||
if (!this.cdp) throw new Error('PerformanceHelper not initialized')
|
||||
const { metrics } = (await this.cdp.send('Performance.getMetrics')) as {
|
||||
metrics: { name: string; value: number }[]
|
||||
}
|
||||
function get(name: string): number {
|
||||
return metrics.find((m) => m.name === name)?.value ?? 0
|
||||
}
|
||||
return {
|
||||
RecalcStyleCount: get('RecalcStyleCount'),
|
||||
RecalcStyleDuration: get('RecalcStyleDuration'),
|
||||
LayoutCount: get('LayoutCount'),
|
||||
LayoutDuration: get('LayoutDuration'),
|
||||
TaskDuration: get('TaskDuration'),
|
||||
JSHeapUsedSize: get('JSHeapUsedSize'),
|
||||
Timestamp: get('Timestamp')
|
||||
}
|
||||
}
|
||||
|
||||
async startMeasuring(): Promise<void> {
|
||||
if (this.snapshot) {
|
||||
throw new Error(
|
||||
'Measurement already in progress — call stopMeasuring() first'
|
||||
)
|
||||
}
|
||||
this.snapshot = await this.getSnapshot()
|
||||
}
|
||||
|
||||
async stopMeasuring(name: string): Promise<PerfMeasurement> {
|
||||
if (!this.snapshot) throw new Error('Call startMeasuring() first')
|
||||
const after = await this.getSnapshot()
|
||||
const before = this.snapshot
|
||||
this.snapshot = null
|
||||
|
||||
function delta(key: keyof PerfSnapshot): number {
|
||||
return after[key] - before[key]
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
durationMs: delta('Timestamp') * 1000,
|
||||
styleRecalcs: delta('RecalcStyleCount'),
|
||||
styleRecalcDurationMs: delta('RecalcStyleDuration') * 1000,
|
||||
layouts: delta('LayoutCount'),
|
||||
layoutDurationMs: delta('LayoutDuration') * 1000,
|
||||
taskDurationMs: delta('TaskDuration') * 1000,
|
||||
heapDeltaBytes: delta('JSHeapUsedSize')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import type { FullConfig } from '@playwright/test'
|
||||
import dotenv from 'dotenv'
|
||||
|
||||
import { writePerfReport } from './helpers/perfReporter'
|
||||
import { restorePath } from './utils/backupUtils'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
export default function globalTeardown(_config: FullConfig) {
|
||||
writePerfReport()
|
||||
|
||||
if (!process.env.CI && process.env.TEST_COMFYUI_DIR) {
|
||||
restorePath([process.env.TEST_COMFYUI_DIR, 'user'])
|
||||
restorePath([process.env.TEST_COMFYUI_DIR, 'models'])
|
||||
|
||||
49
browser_tests/helpers/perfReporter.ts
Normal file
49
browser_tests/helpers/perfReporter.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
|
||||
import type { PerfMeasurement } from '../fixtures/helpers/PerformanceHelper'
|
||||
|
||||
export interface PerfReport {
|
||||
timestamp: string
|
||||
gitSha: string
|
||||
branch: string
|
||||
measurements: PerfMeasurement[]
|
||||
}
|
||||
|
||||
const TEMP_DIR = join('test-results', 'perf-temp')
|
||||
|
||||
export function recordMeasurement(m: PerfMeasurement) {
|
||||
mkdirSync(TEMP_DIR, { recursive: true })
|
||||
const filename = `${m.name}-${Date.now()}.json`
|
||||
writeFileSync(join(TEMP_DIR, filename), JSON.stringify(m))
|
||||
}
|
||||
|
||||
export function writePerfReport(
|
||||
gitSha = process.env.GITHUB_SHA ?? 'local',
|
||||
branch = process.env.GITHUB_HEAD_REF ?? 'local'
|
||||
) {
|
||||
if (!readdirSync('test-results', { withFileTypes: true }).length) return
|
||||
|
||||
let tempFiles: string[]
|
||||
try {
|
||||
tempFiles = readdirSync(TEMP_DIR).filter((f) => f.endsWith('.json'))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (tempFiles.length === 0) return
|
||||
|
||||
const measurements: PerfMeasurement[] = tempFiles.map((f) =>
|
||||
JSON.parse(readFileSync(join(TEMP_DIR, f), 'utf-8'))
|
||||
)
|
||||
|
||||
const report: PerfReport = {
|
||||
timestamp: new Date().toISOString(),
|
||||
gitSha,
|
||||
branch,
|
||||
measurements
|
||||
}
|
||||
writeFileSync(
|
||||
join('test-results', 'perf-metrics.json'),
|
||||
JSON.stringify(report, null, 2)
|
||||
)
|
||||
}
|
||||
70
browser_tests/tests/performance.spec.ts
Normal file
70
browser_tests/tests/performance.spec.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { comfyPageFixture as test } from '../fixtures/ComfyPage'
|
||||
import { recordMeasurement } from '../helpers/perfReporter'
|
||||
|
||||
test.describe('Performance', { tag: ['@perf'] }, () => {
|
||||
test('canvas idle style recalculations', async ({ comfyPage }) => {
|
||||
await comfyPage.workflow.loadWorkflow('default')
|
||||
await comfyPage.perf.startMeasuring()
|
||||
|
||||
// Let the canvas idle for 2 seconds — no user interaction.
|
||||
// Measures baseline style recalcs from reactive state + render loop.
|
||||
for (let i = 0; i < 120; i++) {
|
||||
await comfyPage.nextFrame()
|
||||
}
|
||||
|
||||
const m = await comfyPage.perf.stopMeasuring('canvas-idle')
|
||||
recordMeasurement(m)
|
||||
console.log(
|
||||
`Canvas idle: ${m.styleRecalcs} style recalcs, ${m.layouts} layouts`
|
||||
)
|
||||
})
|
||||
|
||||
test('canvas mouse interaction style recalculations', async ({
|
||||
comfyPage
|
||||
}) => {
|
||||
await comfyPage.workflow.loadWorkflow('default')
|
||||
await comfyPage.perf.startMeasuring()
|
||||
|
||||
const canvas = comfyPage.canvas
|
||||
const box = await canvas.boundingBox()
|
||||
if (!box) throw new Error('Canvas bounding box not available')
|
||||
|
||||
// Sweep mouse across the canvas — crosses nodes, empty space, slots
|
||||
for (let i = 0; i < 100; i++) {
|
||||
await comfyPage.page.mouse.move(
|
||||
box.x + (box.width * i) / 100,
|
||||
box.y + (box.height * (i % 3)) / 3
|
||||
)
|
||||
}
|
||||
|
||||
const m = await comfyPage.perf.stopMeasuring('canvas-mouse-sweep')
|
||||
recordMeasurement(m)
|
||||
console.log(
|
||||
`Mouse sweep: ${m.styleRecalcs} style recalcs, ${m.layouts} layouts`
|
||||
)
|
||||
})
|
||||
|
||||
test('DOM widget clipping during node selection', async ({ comfyPage }) => {
|
||||
// Load default workflow which has DOM widgets (text inputs, combos)
|
||||
await comfyPage.workflow.loadWorkflow('default')
|
||||
await comfyPage.perf.startMeasuring()
|
||||
|
||||
// Select and deselect nodes rapidly to trigger clipping recalculation
|
||||
const canvas = comfyPage.canvas
|
||||
const box = await canvas.boundingBox()
|
||||
if (!box) throw new Error('Canvas bounding box not available')
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
// Click on canvas area (nodes occupy various positions)
|
||||
await comfyPage.page.mouse.click(
|
||||
box.x + box.width / 3 + (i % 5) * 30,
|
||||
box.y + box.height / 3 + (i % 4) * 30
|
||||
)
|
||||
await comfyPage.nextFrame()
|
||||
}
|
||||
|
||||
const m = await comfyPage.perf.stopMeasuring('dom-widget-clipping')
|
||||
recordMeasurement(m)
|
||||
console.log(`Clipping: ${m.layouts} forced layouts`)
|
||||
})
|
||||
})
|
||||
@@ -22,7 +22,9 @@ const extraFileExtensions = ['.vue']
|
||||
|
||||
const commonGlobals = {
|
||||
...globals.browser,
|
||||
__COMFYUI_FRONTEND_VERSION__: 'readonly'
|
||||
__COMFYUI_FRONTEND_VERSION__: 'readonly',
|
||||
__DISTRIBUTION__: 'readonly',
|
||||
__IS_NIGHTLY__: 'readonly'
|
||||
} as const
|
||||
|
||||
const settings = {
|
||||
|
||||
@@ -36,7 +36,18 @@ export default defineConfig({
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
timeout: 15000,
|
||||
grepInvert: /@mobile/ // Run all tests except those tagged with @mobile
|
||||
grepInvert: /@mobile|@perf/ // Run all tests except those tagged with @mobile or @perf
|
||||
},
|
||||
|
||||
{
|
||||
name: 'performance',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
trace: 'retain-on-failure'
|
||||
},
|
||||
timeout: 60_000,
|
||||
grep: /@perf/,
|
||||
fullyParallel: false
|
||||
},
|
||||
|
||||
{
|
||||
|
||||
125
scripts/perf-report.ts
Normal file
125
scripts/perf-report.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
|
||||
interface PerfMeasurement {
|
||||
name: string
|
||||
durationMs: number
|
||||
styleRecalcs: number
|
||||
styleRecalcDurationMs: number
|
||||
layouts: number
|
||||
layoutDurationMs: number
|
||||
taskDurationMs: number
|
||||
heapDeltaBytes: number
|
||||
}
|
||||
|
||||
interface PerfReport {
|
||||
timestamp: string
|
||||
gitSha: string
|
||||
branch: string
|
||||
measurements: PerfMeasurement[]
|
||||
}
|
||||
|
||||
const CURRENT_PATH = 'test-results/perf-metrics.json'
|
||||
const BASELINE_PATH = 'temp/perf-baseline/perf-metrics.json'
|
||||
|
||||
function formatDelta(pct: number): string {
|
||||
if (pct >= 20) return `+${pct.toFixed(0)}% 🔴`
|
||||
if (pct >= 10) return `+${pct.toFixed(0)}% 🟠`
|
||||
if (pct > -10) return `${pct >= 0 ? '+' : ''}${pct.toFixed(0)}% ⚪`
|
||||
return `${pct.toFixed(0)}% 🟢`
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (Math.abs(bytes) < 1024) return `${bytes} B`
|
||||
if (Math.abs(bytes) < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function calcDelta(
|
||||
baseline: number,
|
||||
current: number
|
||||
): { pct: number; isNew: boolean } {
|
||||
if (baseline > 0) {
|
||||
return { pct: ((current - baseline) / baseline) * 100, isNew: false }
|
||||
}
|
||||
return current > 0 ? { pct: Infinity, isNew: true } : { pct: 0, isNew: false }
|
||||
}
|
||||
|
||||
function formatDeltaCell(delta: { pct: number; isNew: boolean }): string {
|
||||
return delta.isNew ? 'new 🔴' : formatDelta(delta.pct)
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (!existsSync(CURRENT_PATH)) {
|
||||
process.stdout.write(
|
||||
'## ⚡ Performance Report\n\nNo perf metrics found. Perf tests may not have run.\n'
|
||||
)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const current: PerfReport = JSON.parse(readFileSync(CURRENT_PATH, 'utf-8'))
|
||||
|
||||
const baseline: PerfReport | null = existsSync(BASELINE_PATH)
|
||||
? JSON.parse(readFileSync(BASELINE_PATH, 'utf-8'))
|
||||
: null
|
||||
|
||||
const lines: string[] = []
|
||||
lines.push('## ⚡ Performance Report\n')
|
||||
|
||||
if (baseline) {
|
||||
lines.push(
|
||||
'| Metric | Baseline | PR | Δ |',
|
||||
'|--------|----------|-----|---|'
|
||||
)
|
||||
|
||||
for (const m of current.measurements) {
|
||||
const base = baseline.measurements.find((b) => b.name === m.name)
|
||||
if (!base) {
|
||||
lines.push(`| ${m.name}: style recalcs | — | ${m.styleRecalcs} | new |`)
|
||||
lines.push(`| ${m.name}: layouts | — | ${m.layouts} | new |`)
|
||||
lines.push(
|
||||
`| ${m.name}: task duration | — | ${m.taskDurationMs.toFixed(0)}ms | new |`
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const recalcDelta = calcDelta(base.styleRecalcs, m.styleRecalcs)
|
||||
lines.push(
|
||||
`| ${m.name}: style recalcs | ${base.styleRecalcs} | ${m.styleRecalcs} | ${formatDeltaCell(recalcDelta)} |`
|
||||
)
|
||||
|
||||
const layoutDelta = calcDelta(base.layouts, m.layouts)
|
||||
lines.push(
|
||||
`| ${m.name}: layouts | ${base.layouts} | ${m.layouts} | ${formatDeltaCell(layoutDelta)} |`
|
||||
)
|
||||
|
||||
const taskDelta = calcDelta(base.taskDurationMs, m.taskDurationMs)
|
||||
lines.push(
|
||||
`| ${m.name}: task duration | ${base.taskDurationMs.toFixed(0)}ms | ${m.taskDurationMs.toFixed(0)}ms | ${formatDeltaCell(taskDelta)} |`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
lines.push(
|
||||
'No baseline found — showing absolute values.\n',
|
||||
'| Metric | Value |',
|
||||
'|--------|-------|'
|
||||
)
|
||||
for (const m of current.measurements) {
|
||||
lines.push(`| ${m.name}: style recalcs | ${m.styleRecalcs} |`)
|
||||
lines.push(`| ${m.name}: layouts | ${m.layouts} |`)
|
||||
lines.push(
|
||||
`| ${m.name}: task duration | ${m.taskDurationMs.toFixed(0)}ms |`
|
||||
)
|
||||
lines.push(`| ${m.name}: heap delta | ${formatBytes(m.heapDeltaBytes)} |`)
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('\n<details><summary>Raw data</summary>\n')
|
||||
lines.push('```json')
|
||||
lines.push(JSON.stringify(current, null, 2))
|
||||
lines.push('```')
|
||||
lines.push('\n</details>')
|
||||
|
||||
process.stdout.write(lines.join('\n') + '\n')
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -51,7 +51,6 @@ onMounted(() => {
|
||||
// See: https://vite.dev/guide/build#load-error-handling
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
event.preventDefault()
|
||||
// eslint-disable-next-line no-undef
|
||||
if (__DISTRIBUTION__ === 'cloud') {
|
||||
captureException(event.payload, {
|
||||
tags: { error_type: 'vite_preload_error' }
|
||||
|
||||
@@ -262,7 +262,7 @@ describe('TopMenuSection', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('opens the assets sidebar tab when QPO V2 is enabled', async () => {
|
||||
it('opens the job history sidebar tab when QPO V2 is enabled', async () => {
|
||||
const pinia = createTestingPinia({ createSpy: vi.fn, stubActions: false })
|
||||
const settingStore = useSettingStore(pinia)
|
||||
vi.mocked(settingStore.get).mockImplementation((key) =>
|
||||
@@ -273,10 +273,10 @@ describe('TopMenuSection', () => {
|
||||
|
||||
await wrapper.find('[data-testid="queue-overlay-toggle"]').trigger('click')
|
||||
|
||||
expect(sidebarTabStore.activeSidebarTabId).toBe('assets')
|
||||
expect(sidebarTabStore.activeSidebarTabId).toBe('job-history')
|
||||
})
|
||||
|
||||
it('toggles the assets sidebar tab when QPO V2 is enabled', async () => {
|
||||
it('toggles the job history sidebar tab when QPO V2 is enabled', async () => {
|
||||
const pinia = createTestingPinia({ createSpy: vi.fn, stubActions: false })
|
||||
const settingStore = useSettingStore(pinia)
|
||||
vi.mocked(settingStore.get).mockImplementation((key) =>
|
||||
@@ -287,7 +287,7 @@ describe('TopMenuSection', () => {
|
||||
const toggleButton = wrapper.find('[data-testid="queue-overlay-toggle"]')
|
||||
|
||||
await toggleButton.trigger('click')
|
||||
expect(sidebarTabStore.activeSidebarTabId).toBe('assets')
|
||||
expect(sidebarTabStore.activeSidebarTabId).toBe('job-history')
|
||||
|
||||
await toggleButton.trigger('click')
|
||||
expect(sidebarTabStore.activeSidebarTabId).toBe(null)
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
size="md"
|
||||
:aria-pressed="
|
||||
isQueuePanelV2Enabled
|
||||
? activeSidebarTabId === 'assets'
|
||||
? activeSidebarTabId === 'job-history'
|
||||
: isQueueProgressOverlayEnabled
|
||||
? isQueueOverlayExpanded
|
||||
: undefined
|
||||
@@ -127,13 +127,15 @@
|
||||
<div
|
||||
class="pointer-events-none absolute left-0 right-0 top-full mt-1 flex justify-end pr-1"
|
||||
>
|
||||
<QueueInlineProgressSummary :hidden="isQueueOverlayExpanded" />
|
||||
<QueueInlineProgressSummary
|
||||
:hidden="shouldHideInlineProgressSummary"
|
||||
/>
|
||||
</div>
|
||||
</Teleport>
|
||||
<QueueInlineProgressSummary
|
||||
v-else-if="shouldShowInlineProgressSummary && !isActionbarFloating"
|
||||
class="pr-1"
|
||||
:hidden="isQueueOverlayExpanded"
|
||||
:hidden="shouldHideInlineProgressSummary"
|
||||
/>
|
||||
<QueueNotificationBannerHost
|
||||
v-if="shouldShowQueueNotificationBanners"
|
||||
@@ -241,6 +243,9 @@ const inlineProgressSummaryTarget = computed(() => {
|
||||
}
|
||||
return progressTarget.value
|
||||
})
|
||||
const shouldHideInlineProgressSummary = computed(
|
||||
() => isQueueProgressOverlayEnabled.value && isQueueOverlayExpanded.value
|
||||
)
|
||||
const queueHistoryTooltipConfig = computed(() =>
|
||||
buildTooltipConfig(t('sideToolbar.queueProgressOverlay.viewJobHistory'))
|
||||
)
|
||||
@@ -283,7 +288,7 @@ onMounted(() => {
|
||||
|
||||
const toggleQueueOverlay = () => {
|
||||
if (isQueuePanelV2Enabled.value) {
|
||||
sidebarTabStore.toggleSidebarTab('assets')
|
||||
sidebarTabStore.toggleSidebarTab('job-history')
|
||||
return
|
||||
}
|
||||
commandStore.execute('Comfy.Queue.ToggleOverlay')
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
<Teleport v-if="inlineProgressTarget" :to="inlineProgressTarget">
|
||||
<QueueInlineProgress
|
||||
:hidden="queueOverlayExpanded"
|
||||
:hidden="shouldHideInlineProgress"
|
||||
:radius-class="cn(isDocked ? 'rounded-[7px]' : 'rounded-[5px]')"
|
||||
data-testid="queue-inline-progress"
|
||||
/>
|
||||
@@ -287,6 +287,9 @@ const inlineProgressTarget = computed(() => {
|
||||
if (isDocked.value) return topMenuContainer ?? null
|
||||
return panelElement.value
|
||||
})
|
||||
const shouldHideInlineProgress = computed(
|
||||
() => !isQueuePanelV2Enabled.value && queueOverlayExpanded
|
||||
)
|
||||
watch(
|
||||
panelElement,
|
||||
(target) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { CurvePoint } from './types'
|
||||
|
||||
import CurveEditor from './CurveEditor.vue'
|
||||
|
||||
|
||||
@@ -77,7 +77,8 @@
|
||||
import { computed, useTemplateRef } from 'vue'
|
||||
|
||||
import { useCurveEditor } from '@/composables/useCurveEditor'
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
|
||||
import type { CurvePoint } from './types'
|
||||
|
||||
import { histogramToPath } from './curveUtils'
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { CurvePoint } from './types'
|
||||
|
||||
import CurveEditor from './CurveEditor.vue'
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { CurvePoint } from './types'
|
||||
|
||||
import {
|
||||
createMonotoneInterpolator,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { CurvePoint } from './types'
|
||||
|
||||
/**
|
||||
* Monotone cubic Hermite interpolation.
|
||||
@@ -95,15 +95,15 @@ export function histogramToPath(histogram: Uint32Array): string {
|
||||
const max = sorted[Math.floor(255 * 0.995)]
|
||||
if (max === 0) return ''
|
||||
|
||||
const step = 1 / 255
|
||||
let d = 'M0,1'
|
||||
const invMax = 1 / max
|
||||
const parts: string[] = ['M0,1']
|
||||
for (let i = 0; i < 256; i++) {
|
||||
const x = i * step
|
||||
const y = 1 - Math.min(1, histogram[i] / max)
|
||||
d += ` L${x.toFixed(4)},${y.toFixed(4)}`
|
||||
const x = i / 255
|
||||
const y = 1 - Math.min(1, histogram[i] * invMax)
|
||||
parts.push(`L${x},${y}`)
|
||||
}
|
||||
d += ' L1,1 Z'
|
||||
return d
|
||||
parts.push('L1,1 Z')
|
||||
return parts.join(' ')
|
||||
}
|
||||
|
||||
export function curvesToLUT(points: CurvePoint[]): Uint8Array {
|
||||
|
||||
1
src/components/curve/types.ts
Normal file
1
src/components/curve/types.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type CurvePoint = [x: number, y: number]
|
||||
@@ -438,7 +438,6 @@ onMounted(() => {
|
||||
const systemStatsStore = useSystemStatsStore()
|
||||
|
||||
const distributions = computed(() => {
|
||||
// eslint-disable-next-line no-undef
|
||||
switch (__DISTRIBUTION__) {
|
||||
case 'cloud':
|
||||
return [TemplateIncludeOnDistributionEnum.Cloud]
|
||||
|
||||
@@ -234,6 +234,7 @@ import { isCloud } from '@/platform/distribution/types'
|
||||
import type { NodeReplacement } from '@/platform/nodeReplacement/types'
|
||||
import { useNodeReplacement } from '@/platform/nodeReplacement/useNodeReplacement'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
import { useMissingNodes } from '@/workbench/extensions/manager/composables/nodePack/useMissingNodes'
|
||||
@@ -245,6 +246,7 @@ const { missingNodeTypes } = defineProps<{
|
||||
const { missingCoreNodes } = useMissingNodes()
|
||||
const { replaceNodesInPlace } = useNodeReplacement()
|
||||
const dialogStore = useDialogStore()
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
|
||||
interface ProcessedNode {
|
||||
label: string
|
||||
@@ -339,6 +341,11 @@ function handleReplaceSelected() {
|
||||
replacedTypes.value = nextReplaced
|
||||
selectedTypes.value = nextSelected
|
||||
|
||||
// Sync with execution error store so the Errors Tab updates immediately
|
||||
if (result.length > 0) {
|
||||
executionErrorStore.removeMissingNodesByType(result)
|
||||
}
|
||||
|
||||
// Auto-close when all replaceable nodes replaced and no non-replaceable remain
|
||||
const allReplaced = replaceableNodes.value.every((n) =>
|
||||
nextReplaced.has(n.label)
|
||||
|
||||
359
src/components/painter/WidgetPainter.vue
Normal file
359
src/components/painter/WidgetPainter.vue
Normal file
@@ -0,0 +1,359 @@
|
||||
<template>
|
||||
<div
|
||||
class="widget-expands flex h-full w-full flex-col gap-1"
|
||||
@pointerdown.stop
|
||||
@pointermove.stop
|
||||
@pointerup.stop
|
||||
>
|
||||
<div
|
||||
class="flex min-h-0 flex-1 items-center justify-center overflow-hidden rounded-lg bg-node-component-surface"
|
||||
>
|
||||
<div class="relative max-h-full w-full" :style="canvasContainerStyle">
|
||||
<img
|
||||
v-if="inputImageUrl"
|
||||
:src="inputImageUrl"
|
||||
class="absolute inset-0 size-full"
|
||||
draggable="false"
|
||||
@load="handleInputImageLoad"
|
||||
@dragstart.prevent
|
||||
/>
|
||||
<canvas
|
||||
ref="canvasEl"
|
||||
class="absolute inset-0 size-full cursor-none touch-none"
|
||||
@pointerdown="handlePointerDown"
|
||||
@pointermove="handlePointerMove"
|
||||
@pointerup="handlePointerUp"
|
||||
@pointerenter="handlePointerEnter"
|
||||
@pointerleave="handlePointerLeave"
|
||||
/>
|
||||
<div
|
||||
v-show="cursorVisible"
|
||||
class="pointer-events-none absolute left-0 top-0 rounded-full border border-black/60 shadow-[0_0_0_1px_rgba(255,255,255,0.8)]"
|
||||
:style="cursorStyle"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isImageInputConnected"
|
||||
class="text-center text-xs text-muted-foreground"
|
||||
>
|
||||
{{ canvasWidth }} x {{ canvasHeight }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref="controlsEl"
|
||||
:class="
|
||||
cn(
|
||||
'grid shrink-0 gap-x-1 gap-y-1',
|
||||
compact ? 'grid-cols-1' : 'grid-cols-[auto_1fr]'
|
||||
)
|
||||
"
|
||||
>
|
||||
<div
|
||||
v-if="!compact"
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.tool') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 items-center gap-1 rounded-sm bg-component-node-widget-background p-1"
|
||||
>
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="unset"
|
||||
:class="
|
||||
cn(
|
||||
'flex-1 self-stretch px-2 text-xs transition-colors',
|
||||
tool === PAINTER_TOOLS.BRUSH
|
||||
? 'rounded-sm bg-component-node-widget-background-selected text-base-foreground'
|
||||
: 'text-node-text-muted hover:text-node-text'
|
||||
)
|
||||
"
|
||||
@click="tool = PAINTER_TOOLS.BRUSH"
|
||||
>
|
||||
{{ $t('painter.brush') }}
|
||||
</Button>
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="unset"
|
||||
:class="
|
||||
cn(
|
||||
'flex-1 self-stretch px-2 text-xs transition-colors',
|
||||
tool === PAINTER_TOOLS.ERASER
|
||||
? 'rounded-sm bg-component-node-widget-background-selected text-base-foreground'
|
||||
: 'text-node-text-muted hover:text-node-text'
|
||||
)
|
||||
"
|
||||
@click="tool = PAINTER_TOOLS.ERASER"
|
||||
>
|
||||
{{ $t('painter.eraser') }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!compact"
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.size') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 items-center gap-2 rounded-lg bg-component-node-widget-background pr-2 pl-3"
|
||||
>
|
||||
<Slider
|
||||
:model-value="[brushSize]"
|
||||
:min="1"
|
||||
:max="200"
|
||||
:step="1"
|
||||
class="flex-1"
|
||||
@update:model-value="(v) => v?.length && (brushSize = v[0])"
|
||||
/>
|
||||
<span class="w-8 text-center text-xs text-node-text-muted">{{
|
||||
brushSize
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<template v-if="tool === PAINTER_TOOLS.BRUSH">
|
||||
<div
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.color') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 w-full items-center gap-2 rounded-lg bg-component-node-widget-background px-4"
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
:value="brushColorDisplay"
|
||||
class="h-4 w-8 cursor-pointer appearance-none overflow-hidden rounded-full border-none bg-transparent [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:border-none [&::-webkit-color-swatch]:rounded-full [&::-moz-color-swatch]:border-none [&::-moz-color-swatch]:rounded-full"
|
||||
@input="
|
||||
(e) => (brushColorDisplay = (e.target as HTMLInputElement).value)
|
||||
"
|
||||
/>
|
||||
<span class="min-w-[4ch] truncate text-xs">{{
|
||||
brushColorDisplay
|
||||
}}</span>
|
||||
<span class="ml-auto flex items-center text-xs text-node-text-muted">
|
||||
<input
|
||||
type="number"
|
||||
:value="brushOpacityPercent"
|
||||
min="0"
|
||||
max="100"
|
||||
step="1"
|
||||
class="w-7 appearance-none border-0 bg-transparent text-right text-xs text-node-text-muted outline-none [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||
@click.prevent
|
||||
@change="
|
||||
(e) => {
|
||||
const val = Math.min(
|
||||
100,
|
||||
Math.max(0, Number((e.target as HTMLInputElement).value))
|
||||
)
|
||||
brushOpacityPercent = val
|
||||
;(e.target as HTMLInputElement).value = String(val)
|
||||
}
|
||||
"
|
||||
/>%</span
|
||||
>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.hardness') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 items-center gap-2 rounded-lg bg-component-node-widget-background pr-2 pl-3"
|
||||
>
|
||||
<Slider
|
||||
:model-value="[brushHardnessPercent]"
|
||||
:min="0"
|
||||
:max="100"
|
||||
:step="1"
|
||||
class="flex-1"
|
||||
@update:model-value="
|
||||
(v) => v?.length && (brushHardnessPercent = v[0])
|
||||
"
|
||||
/>
|
||||
<span class="w-8 text-center text-xs text-node-text-muted"
|
||||
>{{ brushHardnessPercent }}%</span
|
||||
>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-if="!isImageInputConnected">
|
||||
<div
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.width') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 items-center gap-2 rounded-lg bg-component-node-widget-background pr-2 pl-3"
|
||||
>
|
||||
<Slider
|
||||
:model-value="[canvasWidth]"
|
||||
:min="64"
|
||||
:max="4096"
|
||||
:step="64"
|
||||
class="flex-1"
|
||||
@update:model-value="(v) => v?.length && (canvasWidth = v[0])"
|
||||
/>
|
||||
<span class="w-10 text-center text-xs text-node-text-muted">{{
|
||||
canvasWidth
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.height') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 items-center gap-2 rounded-lg bg-component-node-widget-background pr-2 pl-3"
|
||||
>
|
||||
<Slider
|
||||
:model-value="[canvasHeight]"
|
||||
:min="64"
|
||||
:max="4096"
|
||||
:step="64"
|
||||
class="flex-1"
|
||||
@update:model-value="(v) => v?.length && (canvasHeight = v[0])"
|
||||
/>
|
||||
<span class="w-10 text-center text-xs text-node-text-muted">{{
|
||||
canvasHeight
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex w-28 items-center truncate text-sm text-muted-foreground"
|
||||
>
|
||||
{{ $t('painter.background') }}
|
||||
</div>
|
||||
<div
|
||||
class="flex h-8 w-full items-center gap-2 rounded-lg bg-component-node-widget-background px-4"
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
:value="backgroundColorDisplay"
|
||||
class="h-4 w-8 cursor-pointer appearance-none overflow-hidden rounded-full border-none bg-transparent [&::-webkit-color-swatch-wrapper]:p-0 [&::-webkit-color-swatch]:border-none [&::-webkit-color-swatch]:rounded-full [&::-moz-color-swatch]:border-none [&::-moz-color-swatch]:rounded-full"
|
||||
@input="
|
||||
(e) =>
|
||||
(backgroundColorDisplay = (e.target as HTMLInputElement).value)
|
||||
"
|
||||
/>
|
||||
<span class="min-w-[4ch] truncate text-xs">{{
|
||||
backgroundColorDisplay
|
||||
}}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="md"
|
||||
:class="
|
||||
cn(
|
||||
'gap-2 rounded-lg border border-component-node-border bg-component-node-background text-xs text-muted-foreground hover:text-base-foreground',
|
||||
!compact && 'col-span-2'
|
||||
)
|
||||
"
|
||||
@click="handleClear"
|
||||
>
|
||||
<i class="icon-[lucide--undo-2]" />
|
||||
{{ $t('painter.clear') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { computed, useTemplateRef } from 'vue'
|
||||
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import Slider from '@/components/ui/slider/Slider.vue'
|
||||
import { PAINTER_TOOLS, usePainter } from '@/composables/painter/usePainter'
|
||||
import { toHexFromFormat } from '@/utils/colorUtil'
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
|
||||
const { nodeId } = defineProps<{
|
||||
nodeId: string
|
||||
}>()
|
||||
|
||||
const modelValue = defineModel<string>({ default: '' })
|
||||
|
||||
const canvasEl = useTemplateRef<HTMLCanvasElement>('canvasEl')
|
||||
const controlsEl = useTemplateRef<HTMLDivElement>('controlsEl')
|
||||
const { width: controlsWidth } = useElementSize(controlsEl)
|
||||
const compact = computed(
|
||||
() => controlsWidth.value > 0 && controlsWidth.value < 350
|
||||
)
|
||||
|
||||
const {
|
||||
tool,
|
||||
brushSize,
|
||||
brushColor,
|
||||
brushOpacity,
|
||||
brushHardness,
|
||||
backgroundColor,
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
cursorX,
|
||||
cursorY,
|
||||
cursorVisible,
|
||||
displayBrushSize,
|
||||
inputImageUrl,
|
||||
isImageInputConnected,
|
||||
handlePointerDown,
|
||||
handlePointerMove,
|
||||
handlePointerUp,
|
||||
handlePointerEnter,
|
||||
handlePointerLeave,
|
||||
handleInputImageLoad,
|
||||
handleClear
|
||||
} = usePainter(nodeId, { canvasEl, modelValue })
|
||||
|
||||
const canvasContainerStyle = computed(() => ({
|
||||
aspectRatio: `${canvasWidth.value} / ${canvasHeight.value}`,
|
||||
backgroundColor: isImageInputConnected.value
|
||||
? undefined
|
||||
: backgroundColor.value
|
||||
}))
|
||||
|
||||
const cursorStyle = computed(() => {
|
||||
const size = displayBrushSize.value
|
||||
const x = cursorX.value - size / 2
|
||||
const y = cursorY.value - size / 2
|
||||
return {
|
||||
width: `${size}px`,
|
||||
height: `${size}px`,
|
||||
transform: `translate(${x}px, ${y}px)`
|
||||
}
|
||||
})
|
||||
|
||||
const brushOpacityPercent = computed({
|
||||
get: () => Math.round(brushOpacity.value * 100),
|
||||
set: (val: number) => {
|
||||
brushOpacity.value = val / 100
|
||||
}
|
||||
})
|
||||
|
||||
const brushHardnessPercent = computed({
|
||||
get: () => Math.round(brushHardness.value * 100),
|
||||
set: (val: number) => {
|
||||
brushHardness.value = val / 100
|
||||
}
|
||||
})
|
||||
|
||||
const brushColorDisplay = computed({
|
||||
get: () => toHexFromFormat(brushColor.value, 'hex'),
|
||||
set: (val: unknown) => {
|
||||
brushColor.value = toHexFromFormat(val, 'hex')
|
||||
}
|
||||
})
|
||||
|
||||
const backgroundColorDisplay = computed({
|
||||
get: () => toHexFromFormat(backgroundColor.value, 'hex'),
|
||||
set: (val: unknown) => {
|
||||
backgroundColor.value = toHexFromFormat(val, 'hex')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
146
src/components/queue/job/JobAssetsList.test.ts
Normal file
146
src/components/queue/job/JobAssetsList.test.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { JobGroup, JobListItem } from '@/composables/queue/useJobList'
|
||||
import type { JobListItem as ApiJobListItem } from '@/platform/remote/comfyui/jobs/jobTypes'
|
||||
import { ResultItemImpl, TaskItemImpl } from '@/stores/queueStore'
|
||||
|
||||
import JobAssetsList from './JobAssetsList.vue'
|
||||
|
||||
vi.mock('vue-i18n', () => {
|
||||
return {
|
||||
createI18n: () => ({
|
||||
global: {
|
||||
t: (key: string) => key,
|
||||
te: () => true,
|
||||
d: (value: string) => value
|
||||
}
|
||||
}),
|
||||
useI18n: () => ({
|
||||
t: (key: string) => key
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const createResultItem = (
|
||||
filename: string,
|
||||
mediaType: string = 'images'
|
||||
): ResultItemImpl => {
|
||||
const item = new ResultItemImpl({
|
||||
filename,
|
||||
subfolder: '',
|
||||
type: 'output',
|
||||
nodeId: 'node-1',
|
||||
mediaType
|
||||
})
|
||||
Object.defineProperty(item, 'url', {
|
||||
get: () => `/api/view/${filename}`
|
||||
})
|
||||
return item
|
||||
}
|
||||
|
||||
const createTaskRef = (preview?: ResultItemImpl): TaskItemImpl => {
|
||||
const job: ApiJobListItem = {
|
||||
id: `task-${Math.random().toString(36).slice(2)}`,
|
||||
status: 'completed',
|
||||
create_time: Date.now(),
|
||||
preview_output: null,
|
||||
outputs_count: preview ? 1 : 0,
|
||||
priority: 0
|
||||
}
|
||||
const flatOutputs = preview ? [preview] : []
|
||||
return new TaskItemImpl(job, {}, flatOutputs)
|
||||
}
|
||||
|
||||
const buildJob = (overrides: Partial<JobListItem> = {}): JobListItem => ({
|
||||
id: 'job-1',
|
||||
title: 'Job 1',
|
||||
meta: 'meta',
|
||||
state: 'completed',
|
||||
taskRef: createTaskRef(createResultItem('job-1.png')),
|
||||
...overrides
|
||||
})
|
||||
|
||||
const mountJobAssetsList = (jobs: JobListItem[]) => {
|
||||
const displayedJobGroups: JobGroup[] = [
|
||||
{
|
||||
key: 'group-1',
|
||||
label: 'Group 1',
|
||||
items: jobs
|
||||
}
|
||||
]
|
||||
|
||||
return mount(JobAssetsList, {
|
||||
props: { displayedJobGroups }
|
||||
})
|
||||
}
|
||||
|
||||
describe('JobAssetsList', () => {
|
||||
it('emits viewItem on preview-click for completed jobs with preview', async () => {
|
||||
const job = buildJob()
|
||||
const wrapper = mountJobAssetsList([job])
|
||||
|
||||
const listItem = wrapper.findComponent({ name: 'AssetsListItem' })
|
||||
listItem.vm.$emit('preview-click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('viewItem')).toEqual([[job]])
|
||||
})
|
||||
|
||||
it('emits viewItem on double-click for completed jobs with preview', async () => {
|
||||
const job = buildJob()
|
||||
const wrapper = mountJobAssetsList([job])
|
||||
|
||||
const listItem = wrapper.findComponent({ name: 'AssetsListItem' })
|
||||
await listItem.trigger('dblclick')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('viewItem')).toEqual([[job]])
|
||||
})
|
||||
|
||||
it('emits viewItem on double-click for completed video jobs without icon image', async () => {
|
||||
const job = buildJob({
|
||||
iconImageUrl: undefined,
|
||||
taskRef: createTaskRef(createResultItem('job-1.webm', 'video'))
|
||||
})
|
||||
const wrapper = mountJobAssetsList([job])
|
||||
|
||||
const listItem = wrapper.findComponent({ name: 'AssetsListItem' })
|
||||
expect(listItem.props('previewUrl')).toBe('/api/view/job-1.webm')
|
||||
expect(listItem.props('isVideoPreview')).toBe(true)
|
||||
|
||||
await listItem.trigger('dblclick')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('viewItem')).toEqual([[job]])
|
||||
})
|
||||
|
||||
it('emits viewItem on icon click for completed 3D jobs without preview tile', async () => {
|
||||
const job = buildJob({
|
||||
iconImageUrl: undefined,
|
||||
taskRef: createTaskRef(createResultItem('job-1.glb', 'model'))
|
||||
})
|
||||
const wrapper = mountJobAssetsList([job])
|
||||
|
||||
const listItem = wrapper.findComponent({ name: 'AssetsListItem' })
|
||||
|
||||
await listItem.find('i').trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('viewItem')).toEqual([[job]])
|
||||
})
|
||||
|
||||
it('does not emit viewItem on double-click for non-completed jobs', async () => {
|
||||
const job = buildJob({
|
||||
state: 'running',
|
||||
taskRef: createTaskRef(createResultItem('job-1.png'))
|
||||
})
|
||||
const wrapper = mountJobAssetsList([job])
|
||||
|
||||
const listItem = wrapper.findComponent({ name: 'AssetsListItem' })
|
||||
await listItem.trigger('dblclick')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('viewItem')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -12,7 +12,8 @@
|
||||
v-for="job in group.items"
|
||||
:key="job.id"
|
||||
class="w-full shrink-0 cursor-default text-text-primary transition-colors hover:bg-secondary-background-hover"
|
||||
:preview-url="job.iconImageUrl"
|
||||
:preview-url="getJobPreviewUrl(job)"
|
||||
:is-video-preview="isVideoPreviewJob(job)"
|
||||
:preview-alt="job.title"
|
||||
:icon-name="job.iconName ?? iconForJobState(job.state)"
|
||||
:icon-class="getJobIconClass(job)"
|
||||
@@ -23,6 +24,8 @@
|
||||
@mouseenter="hoveredJobId = job.id"
|
||||
@mouseleave="onJobLeave(job.id)"
|
||||
@contextmenu.prevent.stop="$emit('menu', job, $event)"
|
||||
@dblclick.stop="emitViewItem(job)"
|
||||
@preview-click="emitViewItem(job)"
|
||||
@click.stop
|
||||
>
|
||||
<template v-if="hoveredJobId === job.id" #actions>
|
||||
@@ -78,7 +81,7 @@ import { isActiveJobState } from '@/utils/queueUtil'
|
||||
|
||||
defineProps<{ displayedJobGroups: JobGroup[] }>()
|
||||
|
||||
defineEmits<{
|
||||
const emit = defineEmits<{
|
||||
(e: 'cancelItem', item: JobListItem): void
|
||||
(e: 'deleteItem', item: JobListItem): void
|
||||
(e: 'menu', item: JobListItem, ev: MouseEvent): void
|
||||
@@ -100,6 +103,28 @@ const isCancelable = (job: JobListItem) =>
|
||||
const isFailedDeletable = (job: JobListItem) =>
|
||||
job.showClear !== false && job.state === 'failed'
|
||||
|
||||
const getPreviewOutput = (job: JobListItem) => job.taskRef?.previewOutput
|
||||
|
||||
const getJobPreviewUrl = (job: JobListItem) => {
|
||||
const preview = getPreviewOutput(job)
|
||||
if (preview?.isImage || preview?.isVideo) {
|
||||
return preview.url
|
||||
}
|
||||
return job.iconImageUrl
|
||||
}
|
||||
|
||||
const isVideoPreviewJob = (job: JobListItem) =>
|
||||
job.state === 'completed' && !!getPreviewOutput(job)?.isVideo
|
||||
|
||||
const isPreviewableCompletedJob = (job: JobListItem) =>
|
||||
job.state === 'completed' && !!getPreviewOutput(job)
|
||||
|
||||
const emitViewItem = (job: JobListItem) => {
|
||||
if (isPreviewableCompletedJob(job)) {
|
||||
emit('viewItem', job)
|
||||
}
|
||||
}
|
||||
|
||||
const getJobIconClass = (job: JobListItem): string | undefined => {
|
||||
const iconName = job.iconName ?? iconForJobState(job.state)
|
||||
if (!job.iconImageUrl && iconName === iconForJobState('pending')) {
|
||||
|
||||
@@ -131,11 +131,11 @@ export const Queued: Story = {
|
||||
const exec = useExecutionStore()
|
||||
|
||||
const jobId = 'job-queued-1'
|
||||
const queueIndex = 104
|
||||
const priority = 104
|
||||
|
||||
// Current job in pending
|
||||
queue.pendingTasks = [
|
||||
makePendingTask(jobId, queueIndex, Date.now() - 90_000)
|
||||
makePendingTask(jobId, priority, Date.now() - 90_000)
|
||||
]
|
||||
// Add some other pending jobs to give context
|
||||
queue.pendingTasks.push(
|
||||
@@ -179,13 +179,13 @@ export const QueuedParallel: Story = {
|
||||
const exec = useExecutionStore()
|
||||
|
||||
const jobId = 'job-queued-parallel'
|
||||
const queueIndex = 210
|
||||
const priority = 210
|
||||
|
||||
// Current job in pending with some ahead
|
||||
queue.pendingTasks = [
|
||||
makePendingTask('job-ahead-1', 200, Date.now() - 180_000),
|
||||
makePendingTask('job-ahead-2', 205, Date.now() - 150_000),
|
||||
makePendingTask(jobId, queueIndex, Date.now() - 120_000)
|
||||
makePendingTask(jobId, priority, Date.now() - 120_000)
|
||||
]
|
||||
|
||||
// Seen 2 minutes ago - set via prompt metadata above
|
||||
@@ -238,9 +238,9 @@ export const Running: Story = {
|
||||
const exec = useExecutionStore()
|
||||
|
||||
const jobId = 'job-running-1'
|
||||
const queueIndex = 300
|
||||
const priority = 300
|
||||
queue.runningTasks = [
|
||||
makeRunningTask(jobId, queueIndex, Date.now() - 65_000)
|
||||
makeRunningTask(jobId, priority, Date.now() - 65_000)
|
||||
]
|
||||
queue.historyTasks = [
|
||||
makeHistoryTask('hist-r1', 250, 30, true),
|
||||
@@ -279,10 +279,10 @@ export const QueuedZeroAheadSingleRunning: Story = {
|
||||
const exec = useExecutionStore()
|
||||
|
||||
const jobId = 'job-queued-zero-ahead-single'
|
||||
const queueIndex = 510
|
||||
const priority = 510
|
||||
|
||||
queue.pendingTasks = [
|
||||
makePendingTask(jobId, queueIndex, Date.now() - 45_000)
|
||||
makePendingTask(jobId, priority, Date.now() - 45_000)
|
||||
]
|
||||
|
||||
queue.historyTasks = [
|
||||
@@ -324,10 +324,10 @@ export const QueuedZeroAheadMultiRunning: Story = {
|
||||
const exec = useExecutionStore()
|
||||
|
||||
const jobId = 'job-queued-zero-ahead-multi'
|
||||
const queueIndex = 520
|
||||
const priority = 520
|
||||
|
||||
queue.pendingTasks = [
|
||||
makePendingTask(jobId, queueIndex, Date.now() - 20_000)
|
||||
makePendingTask(jobId, priority, Date.now() - 20_000)
|
||||
]
|
||||
|
||||
queue.historyTasks = [
|
||||
@@ -380,8 +380,8 @@ export const Completed: Story = {
|
||||
const queue = useQueueStore()
|
||||
|
||||
const jobId = 'job-completed-1'
|
||||
const queueIndex = 400
|
||||
queue.historyTasks = [makeHistoryTask(jobId, queueIndex, 37, true)]
|
||||
const priority = 400
|
||||
queue.historyTasks = [makeHistoryTask(jobId, priority, 37, true)]
|
||||
|
||||
return { args: { ...args, jobId } }
|
||||
},
|
||||
@@ -401,11 +401,11 @@ export const Failed: Story = {
|
||||
const queue = useQueueStore()
|
||||
|
||||
const jobId = 'job-failed-1'
|
||||
const queueIndex = 410
|
||||
const priority = 410
|
||||
queue.historyTasks = [
|
||||
makeHistoryTask(
|
||||
jobId,
|
||||
queueIndex,
|
||||
priority,
|
||||
12,
|
||||
false,
|
||||
'Example error: invalid inputs for node X'
|
||||
|
||||
@@ -168,14 +168,14 @@ const queuedAtValue = computed(() =>
|
||||
|
||||
const currentQueueIndex = computed<number | null>(() => {
|
||||
const task = taskForJob.value
|
||||
return task ? Number(task.queueIndex) : null
|
||||
return task ? Number(task.job.priority) : null
|
||||
})
|
||||
|
||||
const jobsAhead = computed<number | null>(() => {
|
||||
const idx = currentQueueIndex.value
|
||||
if (idx == null) return null
|
||||
const ahead = queueStore.pendingTasks.filter(
|
||||
(t: TaskItemImpl) => Number(t.queueIndex) < idx
|
||||
(t: TaskItemImpl) => Number(t.job.priority) < idx
|
||||
)
|
||||
return ahead.length
|
||||
})
|
||||
|
||||
@@ -40,7 +40,8 @@ const rightSidePanelStore = useRightSidePanelStore()
|
||||
const settingStore = useSettingStore()
|
||||
const { t } = useI18n()
|
||||
|
||||
const { hasAnyError, allErrorExecutionIds } = storeToRefs(executionErrorStore)
|
||||
const { hasAnyError, allErrorExecutionIds, activeMissingNodeGraphIds } =
|
||||
storeToRefs(executionErrorStore)
|
||||
|
||||
const { findParentGroup } = useGraphHierarchy()
|
||||
|
||||
@@ -109,9 +110,21 @@ const hasContainerInternalError = computed(() => {
|
||||
})
|
||||
})
|
||||
|
||||
const hasMissingNodeSelected = computed(
|
||||
() =>
|
||||
hasSelection.value &&
|
||||
selectedNodes.value.some((node) =>
|
||||
activeMissingNodeGraphIds.value.has(String(node.id))
|
||||
)
|
||||
)
|
||||
|
||||
const hasRelevantErrors = computed(() => {
|
||||
if (!hasSelection.value) return hasAnyError.value
|
||||
return hasDirectNodeError.value || hasContainerInternalError.value
|
||||
return (
|
||||
hasDirectNodeError.value ||
|
||||
hasContainerInternalError.value ||
|
||||
hasMissingNodeSelected.value
|
||||
)
|
||||
})
|
||||
|
||||
const tabs = computed<RightSidePanelTabList>(() => {
|
||||
|
||||
@@ -17,24 +17,26 @@
|
||||
>
|
||||
{{ card.nodeTitle }}
|
||||
</span>
|
||||
<Button
|
||||
v-if="card.isSubgraphNode"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="rounded-lg text-sm shrink-0"
|
||||
@click.stop="handleEnterSubgraph"
|
||||
>
|
||||
{{ t('rightSidePanel.enterSubgraph') }}
|
||||
</Button>
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
class="size-7 text-muted-foreground hover:text-base-foreground shrink-0"
|
||||
:aria-label="t('rightSidePanel.locateNode')"
|
||||
@click.stop="handleLocateNode"
|
||||
>
|
||||
<i class="icon-[lucide--locate] size-3.5" />
|
||||
</Button>
|
||||
<div class="flex items-center shrink-0">
|
||||
<Button
|
||||
v-if="card.isSubgraphNode"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="rounded-lg text-sm shrink-0 h-8"
|
||||
@click.stop="handleEnterSubgraph"
|
||||
>
|
||||
{{ t('rightSidePanel.enterSubgraph') }}
|
||||
</Button>
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
class="size-8 text-muted-foreground hover:text-base-foreground shrink-0"
|
||||
:aria-label="t('rightSidePanel.locateNode')"
|
||||
@click.stop="handleLocateNode"
|
||||
>
|
||||
<i class="icon-[lucide--locate] size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Multiple Errors within one Card -->
|
||||
|
||||
79
src/components/rightSidePanel/errors/MissingNodeCard.vue
Normal file
79
src/components/rightSidePanel/errors/MissingNodeCard.vue
Normal file
@@ -0,0 +1,79 @@
|
||||
<template>
|
||||
<div class="px-4 pb-2">
|
||||
<!-- Sub-label: cloud or OSS message shown above all pack groups -->
|
||||
<p class="m-0 pb-5 text-sm text-muted-foreground leading-relaxed">
|
||||
{{
|
||||
isCloud
|
||||
? t('rightSidePanel.missingNodePacks.cloudMessage')
|
||||
: t('rightSidePanel.missingNodePacks.ossMessage')
|
||||
}}
|
||||
</p>
|
||||
<MissingPackGroupRow
|
||||
v-for="group in missingPackGroups"
|
||||
:key="group.packId ?? '__unknown__'"
|
||||
:group="group"
|
||||
:show-info-button="showInfoButton"
|
||||
:show-node-id-badge="showNodeIdBadge"
|
||||
@locate-node="emit('locateNode', $event)"
|
||||
@open-manager-info="emit('openManagerInfo', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Apply Changes: shown when manager enabled and at least one pack install succeeded -->
|
||||
<div v-if="shouldShowManagerButtons" class="px-4">
|
||||
<Button
|
||||
v-if="hasInstalledPacksPendingRestart"
|
||||
variant="primary"
|
||||
:disabled="isRestarting"
|
||||
class="w-full h-9 justify-center gap-2 text-sm font-semibold mt-2"
|
||||
@click="applyChanges()"
|
||||
>
|
||||
<DotSpinner v-if="isRestarting" duration="1s" :size="14" />
|
||||
<i v-else class="icon-[lucide--refresh-cw] size-4 shrink-0" />
|
||||
<span class="truncate min-w-0">{{
|
||||
t('rightSidePanel.missingNodePacks.applyChanges')
|
||||
}}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import DotSpinner from '@/components/common/DotSpinner.vue'
|
||||
import { useApplyChanges } from '@/workbench/extensions/manager/composables/useApplyChanges'
|
||||
import { useComfyManagerStore } from '@/workbench/extensions/manager/stores/comfyManagerStore'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState'
|
||||
import type { MissingPackGroup } from '@/components/rightSidePanel/errors/useErrorGroups'
|
||||
import MissingPackGroupRow from '@/components/rightSidePanel/errors/MissingPackGroupRow.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
showInfoButton: boolean
|
||||
showNodeIdBadge: boolean
|
||||
missingPackGroups: MissingPackGroup[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
locateNode: [nodeId: string]
|
||||
openManagerInfo: [packId: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const comfyManagerStore = useComfyManagerStore()
|
||||
const { isRestarting, applyChanges } = useApplyChanges()
|
||||
const { shouldShowManagerButtons } = useManagerState()
|
||||
|
||||
/**
|
||||
* Show Apply Changes when any pack from the error group is already installed
|
||||
* on disk but ComfyUI hasn't restarted yet to load it.
|
||||
* This is server-state based → persists across browser refreshes.
|
||||
*/
|
||||
const hasInstalledPacksPendingRestart = computed(() =>
|
||||
props.missingPackGroups.some(
|
||||
(g) => g.packId !== null && comfyManagerStore.isPackInstalled(g.packId)
|
||||
)
|
||||
)
|
||||
</script>
|
||||
250
src/components/rightSidePanel/errors/MissingPackGroupRow.vue
Normal file
250
src/components/rightSidePanel/errors/MissingPackGroupRow.vue
Normal file
@@ -0,0 +1,250 @@
|
||||
<template>
|
||||
<div class="flex flex-col w-full mb-2">
|
||||
<!-- Pack header row: pack name + info + chevron -->
|
||||
<div class="flex h-8 items-center w-full">
|
||||
<!-- Warning icon for unknown packs -->
|
||||
<i
|
||||
v-if="group.packId === null && !group.isResolving"
|
||||
class="icon-[lucide--triangle-alert] size-4 text-warning-background shrink-0 mr-1.5"
|
||||
/>
|
||||
<p
|
||||
class="flex-1 min-w-0 text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap"
|
||||
:class="
|
||||
group.packId === null && !group.isResolving
|
||||
? 'text-warning-background'
|
||||
: 'text-foreground'
|
||||
"
|
||||
>
|
||||
<span v-if="group.isResolving" class="text-muted-foreground italic">
|
||||
{{ t('g.loading') }}...
|
||||
</span>
|
||||
<span v-else>
|
||||
{{
|
||||
`${group.packId ?? t('rightSidePanel.missingNodePacks.unknownPack')} (${group.nodeTypes.length})`
|
||||
}}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
v-if="showInfoButton && group.packId !== null"
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
class="size-8 text-muted-foreground hover:text-base-foreground shrink-0"
|
||||
:aria-label="t('rightSidePanel.missingNodePacks.viewInManager')"
|
||||
@click="emit('openManagerInfo', group.packId ?? '')"
|
||||
>
|
||||
<i class="icon-[lucide--info] size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
:class="
|
||||
cn(
|
||||
'size-8 shrink-0 transition-transform duration-200 hover:bg-transparent',
|
||||
{ 'rotate-180': expanded }
|
||||
)
|
||||
"
|
||||
:aria-label="
|
||||
expanded
|
||||
? t('rightSidePanel.missingNodePacks.collapse')
|
||||
: t('rightSidePanel.missingNodePacks.expand')
|
||||
"
|
||||
@click="toggleExpand"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--chevron-down] size-4 text-muted-foreground group-hover:text-base-foreground"
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Sub-labels: individual node instances, each with their own Locate button -->
|
||||
<TransitionCollapse>
|
||||
<div
|
||||
v-if="expanded"
|
||||
class="flex flex-col gap-0.5 pl-2 mb-1 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
v-for="nodeType in group.nodeTypes"
|
||||
:key="getKey(nodeType)"
|
||||
class="flex h-7 items-center"
|
||||
>
|
||||
<span
|
||||
v-if="
|
||||
showNodeIdBadge &&
|
||||
typeof nodeType !== 'string' &&
|
||||
nodeType.nodeId != null
|
||||
"
|
||||
class="shrink-0 rounded-md bg-secondary-background-selected px-2 py-0.5 text-xs font-mono text-muted-foreground font-bold mr-1"
|
||||
>
|
||||
#{{ nodeType.nodeId }}
|
||||
</span>
|
||||
<p class="flex-1 min-w-0 text-xs text-muted-foreground truncate">
|
||||
{{ getLabel(nodeType) }}
|
||||
</p>
|
||||
<Button
|
||||
v-if="typeof nodeType !== 'string' && nodeType.nodeId != null"
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
class="size-6 text-muted-foreground hover:text-base-foreground shrink-0 mr-1"
|
||||
:aria-label="t('rightSidePanel.locateNode')"
|
||||
@click="handleLocateNode(nodeType)"
|
||||
>
|
||||
<i class="icon-[lucide--locate] size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TransitionCollapse>
|
||||
|
||||
<!-- Install button: shown when manager enabled, registry knows the pack or it's already installed -->
|
||||
<div
|
||||
v-if="
|
||||
shouldShowManagerButtons &&
|
||||
group.packId !== null &&
|
||||
(nodePack || comfyManagerStore.isPackInstalled(group.packId))
|
||||
"
|
||||
class="flex items-start w-full pt-1 pb-1"
|
||||
>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="md"
|
||||
class="flex flex-1 w-full"
|
||||
:disabled="
|
||||
comfyManagerStore.isPackInstalled(group.packId) || isInstalling
|
||||
"
|
||||
@click="handlePackInstallClick"
|
||||
>
|
||||
<DotSpinner
|
||||
v-if="isInstalling"
|
||||
duration="1s"
|
||||
:size="12"
|
||||
class="mr-1.5 shrink-0"
|
||||
/>
|
||||
<i
|
||||
v-else-if="comfyManagerStore.isPackInstalled(group.packId)"
|
||||
class="icon-[lucide--check] size-4 text-foreground shrink-0 mr-1"
|
||||
/>
|
||||
<i
|
||||
v-else
|
||||
class="icon-[lucide--download] size-4 text-foreground shrink-0 mr-1"
|
||||
/>
|
||||
<span class="text-sm text-foreground truncate min-w-0">
|
||||
{{
|
||||
isInstalling
|
||||
? t('rightSidePanel.missingNodePacks.installing')
|
||||
: comfyManagerStore.isPackInstalled(group.packId)
|
||||
? t('rightSidePanel.missingNodePacks.installed')
|
||||
: t('rightSidePanel.missingNodePacks.installNodePack')
|
||||
}}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Registry still loading: packId known but result not yet available -->
|
||||
<div
|
||||
v-else-if="group.packId !== null && shouldShowManagerButtons && isLoading"
|
||||
class="flex items-start w-full pt-1 pb-1"
|
||||
>
|
||||
<div
|
||||
class="flex flex-1 h-8 items-center justify-center overflow-hidden p-2 rounded-lg min-w-0 bg-secondary-background opacity-60 cursor-not-allowed select-none"
|
||||
>
|
||||
<DotSpinner duration="1s" :size="12" class="mr-1.5 shrink-0" />
|
||||
<span class="text-sm text-foreground truncate min-w-0">
|
||||
{{ t('g.loading') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Search in Manager: fetch done but pack not found in registry -->
|
||||
<div
|
||||
v-else-if="group.packId !== null && shouldShowManagerButtons"
|
||||
class="flex items-start w-full pt-1 pb-1"
|
||||
>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="md"
|
||||
class="flex flex-1 w-full"
|
||||
@click="
|
||||
openManager({
|
||||
initialTab: ManagerTab.All,
|
||||
initialPackId: group.packId!
|
||||
})
|
||||
"
|
||||
>
|
||||
<i class="icon-[lucide--search] size-4 text-foreground shrink-0 mr-1" />
|
||||
<span class="text-sm text-foreground truncate min-w-0">
|
||||
{{ t('rightSidePanel.missingNodePacks.searchInManager') }}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import DotSpinner from '@/components/common/DotSpinner.vue'
|
||||
import TransitionCollapse from '@/components/rightSidePanel/layout/TransitionCollapse.vue'
|
||||
import { useMissingNodes } from '@/workbench/extensions/manager/composables/nodePack/useMissingNodes'
|
||||
import { usePackInstall } from '@/workbench/extensions/manager/composables/nodePack/usePackInstall'
|
||||
import { useComfyManagerStore } from '@/workbench/extensions/manager/stores/comfyManagerStore'
|
||||
import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState'
|
||||
import { ManagerTab } from '@/workbench/extensions/manager/types/comfyManagerTypes'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import type { MissingPackGroup } from '@/components/rightSidePanel/errors/useErrorGroups'
|
||||
|
||||
const props = defineProps<{
|
||||
group: MissingPackGroup
|
||||
showInfoButton: boolean
|
||||
showNodeIdBadge: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
locateNode: [nodeId: string]
|
||||
openManagerInfo: [packId: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { missingNodePacks, isLoading } = useMissingNodes()
|
||||
const comfyManagerStore = useComfyManagerStore()
|
||||
const { shouldShowManagerButtons, openManager } = useManagerState()
|
||||
|
||||
const nodePack = computed(() => {
|
||||
if (!props.group.packId) return null
|
||||
return missingNodePacks.value.find((p) => p.id === props.group.packId) ?? null
|
||||
})
|
||||
|
||||
const { isInstalling, installAllPacks } = usePackInstall(() =>
|
||||
nodePack.value ? [nodePack.value] : []
|
||||
)
|
||||
|
||||
function handlePackInstallClick() {
|
||||
if (!props.group.packId) return
|
||||
if (!comfyManagerStore.isPackInstalled(props.group.packId)) {
|
||||
void installAllPacks()
|
||||
}
|
||||
}
|
||||
|
||||
const expanded = ref(false)
|
||||
|
||||
function toggleExpand() {
|
||||
expanded.value = !expanded.value
|
||||
}
|
||||
|
||||
function getKey(nodeType: MissingNodeType): string {
|
||||
if (typeof nodeType === 'string') return nodeType
|
||||
return nodeType.nodeId != null ? String(nodeType.nodeId) : nodeType.type
|
||||
}
|
||||
|
||||
function getLabel(nodeType: MissingNodeType): string {
|
||||
return typeof nodeType === 'string' ? nodeType : nodeType.type
|
||||
}
|
||||
|
||||
function handleLocateNode(nodeType: MissingNodeType) {
|
||||
if (typeof nodeType === 'string') return
|
||||
if (nodeType.nodeId != null) {
|
||||
emit('locateNode', String(nodeType.nodeId))
|
||||
}
|
||||
}
|
||||
</script>
|
||||
150
src/components/rightSidePanel/errors/SwapNodeGroupRow.vue
Normal file
150
src/components/rightSidePanel/errors/SwapNodeGroupRow.vue
Normal file
@@ -0,0 +1,150 @@
|
||||
<template>
|
||||
<div class="flex flex-col w-full mb-4">
|
||||
<!-- Type header row: type name + chevron -->
|
||||
<div class="flex h-8 items-center w-full">
|
||||
<p
|
||||
class="flex-1 min-w-0 text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap text-foreground"
|
||||
>
|
||||
{{ `${group.type} (${group.nodeTypes.length})` }}
|
||||
</p>
|
||||
|
||||
<Button
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
:class="
|
||||
cn(
|
||||
'size-8 shrink-0 transition-transform duration-200 hover:bg-transparent',
|
||||
{ 'rotate-180': expanded }
|
||||
)
|
||||
"
|
||||
:aria-label="
|
||||
expanded
|
||||
? t('rightSidePanel.missingNodePacks.collapse', 'Collapse')
|
||||
: t('rightSidePanel.missingNodePacks.expand', 'Expand')
|
||||
"
|
||||
@click="toggleExpand"
|
||||
>
|
||||
<i
|
||||
class="icon-[lucide--chevron-down] size-4 text-muted-foreground group-hover:text-base-foreground"
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- Sub-labels: individual node instances, each with their own Locate button -->
|
||||
<TransitionCollapse>
|
||||
<div
|
||||
v-if="expanded"
|
||||
class="flex flex-col gap-0.5 pl-2 mb-2 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
v-for="nodeType in group.nodeTypes"
|
||||
:key="getKey(nodeType)"
|
||||
class="flex h-7 items-center"
|
||||
>
|
||||
<span
|
||||
v-if="
|
||||
showNodeIdBadge &&
|
||||
typeof nodeType !== 'string' &&
|
||||
nodeType.nodeId != null
|
||||
"
|
||||
class="shrink-0 rounded-md bg-secondary-background-selected px-2 py-0.5 text-xs font-mono text-muted-foreground font-bold mr-1"
|
||||
>
|
||||
#{{ nodeType.nodeId }}
|
||||
</span>
|
||||
<p class="flex-1 min-w-0 text-xs text-muted-foreground truncate">
|
||||
{{ getLabel(nodeType) }}
|
||||
</p>
|
||||
<Button
|
||||
v-if="typeof nodeType !== 'string' && nodeType.nodeId != null"
|
||||
variant="textonly"
|
||||
size="icon-sm"
|
||||
class="size-6 text-muted-foreground hover:text-base-foreground shrink-0 mr-1"
|
||||
:aria-label="t('rightSidePanel.locateNode', 'Locate Node')"
|
||||
@click="handleLocateNode(nodeType)"
|
||||
>
|
||||
<i class="icon-[lucide--locate] size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TransitionCollapse>
|
||||
|
||||
<!-- Description rows: what it is replaced by -->
|
||||
<div class="flex flex-col text-[13px] mb-2 mt-1 px-1 gap-0.5">
|
||||
<span class="text-muted-foreground">{{
|
||||
t('nodeReplacement.willBeReplacedBy', 'This node will be replaced by:')
|
||||
}}</span>
|
||||
<span class="font-bold text-foreground">{{
|
||||
group.newNodeId ?? t('nodeReplacement.unknownNode', 'Unknown')
|
||||
}}</span>
|
||||
</div>
|
||||
|
||||
<!-- Replace Action Button -->
|
||||
<div class="flex items-start w-full pt-1 pb-1">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="md"
|
||||
class="flex flex-1 w-full"
|
||||
@click="handleReplaceNode"
|
||||
>
|
||||
<i class="icon-[lucide--repeat] size-4 text-foreground shrink-0 mr-1" />
|
||||
<span class="text-sm text-foreground truncate min-w-0">
|
||||
{{ t('nodeReplacement.replaceNode', 'Replace Node') }}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import TransitionCollapse from '@/components/rightSidePanel/layout/TransitionCollapse.vue'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import type { SwapNodeGroup } from './useErrorGroups'
|
||||
import { useNodeReplacement } from '@/platform/nodeReplacement/useNodeReplacement'
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
|
||||
const props = defineProps<{
|
||||
group: SwapNodeGroup
|
||||
showNodeIdBadge: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'locate-node': [nodeId: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const { replaceNodesInPlace } = useNodeReplacement()
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
|
||||
const expanded = ref(false)
|
||||
|
||||
function toggleExpand() {
|
||||
expanded.value = !expanded.value
|
||||
}
|
||||
|
||||
function getKey(nodeType: MissingNodeType): string {
|
||||
if (typeof nodeType === 'string') return nodeType
|
||||
return nodeType.nodeId != null ? String(nodeType.nodeId) : nodeType.type
|
||||
}
|
||||
|
||||
function getLabel(nodeType: MissingNodeType): string {
|
||||
return typeof nodeType === 'string' ? nodeType : nodeType.type
|
||||
}
|
||||
|
||||
function handleLocateNode(nodeType: MissingNodeType) {
|
||||
if (typeof nodeType === 'string') return
|
||||
if (nodeType.nodeId != null) {
|
||||
emit('locate-node', String(nodeType.nodeId))
|
||||
}
|
||||
}
|
||||
|
||||
function handleReplaceNode() {
|
||||
const replaced = replaceNodesInPlace(props.group.nodeTypes)
|
||||
if (replaced.length > 0) {
|
||||
executionErrorStore.removeMissingNodesByType([props.group.type])
|
||||
}
|
||||
}
|
||||
</script>
|
||||
38
src/components/rightSidePanel/errors/SwapNodesCard.vue
Normal file
38
src/components/rightSidePanel/errors/SwapNodesCard.vue
Normal file
@@ -0,0 +1,38 @@
|
||||
<template>
|
||||
<div class="px-4 pb-2 mt-2">
|
||||
<!-- Sub-label: guidance message shown above all swap groups -->
|
||||
<p class="m-0 pb-5 text-sm text-muted-foreground leading-relaxed">
|
||||
{{
|
||||
t(
|
||||
'nodeReplacement.swapNodesGuide',
|
||||
'The following nodes can be automatically replaced with compatible alternatives.'
|
||||
)
|
||||
}}
|
||||
</p>
|
||||
<!-- Group Rows -->
|
||||
<SwapNodeGroupRow
|
||||
v-for="group in swapNodeGroups"
|
||||
:key="group.type"
|
||||
:group="group"
|
||||
:show-node-id-badge="showNodeIdBadge"
|
||||
@locate-node="emit('locate-node', $event)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import type { SwapNodeGroup } from './useErrorGroups'
|
||||
import SwapNodeGroupRow from './SwapNodeGroupRow.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { swapNodeGroups, showNodeIdBadge } = defineProps<{
|
||||
swapNodeGroups: SwapNodeGroup[]
|
||||
showNodeIdBadge: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'locate-node': [nodeId: string]
|
||||
}>()
|
||||
</script>
|
||||
@@ -18,7 +18,8 @@ vi.mock('@/scripts/app', () => ({
|
||||
vi.mock('@/utils/graphTraversalUtil', () => ({
|
||||
getNodeByExecutionId: vi.fn(),
|
||||
getRootParentNode: vi.fn(() => null),
|
||||
forEachNode: vi.fn()
|
||||
forEachNode: vi.fn(),
|
||||
mapAllNodes: vi.fn(() => [])
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/useCopyToClipboard', () => ({
|
||||
|
||||
@@ -27,6 +27,11 @@
|
||||
:key="group.title"
|
||||
:collapse="collapseState[group.title] ?? false"
|
||||
class="border-b border-interface-stroke"
|
||||
:size="
|
||||
group.type === 'missing_node' || group.type === 'swap_nodes'
|
||||
? 'lg'
|
||||
: 'default'
|
||||
"
|
||||
@update:collapse="collapseState[group.title] = $event"
|
||||
>
|
||||
<template #label>
|
||||
@@ -36,20 +41,78 @@
|
||||
class="icon-[lucide--octagon-alert] size-4 text-destructive-background-hover shrink-0"
|
||||
/>
|
||||
<span class="text-destructive-background-hover truncate">
|
||||
{{ group.title }}
|
||||
{{
|
||||
group.type === 'missing_node'
|
||||
? `${group.title} (${missingPackGroups.length})`
|
||||
: group.type === 'swap_nodes'
|
||||
? `${group.title} (${swapNodeGroups.length})`
|
||||
: group.title
|
||||
}}
|
||||
</span>
|
||||
<span
|
||||
v-if="group.cards.length > 1"
|
||||
v-if="group.type === 'execution' && group.cards.length > 1"
|
||||
class="text-destructive-background-hover"
|
||||
>
|
||||
({{ group.cards.length }})
|
||||
</span>
|
||||
</span>
|
||||
<Button
|
||||
v-if="
|
||||
group.type === 'missing_node' &&
|
||||
missingNodePacks.length > 0 &&
|
||||
shouldShowInstallButton
|
||||
"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="shrink-0 mr-2 h-8 rounded-lg text-sm"
|
||||
:disabled="isInstallingAll"
|
||||
@click.stop="installAll"
|
||||
>
|
||||
<DotSpinner v-if="isInstallingAll" duration="1s" :size="12" />
|
||||
{{
|
||||
isInstallingAll
|
||||
? t('rightSidePanel.missingNodePacks.installing')
|
||||
: t('rightSidePanel.missingNodePacks.installAll')
|
||||
}}
|
||||
</Button>
|
||||
<Button
|
||||
v-else-if="group.type === 'swap_nodes'"
|
||||
v-tooltip.top="
|
||||
t(
|
||||
'nodeReplacement.replaceAllWarning',
|
||||
'Replaces all available nodes in this group.'
|
||||
)
|
||||
"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="shrink-0 mr-2 h-8 rounded-lg text-sm"
|
||||
@click.stop="handleReplaceAll()"
|
||||
>
|
||||
{{ t('nodeReplacement.replaceAll', 'Replace All') }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Cards in Group (default slot) -->
|
||||
<div class="px-4 space-y-3">
|
||||
<!-- Missing Node Packs -->
|
||||
<MissingNodeCard
|
||||
v-if="group.type === 'missing_node'"
|
||||
:show-info-button="shouldShowManagerButtons"
|
||||
:show-node-id-badge="showNodeIdBadge"
|
||||
:missing-pack-groups="missingPackGroups"
|
||||
@locate-node="handleLocateMissingNode"
|
||||
@open-manager-info="handleOpenManagerInfo"
|
||||
/>
|
||||
|
||||
<!-- Swap Nodes -->
|
||||
<SwapNodesCard
|
||||
v-else-if="group.type === 'swap_nodes'"
|
||||
:swap-node-groups="swapNodeGroups"
|
||||
:show-node-id-badge="showNodeIdBadge"
|
||||
@locate-node="handleLocateMissingNode"
|
||||
/>
|
||||
|
||||
<!-- Execution Errors -->
|
||||
<div v-else-if="group.type === 'execution'" class="px-4 space-y-3">
|
||||
<ErrorNodeCard
|
||||
v-for="card in group.cards"
|
||||
:key="card.id"
|
||||
@@ -108,13 +171,22 @@ import { useExternalLink } from '@/composables/useExternalLink'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { useTelemetry } from '@/platform/telemetry'
|
||||
import { useRightSidePanelStore } from '@/stores/workspace/rightSidePanelStore'
|
||||
import { useManagerState } from '@/workbench/extensions/manager/composables/useManagerState'
|
||||
import { ManagerTab } from '@/workbench/extensions/manager/types/comfyManagerTypes'
|
||||
import { NodeBadgeMode } from '@/types/nodeSource'
|
||||
|
||||
import PropertiesAccordionItem from '../layout/PropertiesAccordionItem.vue'
|
||||
import FormSearchInput from '@/renderer/extensions/vueNodes/widgets/components/form/FormSearchInput.vue'
|
||||
import ErrorNodeCard from './ErrorNodeCard.vue'
|
||||
import MissingNodeCard from './MissingNodeCard.vue'
|
||||
import SwapNodesCard from './SwapNodesCard.vue'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import DotSpinner from '@/components/common/DotSpinner.vue'
|
||||
import { usePackInstall } from '@/workbench/extensions/manager/composables/nodePack/usePackInstall'
|
||||
import { useMissingNodes } from '@/workbench/extensions/manager/composables/nodePack/useMissingNodes'
|
||||
import { useErrorGroups } from './useErrorGroups'
|
||||
import { useNodeReplacement } from '@/platform/nodeReplacement/useNodeReplacement'
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { copyToClipboard } = useCopyToClipboard()
|
||||
@@ -122,6 +194,13 @@ const { focusNode, enterSubgraph } = useFocusNode()
|
||||
const { staticUrls } = useExternalLink()
|
||||
const settingStore = useSettingStore()
|
||||
const rightSidePanelStore = useRightSidePanelStore()
|
||||
const { shouldShowManagerButtons, shouldShowInstallButton, openManager } =
|
||||
useManagerState()
|
||||
const { missingNodePacks } = useMissingNodes()
|
||||
const { isInstalling: isInstallingAll, installAllPacks: installAll } =
|
||||
usePackInstall(() => missingNodePacks.value)
|
||||
const { replaceNodesInPlace } = useNodeReplacement()
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
@@ -136,7 +215,10 @@ const {
|
||||
filteredGroups,
|
||||
collapseState,
|
||||
isSingleNodeSelected,
|
||||
errorNodeCache
|
||||
errorNodeCache,
|
||||
missingNodeCache,
|
||||
missingPackGroups,
|
||||
swapNodeGroups
|
||||
} = useErrorGroups(searchQuery, t)
|
||||
|
||||
/**
|
||||
@@ -151,11 +233,13 @@ watch(
|
||||
if (!graphNodeId) return
|
||||
const prefix = `${graphNodeId}:`
|
||||
for (const group of allErrorGroups.value) {
|
||||
const hasMatch = group.cards.some(
|
||||
(card) =>
|
||||
card.graphNodeId === graphNodeId ||
|
||||
(card.nodeId?.startsWith(prefix) ?? false)
|
||||
)
|
||||
const hasMatch =
|
||||
group.type === 'execution' &&
|
||||
group.cards.some(
|
||||
(card) =>
|
||||
card.graphNodeId === graphNodeId ||
|
||||
(card.nodeId?.startsWith(prefix) ?? false)
|
||||
)
|
||||
collapseState[group.title] = !hasMatch
|
||||
}
|
||||
rightSidePanelStore.focusedErrorNodeId = null
|
||||
@@ -167,6 +251,27 @@ function handleLocateNode(nodeId: string) {
|
||||
focusNode(nodeId, errorNodeCache.value)
|
||||
}
|
||||
|
||||
function handleLocateMissingNode(nodeId: string) {
|
||||
focusNode(nodeId, missingNodeCache.value)
|
||||
}
|
||||
|
||||
function handleOpenManagerInfo(packId: string) {
|
||||
const isKnownToRegistry = missingNodePacks.value.some((p) => p.id === packId)
|
||||
if (isKnownToRegistry) {
|
||||
openManager({ initialTab: ManagerTab.Missing, initialPackId: packId })
|
||||
} else {
|
||||
openManager({ initialTab: ManagerTab.All, initialPackId: packId })
|
||||
}
|
||||
}
|
||||
|
||||
function handleReplaceAll() {
|
||||
const allNodeTypes = swapNodeGroups.value.flatMap((g) => g.nodeTypes)
|
||||
const replaced = replaceNodesInPlace(allNodeTypes)
|
||||
if (replaced.length > 0) {
|
||||
executionErrorStore.removeMissingNodesByType(replaced)
|
||||
}
|
||||
}
|
||||
|
||||
function handleEnterSubgraph(nodeId: string) {
|
||||
enterSubgraph(nodeId, errorNodeCache.value)
|
||||
}
|
||||
|
||||
@@ -14,8 +14,12 @@ export interface ErrorCardData {
|
||||
errors: ErrorItem[]
|
||||
}
|
||||
|
||||
export interface ErrorGroup {
|
||||
title: string
|
||||
cards: ErrorCardData[]
|
||||
priority: number
|
||||
}
|
||||
export type ErrorGroup =
|
||||
| {
|
||||
type: 'execution'
|
||||
title: string
|
||||
cards: ErrorCardData[]
|
||||
priority: number
|
||||
}
|
||||
| { type: 'missing_node'; title: string; priority: number }
|
||||
| { type: 'swap_nodes'; title: string; priority: number }
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { computed, reactive } from 'vue'
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
import Fuse from 'fuse.js'
|
||||
import type { IFuseOptions } from 'fuse.js'
|
||||
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
import { useComfyRegistryStore } from '@/stores/comfyRegistryStore'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
|
||||
import { app } from '@/scripts/app'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import { SubgraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
@@ -20,6 +20,7 @@ import { resolveNodeDisplayName } from '@/utils/nodeTitleUtil'
|
||||
import { isLGraphNode } from '@/utils/litegraphUtil'
|
||||
import { isGroupNode } from '@/utils/executableGroupNodeDto'
|
||||
import { st } from '@/i18n'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import type { ErrorCardData, ErrorGroup, ErrorItem } from './types'
|
||||
import type { NodeExecutionId } from '@/types/nodeIdentification'
|
||||
import { isNodeExecutionId } from '@/types/nodeIdentification'
|
||||
@@ -32,7 +33,23 @@ const KNOWN_PROMPT_ERROR_TYPES = new Set([
|
||||
'server_error'
|
||||
])
|
||||
|
||||
/** Sentinel: distinguishes "fetch in-flight" from "fetch done, pack not found (null)". */
|
||||
const RESOLVING = '__RESOLVING__'
|
||||
|
||||
export interface MissingPackGroup {
|
||||
packId: string | null
|
||||
nodeTypes: MissingNodeType[]
|
||||
isResolving: boolean
|
||||
}
|
||||
|
||||
export interface SwapNodeGroup {
|
||||
type: string
|
||||
newNodeId: string | undefined
|
||||
nodeTypes: MissingNodeType[]
|
||||
}
|
||||
|
||||
interface GroupEntry {
|
||||
type: 'execution'
|
||||
priority: number
|
||||
cards: Map<string, ErrorCardData>
|
||||
}
|
||||
@@ -76,7 +93,7 @@ function getOrCreateGroup(
|
||||
): Map<string, ErrorCardData> {
|
||||
let entry = groupsMap.get(title)
|
||||
if (!entry) {
|
||||
entry = { priority, cards: new Map() }
|
||||
entry = { type: 'execution', priority, cards: new Map() }
|
||||
groupsMap.set(title, entry)
|
||||
}
|
||||
return entry.cards
|
||||
@@ -137,6 +154,7 @@ function addCardErrorToGroup(
|
||||
function toSortedGroups(groupsMap: Map<string, GroupEntry>): ErrorGroup[] {
|
||||
return Array.from(groupsMap.entries())
|
||||
.map(([title, groupData]) => ({
|
||||
type: 'execution' as const,
|
||||
title,
|
||||
cards: Array.from(groupData.cards.values()),
|
||||
priority: groupData.priority
|
||||
@@ -153,6 +171,7 @@ function searchErrorGroups(groups: ErrorGroup[], query: string) {
|
||||
const searchableList: ErrorSearchItem[] = []
|
||||
for (let gi = 0; gi < groups.length; gi++) {
|
||||
const group = groups[gi]
|
||||
if (group.type !== 'execution') continue
|
||||
for (let ci = 0; ci < group.cards.length; ci++) {
|
||||
const card = group.cards[ci]
|
||||
searchableList.push({
|
||||
@@ -160,8 +179,12 @@ function searchErrorGroups(groups: ErrorGroup[], query: string) {
|
||||
cardIndex: ci,
|
||||
searchableNodeId: card.nodeId ?? '',
|
||||
searchableNodeTitle: card.nodeTitle ?? '',
|
||||
searchableMessage: card.errors.map((e) => e.message).join(' '),
|
||||
searchableDetails: card.errors.map((e) => e.details ?? '').join(' ')
|
||||
searchableMessage: card.errors
|
||||
.map((e: ErrorItem) => e.message)
|
||||
.join(' '),
|
||||
searchableDetails: card.errors
|
||||
.map((e: ErrorItem) => e.details ?? '')
|
||||
.join(' ')
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -184,11 +207,16 @@ function searchErrorGroups(groups: ErrorGroup[], query: string) {
|
||||
)
|
||||
|
||||
return groups
|
||||
.map((group, gi) => ({
|
||||
...group,
|
||||
cards: group.cards.filter((_, ci) => matchedCardKeys.has(`${gi}:${ci}`))
|
||||
}))
|
||||
.filter((group) => group.cards.length > 0)
|
||||
.map((group, gi) => {
|
||||
if (group.type !== 'execution') return group
|
||||
return {
|
||||
...group,
|
||||
cards: group.cards.filter((_: ErrorCardData, ci: number) =>
|
||||
matchedCardKeys.has(`${gi}:${ci}`)
|
||||
)
|
||||
}
|
||||
})
|
||||
.filter((group) => group.type !== 'execution' || group.cards.length > 0)
|
||||
}
|
||||
|
||||
export function useErrorGroups(
|
||||
@@ -197,6 +225,7 @@ export function useErrorGroups(
|
||||
) {
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
const canvasStore = useCanvasStore()
|
||||
const { inferPackFromNodeName } = useComfyRegistryStore()
|
||||
const collapseState = reactive<Record<string, boolean>>({})
|
||||
|
||||
const selectedNodeInfo = computed(() => {
|
||||
@@ -237,6 +266,19 @@ export function useErrorGroups(
|
||||
return map
|
||||
})
|
||||
|
||||
const missingNodeCache = computed(() => {
|
||||
const map = new Map<string, LGraphNode>()
|
||||
const nodeTypes = executionErrorStore.missingNodesError?.nodeTypes ?? []
|
||||
for (const nodeType of nodeTypes) {
|
||||
if (typeof nodeType === 'string') continue
|
||||
if (nodeType.nodeId == null) continue
|
||||
const nodeId = String(nodeType.nodeId)
|
||||
const node = getNodeByExecutionId(app.rootGraph, nodeId)
|
||||
if (node) map.set(nodeId, node)
|
||||
}
|
||||
return map
|
||||
})
|
||||
|
||||
function isErrorInSelection(executionNodeId: string): boolean {
|
||||
const nodeIds = selectedNodeInfo.value.nodeIds
|
||||
if (!nodeIds) return true
|
||||
@@ -343,6 +385,173 @@ export function useErrorGroups(
|
||||
)
|
||||
}
|
||||
|
||||
// Async pack-ID resolution for missing node types that lack a cnrId
|
||||
const asyncResolvedIds = ref<Map<string, string | null>>(new Map())
|
||||
|
||||
const pendingTypes = computed(() =>
|
||||
(executionErrorStore.missingNodesError?.nodeTypes ?? []).filter(
|
||||
(n): n is Exclude<MissingNodeType, string> =>
|
||||
typeof n !== 'string' && !n.cnrId
|
||||
)
|
||||
)
|
||||
|
||||
watch(
|
||||
pendingTypes,
|
||||
async (pending, _, onCleanup) => {
|
||||
const toResolve = pending.filter(
|
||||
(n) => asyncResolvedIds.value.get(n.type) === undefined
|
||||
)
|
||||
if (!toResolve.length) return
|
||||
|
||||
const resolvingTypes = toResolve.map((n) => n.type)
|
||||
let cancelled = false
|
||||
onCleanup(() => {
|
||||
cancelled = true
|
||||
const next = new Map(asyncResolvedIds.value)
|
||||
for (const type of resolvingTypes) {
|
||||
if (next.get(type) === RESOLVING) next.delete(type)
|
||||
}
|
||||
asyncResolvedIds.value = next
|
||||
})
|
||||
|
||||
const updated = new Map(asyncResolvedIds.value)
|
||||
for (const type of resolvingTypes) updated.set(type, RESOLVING)
|
||||
asyncResolvedIds.value = updated
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
toResolve.map(async (n) => ({
|
||||
type: n.type,
|
||||
packId: (await inferPackFromNodeName.call(n.type))?.id ?? null
|
||||
}))
|
||||
)
|
||||
if (cancelled) return
|
||||
|
||||
const final = new Map(asyncResolvedIds.value)
|
||||
for (const r of results) {
|
||||
if (r.status === 'fulfilled') {
|
||||
final.set(r.value.type, r.value.packId)
|
||||
}
|
||||
}
|
||||
// Clear any remaining RESOLVING markers for failed lookups
|
||||
for (const type of resolvingTypes) {
|
||||
if (final.get(type) === RESOLVING) final.set(type, null)
|
||||
}
|
||||
asyncResolvedIds.value = final
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
const missingPackGroups = computed<MissingPackGroup[]>(() => {
|
||||
const nodeTypes = executionErrorStore.missingNodesError?.nodeTypes ?? []
|
||||
const map = new Map<
|
||||
string | null,
|
||||
{ nodeTypes: MissingNodeType[]; isResolving: boolean }
|
||||
>()
|
||||
const resolvingKeys = new Set<string | null>()
|
||||
|
||||
for (const nodeType of nodeTypes) {
|
||||
if (typeof nodeType !== 'string' && nodeType.isReplaceable) continue
|
||||
|
||||
let packId: string | null
|
||||
|
||||
if (typeof nodeType === 'string') {
|
||||
packId = null
|
||||
} else if (nodeType.cnrId) {
|
||||
packId = nodeType.cnrId
|
||||
} else {
|
||||
const resolved = asyncResolvedIds.value.get(nodeType.type)
|
||||
if (resolved === undefined || resolved === RESOLVING) {
|
||||
packId = null
|
||||
resolvingKeys.add(null)
|
||||
} else {
|
||||
packId = resolved
|
||||
}
|
||||
}
|
||||
|
||||
const existing = map.get(packId)
|
||||
if (existing) {
|
||||
existing.nodeTypes.push(nodeType)
|
||||
} else {
|
||||
map.set(packId, { nodeTypes: [nodeType], isResolving: false })
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of resolvingKeys) {
|
||||
const group = map.get(key)
|
||||
if (group) group.isResolving = true
|
||||
}
|
||||
|
||||
return Array.from(map.entries())
|
||||
.sort(([packIdA], [packIdB]) => {
|
||||
// null (Unknown Pack) always goes last
|
||||
if (packIdA === null) return 1
|
||||
if (packIdB === null) return -1
|
||||
return packIdA.localeCompare(packIdB)
|
||||
})
|
||||
.map(([packId, { nodeTypes, isResolving }]) => ({
|
||||
packId,
|
||||
nodeTypes: [...nodeTypes].sort((a, b) => {
|
||||
const typeA = typeof a === 'string' ? a : a.type
|
||||
const typeB = typeof b === 'string' ? b : b.type
|
||||
const typeCmp = typeA.localeCompare(typeB)
|
||||
if (typeCmp !== 0) return typeCmp
|
||||
const idA = typeof a === 'string' ? '' : String(a.nodeId ?? '')
|
||||
const idB = typeof b === 'string' ? '' : String(b.nodeId ?? '')
|
||||
return idA.localeCompare(idB, undefined, { numeric: true })
|
||||
}),
|
||||
isResolving
|
||||
}))
|
||||
})
|
||||
|
||||
const swapNodeGroups = computed<SwapNodeGroup[]>(() => {
|
||||
const nodeTypes = executionErrorStore.missingNodesError?.nodeTypes ?? []
|
||||
const map = new Map<string, SwapNodeGroup>()
|
||||
|
||||
for (const nodeType of nodeTypes) {
|
||||
if (typeof nodeType === 'string' || !nodeType.isReplaceable) continue
|
||||
|
||||
const typeName = nodeType.type
|
||||
const existing = map.get(typeName)
|
||||
if (existing) {
|
||||
existing.nodeTypes.push(nodeType)
|
||||
} else {
|
||||
map.set(typeName, {
|
||||
type: typeName,
|
||||
newNodeId: nodeType.replacement?.new_node_id,
|
||||
nodeTypes: [nodeType]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(map.values()).sort((a, b) => a.type.localeCompare(b.type))
|
||||
})
|
||||
|
||||
/** Builds an ErrorGroup from missingNodesError. Returns [] when none present. */
|
||||
function buildMissingNodeGroups(): ErrorGroup[] {
|
||||
const error = executionErrorStore.missingNodesError
|
||||
if (!error) return []
|
||||
|
||||
const groups: ErrorGroup[] = []
|
||||
|
||||
if (swapNodeGroups.value.length > 0) {
|
||||
groups.push({
|
||||
type: 'swap_nodes' as const,
|
||||
title: st('nodeReplacement.swapNodesTitle', 'Swap Nodes'),
|
||||
priority: 0
|
||||
})
|
||||
}
|
||||
|
||||
if (missingPackGroups.value.length > 0) {
|
||||
groups.push({
|
||||
type: 'missing_node' as const,
|
||||
title: error.message,
|
||||
priority: 1
|
||||
})
|
||||
}
|
||||
|
||||
return groups.sort((a, b) => a.priority - b.priority)
|
||||
}
|
||||
|
||||
const allErrorGroups = computed<ErrorGroup[]>(() => {
|
||||
const groupsMap = new Map<string, GroupEntry>()
|
||||
|
||||
@@ -350,7 +559,7 @@ export function useErrorGroups(
|
||||
processNodeErrors(groupsMap)
|
||||
processExecutionError(groupsMap)
|
||||
|
||||
return toSortedGroups(groupsMap)
|
||||
return [...buildMissingNodeGroups(), ...toSortedGroups(groupsMap)]
|
||||
})
|
||||
|
||||
const tabErrorGroups = computed<ErrorGroup[]>(() => {
|
||||
@@ -360,9 +569,11 @@ export function useErrorGroups(
|
||||
processNodeErrors(groupsMap, true)
|
||||
processExecutionError(groupsMap, true)
|
||||
|
||||
return isSingleNodeSelected.value
|
||||
const executionGroups = isSingleNodeSelected.value
|
||||
? toSortedGroups(regroupByErrorMessage(groupsMap))
|
||||
: toSortedGroups(groupsMap)
|
||||
|
||||
return [...buildMissingNodeGroups(), ...executionGroups]
|
||||
})
|
||||
|
||||
const filteredGroups = computed<ErrorGroup[]>(() => {
|
||||
@@ -373,10 +584,15 @@ export function useErrorGroups(
|
||||
const groupedErrorMessages = computed<string[]>(() => {
|
||||
const messages = new Set<string>()
|
||||
for (const group of allErrorGroups.value) {
|
||||
for (const card of group.cards) {
|
||||
for (const err of card.errors) {
|
||||
messages.add(err.message)
|
||||
if (group.type === 'execution') {
|
||||
for (const card of group.cards) {
|
||||
for (const err of card.errors) {
|
||||
messages.add(err.message)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Groups without cards (e.g. missing_node) surface their title as the message.
|
||||
messages.add(group.title)
|
||||
}
|
||||
}
|
||||
return Array.from(messages)
|
||||
@@ -389,6 +605,9 @@ export function useErrorGroups(
|
||||
collapseState,
|
||||
isSingleNodeSelected,
|
||||
errorNodeCache,
|
||||
groupedErrorMessages
|
||||
missingNodeCache,
|
||||
groupedErrorMessages,
|
||||
missingPackGroups,
|
||||
swapNodeGroups
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,14 @@ const {
|
||||
label,
|
||||
enableEmptyState,
|
||||
tooltip,
|
||||
size = 'default',
|
||||
class: className
|
||||
} = defineProps<{
|
||||
disabled?: boolean
|
||||
label?: string
|
||||
enableEmptyState?: boolean
|
||||
tooltip?: string
|
||||
size?: 'default' | 'lg'
|
||||
class?: string
|
||||
}>()
|
||||
|
||||
@@ -39,7 +41,8 @@ const tooltipConfig = computed(() => {
|
||||
type="button"
|
||||
:class="
|
||||
cn(
|
||||
'group min-h-12 bg-transparent border-0 outline-0 ring-0 w-full text-left flex items-center justify-between pl-4 pr-3',
|
||||
'group bg-transparent border-0 outline-0 ring-0 w-full text-left flex items-center justify-between pl-4 pr-3',
|
||||
size === 'lg' ? 'min-h-16' : 'min-h-12',
|
||||
!disabled && 'cursor-pointer'
|
||||
)
|
||||
"
|
||||
|
||||
@@ -131,6 +131,12 @@ const nodeHasError = computed(() => {
|
||||
return hasDirectError.value || hasContainerInternalError.value
|
||||
})
|
||||
|
||||
const showSeeError = computed(
|
||||
() =>
|
||||
nodeHasError.value &&
|
||||
useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')
|
||||
)
|
||||
|
||||
const parentGroup = computed<LGraphGroup | null>(() => {
|
||||
if (!targetNode.value || !getNodeParentGroup) return null
|
||||
return getNodeParentGroup(targetNode.value)
|
||||
@@ -194,6 +200,7 @@ defineExpose({
|
||||
:enable-empty-state
|
||||
:disabled="isEmpty"
|
||||
:tooltip
|
||||
:size="showSeeError ? 'lg' : 'default'"
|
||||
>
|
||||
<template #label>
|
||||
<div class="flex flex-wrap items-center gap-2 flex-1 min-w-0">
|
||||
@@ -223,13 +230,10 @@ defineExpose({
|
||||
</span>
|
||||
</span>
|
||||
<Button
|
||||
v-if="
|
||||
nodeHasError &&
|
||||
useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')
|
||||
"
|
||||
v-if="showSeeError"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
class="shrink-0 rounded-lg text-sm"
|
||||
class="shrink-0 rounded-lg text-sm h-8"
|
||||
@click.stop="navigateToErrorTab"
|
||||
>
|
||||
{{ t('rightSidePanel.seeError') }}
|
||||
|
||||
@@ -106,4 +106,42 @@ describe('AssetsSidebarListView', () => {
|
||||
expect(assetListItem?.props('previewUrl')).toBe('')
|
||||
expect(assetListItem?.props('isVideoPreview')).toBe(false)
|
||||
})
|
||||
|
||||
it('emits preview-asset when item preview is clicked', async () => {
|
||||
const imageAsset = {
|
||||
...buildAsset('image-asset', 'image.png'),
|
||||
preview_url: '/api/view/image.png',
|
||||
user_metadata: {}
|
||||
} satisfies AssetItem
|
||||
|
||||
const wrapper = mountListView([buildOutputItem(imageAsset)])
|
||||
const listItems = wrapper.findAllComponents({ name: 'AssetsListItem' })
|
||||
const assetListItem = listItems.at(-1)
|
||||
|
||||
expect(assetListItem).toBeDefined()
|
||||
|
||||
assetListItem!.vm.$emit('preview-click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('preview-asset')).toEqual([[imageAsset]])
|
||||
})
|
||||
|
||||
it('emits preview-asset when item is double-clicked', async () => {
|
||||
const imageAsset = {
|
||||
...buildAsset('image-asset-dbl', 'image.png'),
|
||||
preview_url: '/api/view/image.png',
|
||||
user_metadata: {}
|
||||
} satisfies AssetItem
|
||||
|
||||
const wrapper = mountListView([buildOutputItem(imageAsset)])
|
||||
const listItems = wrapper.findAllComponents({ name: 'AssetsListItem' })
|
||||
const assetListItem = listItems.at(-1)
|
||||
|
||||
expect(assetListItem).toBeDefined()
|
||||
|
||||
await assetListItem!.trigger('dblclick')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.emitted('preview-asset')).toEqual([[imageAsset]])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -56,6 +56,8 @@
|
||||
@mouseleave="onAssetLeave(item.asset.id)"
|
||||
@contextmenu.prevent.stop="emit('context-menu', $event, item.asset)"
|
||||
@click.stop="emit('select-asset', item.asset, selectableAssets)"
|
||||
@dblclick.stop="emit('preview-asset', item.asset)"
|
||||
@preview-click="emit('preview-asset', item.asset)"
|
||||
@stack-toggle="void toggleStack(item.asset)"
|
||||
>
|
||||
<template v-if="hoveredAssetId === item.asset.id" #actions>
|
||||
@@ -116,6 +118,7 @@ const assetsStore = useAssetsStore()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'select-asset', asset: AssetItem, assets?: AssetItem[]): void
|
||||
(e: 'preview-asset', asset: AssetItem): void
|
||||
(e: 'context-menu', event: MouseEvent, asset: AssetItem): void
|
||||
(e: 'approach-end'): void
|
||||
}>()
|
||||
|
||||
@@ -95,6 +95,7 @@
|
||||
:toggle-stack="toggleListViewStack"
|
||||
:asset-type="activeTab"
|
||||
@select-asset="handleAssetSelect"
|
||||
@preview-asset="handleZoomClick"
|
||||
@context-menu="handleAssetContextMenu"
|
||||
@approach-end="handleApproachEnd"
|
||||
/>
|
||||
@@ -216,10 +217,6 @@ import {
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import NoResultsPlaceholder from '@/components/common/NoResultsPlaceholder.vue'
|
||||
// Lazy-loaded to avoid pulling THREE.js into the main bundle
|
||||
const Load3dViewerContent = defineAsyncComponent(
|
||||
() => import('@/components/load3d/Load3dViewerContent.vue')
|
||||
)
|
||||
import AssetsSidebarGridView from '@/components/sidebar/tabs/AssetsSidebarGridView.vue'
|
||||
import AssetsSidebarListView from '@/components/sidebar/tabs/AssetsSidebarListView.vue'
|
||||
import SidebarTabTemplate from '@/components/sidebar/tabs/SidebarTabTemplate.vue'
|
||||
@@ -251,6 +248,10 @@ import {
|
||||
} from '@/utils/formatUtil'
|
||||
import { cn } from '@/utils/tailwindUtil'
|
||||
|
||||
const Load3dViewerContent = defineAsyncComponent(
|
||||
() => import('@/components/load3d/Load3dViewerContent.vue')
|
||||
)
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const emit = defineEmits<{ assetSelected: [asset: AssetItem] }>()
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, defineAsyncComponent, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import JobFilterActions from '@/components/queue/job/JobFilterActions.vue'
|
||||
@@ -86,11 +86,17 @@ import SidebarTabTemplate from '@/components/sidebar/tabs/SidebarTabTemplate.vue
|
||||
import ResultGallery from '@/components/sidebar/tabs/queue/ResultGallery.vue'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import { useCommandStore } from '@/stores/commandStore'
|
||||
import { useDialogStore } from '@/stores/dialogStore'
|
||||
import { useExecutionStore } from '@/stores/executionStore'
|
||||
import { useQueueStore } from '@/stores/queueStore'
|
||||
|
||||
const Load3dViewerContent = defineAsyncComponent(
|
||||
() => import('@/components/load3d/Load3dViewerContent.vue')
|
||||
)
|
||||
|
||||
const { t, n } = useI18n()
|
||||
const commandStore = useCommandStore()
|
||||
const dialogStore = useDialogStore()
|
||||
const executionStore = useExecutionStore()
|
||||
const queueStore = useQueueStore()
|
||||
const { showQueueClearHistoryDialog } = useQueueClearHistoryDialog()
|
||||
@@ -151,6 +157,24 @@ const {
|
||||
} = useResultGallery(() => filteredTasks.value)
|
||||
|
||||
const onViewItem = wrapWithErrorHandlingAsync(async (item: JobListItem) => {
|
||||
const previewOutput = item.taskRef?.previewOutput
|
||||
|
||||
if (previewOutput?.is3D) {
|
||||
dialogStore.showDialog({
|
||||
key: 'asset-3d-viewer',
|
||||
title: item.title,
|
||||
component: Load3dViewerContent,
|
||||
props: {
|
||||
modelUrl: previewOutput.url || ''
|
||||
},
|
||||
dialogComponentProps: {
|
||||
style: 'width: 80vw; height: 80vh;',
|
||||
maximizable: true
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await openResultGallery(item)
|
||||
})
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { computed, nextTick, watch } from 'vue'
|
||||
|
||||
import { useGraphNodeManager } from '@/composables/graph/useGraphNodeManager'
|
||||
import { createPromotedWidgetView } from '@/core/graph/subgraph/promotedWidgetView'
|
||||
import { BaseWidget, LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
createTestSubgraph,
|
||||
@@ -82,6 +83,163 @@ describe('Node Reactivity', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Widget slotMetadata reactivity on link disconnect', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createTestingPinia({ stubActions: false }))
|
||||
})
|
||||
|
||||
function createWidgetInputGraph() {
|
||||
const graph = new LGraph()
|
||||
const node = new LGraphNode('test')
|
||||
|
||||
// Add a widget and an associated input slot (simulates "widget converted to input")
|
||||
node.addWidget('string', 'prompt', 'hello', () => undefined, {})
|
||||
const input = node.addInput('prompt', 'STRING')
|
||||
// Associate the input slot with the widget (as widgetInputs extension does)
|
||||
input.widget = { name: 'prompt' }
|
||||
|
||||
// Start with a connected link
|
||||
input.link = 42
|
||||
|
||||
graph.add(node)
|
||||
return { graph, node }
|
||||
}
|
||||
|
||||
it('sets slotMetadata.linked to true when input has a link', () => {
|
||||
const { graph, node } = createWidgetInputGraph()
|
||||
const { vueNodeData } = useGraphNodeManager(graph)
|
||||
|
||||
const nodeData = vueNodeData.get(String(node.id))
|
||||
const widgetData = nodeData?.widgets?.find((w) => w.name === 'prompt')
|
||||
|
||||
expect(widgetData?.slotMetadata).toBeDefined()
|
||||
expect(widgetData?.slotMetadata?.linked).toBe(true)
|
||||
})
|
||||
|
||||
it('updates slotMetadata.linked to false after link disconnect event', async () => {
|
||||
const { graph, node } = createWidgetInputGraph()
|
||||
const { vueNodeData } = useGraphNodeManager(graph)
|
||||
|
||||
const nodeData = vueNodeData.get(String(node.id))
|
||||
const widgetData = nodeData?.widgets?.find((w) => w.name === 'prompt')
|
||||
|
||||
// Verify initially linked
|
||||
expect(widgetData?.slotMetadata?.linked).toBe(true)
|
||||
|
||||
// Simulate link disconnection (as LiteGraph does before firing the event)
|
||||
node.inputs[0].link = null
|
||||
|
||||
// Fire the trigger event that LiteGraph fires on disconnect
|
||||
graph.trigger('node:slot-links:changed', {
|
||||
nodeId: node.id,
|
||||
slotType: NodeSlotType.INPUT,
|
||||
slotIndex: 0,
|
||||
connected: false,
|
||||
linkId: 42
|
||||
})
|
||||
|
||||
await nextTick()
|
||||
|
||||
// slotMetadata.linked should now be false
|
||||
expect(widgetData?.slotMetadata?.linked).toBe(false)
|
||||
})
|
||||
|
||||
it('reactively updates disabled state in a derived computed after disconnect', async () => {
|
||||
const { graph, node } = createWidgetInputGraph()
|
||||
const { vueNodeData } = useGraphNodeManager(graph)
|
||||
|
||||
const nodeData = vueNodeData.get(String(node.id))!
|
||||
|
||||
// Mimic what processedWidgets does in NodeWidgets.vue:
|
||||
// derive disabled from slotMetadata.linked
|
||||
const derivedDisabled = computed(() => {
|
||||
const widgets = nodeData.widgets ?? []
|
||||
const widget = widgets.find((w) => w.name === 'prompt')
|
||||
return widget?.slotMetadata?.linked ? true : false
|
||||
})
|
||||
|
||||
// Initially linked → disabled
|
||||
expect(derivedDisabled.value).toBe(true)
|
||||
|
||||
// Track changes
|
||||
const onChange = vi.fn()
|
||||
watch(derivedDisabled, onChange)
|
||||
|
||||
// Simulate disconnect
|
||||
node.inputs[0].link = null
|
||||
graph.trigger('node:slot-links:changed', {
|
||||
nodeId: node.id,
|
||||
slotType: NodeSlotType.INPUT,
|
||||
slotIndex: 0,
|
||||
connected: false,
|
||||
linkId: 42
|
||||
})
|
||||
|
||||
await nextTick()
|
||||
|
||||
// The derived computed should now return false
|
||||
expect(derivedDisabled.value).toBe(false)
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('updates slotMetadata for promoted widgets where SafeWidgetData.name differs from input.widget.name', async () => {
|
||||
// Set up a subgraph with an interior node that has a "prompt" widget.
|
||||
// createPromotedWidgetView resolves against this interior node.
|
||||
const subgraph = createTestSubgraph()
|
||||
const interiorNode = new LGraphNode('interior')
|
||||
interiorNode.id = 10
|
||||
interiorNode.addWidget('string', 'prompt', 'hello', () => undefined, {})
|
||||
subgraph.add(interiorNode)
|
||||
|
||||
const subgraphNode = createTestSubgraphNode(subgraph, { id: 123 })
|
||||
|
||||
// Create a PromotedWidgetView with displayName="value" (subgraph input
|
||||
// slot name) and sourceWidgetName="prompt" (interior widget name).
|
||||
// PromotedWidgetView.name returns "value", but safeWidgetMapper sets
|
||||
// SafeWidgetData.name to sourceWidgetName ("prompt").
|
||||
const promotedView = createPromotedWidgetView(
|
||||
subgraphNode,
|
||||
'10',
|
||||
'prompt',
|
||||
'value'
|
||||
)
|
||||
|
||||
// Host the promoted view on a regular node so we can control widgets
|
||||
// directly (SubgraphNode.widgets is a synthetic getter).
|
||||
const graph = new LGraph()
|
||||
const hostNode = new LGraphNode('host')
|
||||
hostNode.widgets = [promotedView]
|
||||
const input = hostNode.addInput('value', 'STRING')
|
||||
input.widget = { name: 'value' }
|
||||
input.link = 42
|
||||
graph.add(hostNode)
|
||||
|
||||
const { vueNodeData } = useGraphNodeManager(graph)
|
||||
const nodeData = vueNodeData.get(String(hostNode.id))
|
||||
|
||||
// SafeWidgetData.name is "prompt" (sourceWidgetName), but the
|
||||
// input slot widget name is "value" — slotName bridges this gap.
|
||||
const widgetData = nodeData?.widgets?.find((w) => w.name === 'prompt')
|
||||
expect(widgetData).toBeDefined()
|
||||
expect(widgetData?.slotName).toBe('value')
|
||||
expect(widgetData?.slotMetadata?.linked).toBe(true)
|
||||
|
||||
// Disconnect
|
||||
hostNode.inputs[0].link = null
|
||||
graph.trigger('node:slot-links:changed', {
|
||||
nodeId: hostNode.id,
|
||||
slotType: NodeSlotType.INPUT,
|
||||
slotIndex: 0,
|
||||
connected: false,
|
||||
linkId: 42
|
||||
})
|
||||
|
||||
await nextTick()
|
||||
|
||||
expect(widgetData?.slotMetadata?.linked).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Subgraph Promoted Pseudo Widgets', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createTestingPinia({ stubActions: false }))
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
} from '@/lib/litegraph/src/interfaces'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
|
||||
import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
|
||||
import { LayoutSource } from '@/renderer/core/layout/types'
|
||||
import type { NodeId } from '@/renderer/core/layout/types'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
@@ -69,6 +70,12 @@ export interface SafeWidgetData {
|
||||
spec?: InputSpec
|
||||
/** Input slot metadata (index and link status) */
|
||||
slotMetadata?: WidgetSlotMetadata
|
||||
/**
|
||||
* Original LiteGraph widget name used for slot metadata matching.
|
||||
* For promoted widgets, `name` is `sourceWidgetName` (interior widget name)
|
||||
* which differs from the subgraph node's input slot widget name.
|
||||
*/
|
||||
slotName?: string
|
||||
}
|
||||
|
||||
export interface VueNodeData {
|
||||
@@ -238,7 +245,8 @@ function safeWidgetMapper(
|
||||
options: isPromotedPseudoWidget
|
||||
? { ...options, canvasOnly: true }
|
||||
: options,
|
||||
slotMetadata: slotInfo
|
||||
slotMetadata: slotInfo,
|
||||
slotName: name !== widget.name ? widget.name : undefined
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -376,7 +384,7 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
|
||||
|
||||
// Update only widgets with new slot metadata, keeping other widget data intact
|
||||
for (const widget of currentData.widgets ?? []) {
|
||||
const slotInfo = slotMetadata.get(widget.name)
|
||||
const slotInfo = slotMetadata.get(widget.slotName ?? widget.name)
|
||||
if (slotInfo) widget.slotMetadata = slotInfo
|
||||
}
|
||||
}
|
||||
@@ -435,6 +443,11 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
|
||||
const nodePosition = { x: node.pos[0], y: node.pos[1] }
|
||||
const nodeSize = { width: node.size[0], height: node.size[1] }
|
||||
|
||||
// Skip layout creation if it already exists
|
||||
// (e.g. in-place node replacement where the old node's layout is reused for the new node with the same ID).
|
||||
const existingLayout = layoutStore.getNodeLayoutRef(id).value
|
||||
if (existingLayout) return
|
||||
|
||||
// Add node to layout store with final positions
|
||||
setSource(LayoutSource.Canvas)
|
||||
void createNode(id, {
|
||||
|
||||
@@ -2,7 +2,11 @@ import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { useImagePreviewWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImagePreviewWidget'
|
||||
|
||||
export const CANVAS_IMAGE_PREVIEW_WIDGET = '$$canvas-image-preview'
|
||||
const CANVAS_IMAGE_PREVIEW_NODE_TYPES = new Set(['PreviewImage', 'SaveImage'])
|
||||
const CANVAS_IMAGE_PREVIEW_NODE_TYPES = new Set([
|
||||
'PreviewImage',
|
||||
'SaveImage',
|
||||
'GLSLShader'
|
||||
])
|
||||
|
||||
export function supportsVirtualCanvasImagePreview(node: LGraphNode): boolean {
|
||||
return CANVAS_IMAGE_PREVIEW_NODE_TYPES.has(node.type)
|
||||
|
||||
175
src/composables/node/useNodeImageUpload.test.ts
Normal file
175
src/composables/node/useNodeImageUpload.test.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
|
||||
const { mockFetchApi, mockAddAlert, mockUpdateInputs } = vi.hoisted(() => ({
|
||||
mockFetchApi: vi.fn(),
|
||||
mockAddAlert: vi.fn(),
|
||||
mockUpdateInputs: vi.fn()
|
||||
}))
|
||||
|
||||
let capturedDragOnDrop: (files: File[]) => Promise<string[]>
|
||||
|
||||
vi.mock('@/composables/node/useNodeDragAndDrop', () => ({
|
||||
useNodeDragAndDrop: (
|
||||
_node: LGraphNode,
|
||||
opts: { onDrop: typeof capturedDragOnDrop }
|
||||
) => {
|
||||
capturedDragOnDrop = opts.onDrop
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/node/useNodeFileInput', () => ({
|
||||
useNodeFileInput: () => ({ openFileSelection: vi.fn() })
|
||||
}))
|
||||
|
||||
vi.mock('@/composables/node/useNodePaste', () => ({
|
||||
useNodePaste: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/i18n', () => ({
|
||||
t: (key: string) => key
|
||||
}))
|
||||
|
||||
vi.mock('@/platform/updates/common/toastStore', () => ({
|
||||
useToastStore: () => ({ addAlert: mockAddAlert })
|
||||
}))
|
||||
|
||||
vi.mock('@/scripts/api', () => ({
|
||||
api: { fetchApi: mockFetchApi }
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/assetsStore', () => ({
|
||||
useAssetsStore: () => ({ updateInputs: mockUpdateInputs })
|
||||
}))
|
||||
|
||||
function createMockNode(): LGraphNode {
|
||||
return {
|
||||
isUploading: false,
|
||||
imgs: [new Image()],
|
||||
graph: { setDirtyCanvas: vi.fn() },
|
||||
size: [300, 400]
|
||||
} as unknown as LGraphNode
|
||||
}
|
||||
|
||||
function createFile(name = 'test.png'): File {
|
||||
return new File(['data'], name, { type: 'image/png' })
|
||||
}
|
||||
|
||||
function successResponse(name: string, subfolder?: string) {
|
||||
return {
|
||||
status: 200,
|
||||
json: () => Promise.resolve({ name, subfolder })
|
||||
}
|
||||
}
|
||||
|
||||
function failResponse(status = 500) {
|
||||
return {
|
||||
status,
|
||||
statusText: 'Server Error'
|
||||
}
|
||||
}
|
||||
|
||||
describe('useNodeImageUpload', () => {
|
||||
let node: LGraphNode
|
||||
let onUploadComplete: (paths: string[]) => void
|
||||
let onUploadStart: (files: File[]) => void
|
||||
let onUploadError: () => void
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
node = createMockNode()
|
||||
onUploadComplete = vi.fn()
|
||||
onUploadStart = vi.fn()
|
||||
onUploadError = vi.fn()
|
||||
|
||||
const { useNodeImageUpload } = await import('./useNodeImageUpload')
|
||||
useNodeImageUpload(node, {
|
||||
onUploadComplete,
|
||||
onUploadStart,
|
||||
onUploadError,
|
||||
folder: 'input'
|
||||
})
|
||||
})
|
||||
|
||||
it('sets isUploading true during upload and false after', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png'))
|
||||
|
||||
const promise = capturedDragOnDrop([createFile()])
|
||||
expect(node.isUploading).toBe(true)
|
||||
|
||||
await promise
|
||||
expect(node.isUploading).toBe(false)
|
||||
})
|
||||
|
||||
it('clears node.imgs on upload start', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png'))
|
||||
|
||||
const promise = capturedDragOnDrop([createFile()])
|
||||
expect(node.imgs).toBeUndefined()
|
||||
|
||||
await promise
|
||||
})
|
||||
|
||||
it('calls onUploadStart with files', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png'))
|
||||
const files = [createFile()]
|
||||
|
||||
await capturedDragOnDrop(files)
|
||||
expect(onUploadStart).toHaveBeenCalledWith(files)
|
||||
})
|
||||
|
||||
it('calls onUploadComplete with valid paths on success', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png'))
|
||||
|
||||
await capturedDragOnDrop([createFile()])
|
||||
expect(onUploadComplete).toHaveBeenCalledWith(['test.png'])
|
||||
})
|
||||
|
||||
it('includes subfolder in returned path', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png', 'pasted'))
|
||||
|
||||
await capturedDragOnDrop([createFile()])
|
||||
expect(onUploadComplete).toHaveBeenCalledWith(['pasted/test.png'])
|
||||
})
|
||||
|
||||
it('calls onUploadError when all uploads fail', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(failResponse())
|
||||
|
||||
await capturedDragOnDrop([createFile()])
|
||||
expect(onUploadError).toHaveBeenCalled()
|
||||
expect(onUploadComplete).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resets isUploading even when upload fails', async () => {
|
||||
mockFetchApi.mockRejectedValueOnce(new Error('Network error'))
|
||||
|
||||
await capturedDragOnDrop([createFile()])
|
||||
expect(node.isUploading).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects concurrent uploads with a toast', async () => {
|
||||
mockFetchApi.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) =>
|
||||
setTimeout(() => resolve(successResponse('a.png')), 50)
|
||||
)
|
||||
)
|
||||
|
||||
const first = capturedDragOnDrop([createFile('a.png')])
|
||||
const second = await capturedDragOnDrop([createFile('b.png')])
|
||||
|
||||
expect(second).toEqual([])
|
||||
expect(mockAddAlert).toHaveBeenCalledWith('g.uploadAlreadyInProgress')
|
||||
|
||||
await first
|
||||
})
|
||||
|
||||
it('calls setDirtyCanvas on start and finish', async () => {
|
||||
mockFetchApi.mockResolvedValueOnce(successResponse('test.png'))
|
||||
|
||||
await capturedDragOnDrop([createFile()])
|
||||
expect(node.graph?.setDirtyCanvas).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useNodeDragAndDrop } from '@/composables/node/useNodeDragAndDrop'
|
||||
import { useNodeFileInput } from '@/composables/node/useNodeFileInput'
|
||||
import { useNodePaste } from '@/composables/node/useNodePaste'
|
||||
import { t } from '@/i18n'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { useToastStore } from '@/platform/updates/common/toastStore'
|
||||
import type { ResultItemType } from '@/schemas/apiSchema'
|
||||
@@ -62,6 +63,8 @@ interface ImageUploadOptions {
|
||||
* @example 'input', 'output', 'temp'
|
||||
*/
|
||||
folder?: ResultItemType
|
||||
onUploadStart?: (files: File[]) => void
|
||||
onUploadError?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,10 +93,29 @@ export const useNodeImageUpload = (
|
||||
}
|
||||
|
||||
const handleUploadBatch = async (files: File[]) => {
|
||||
const paths = await Promise.all(files.map(handleUpload))
|
||||
const validPaths = paths.filter((p): p is string => !!p)
|
||||
if (validPaths.length) onUploadComplete(validPaths)
|
||||
return validPaths
|
||||
if (node.isUploading) {
|
||||
useToastStore().addAlert(t('g.uploadAlreadyInProgress'))
|
||||
return []
|
||||
}
|
||||
node.isUploading = true
|
||||
|
||||
try {
|
||||
node.imgs = undefined
|
||||
node.graph?.setDirtyCanvas(true)
|
||||
options.onUploadStart?.(files)
|
||||
|
||||
const paths = await Promise.all(files.map(handleUpload))
|
||||
const validPaths = paths.filter((p): p is string => !!p)
|
||||
if (validPaths.length) {
|
||||
onUploadComplete(validPaths)
|
||||
} else {
|
||||
options.onUploadError?.()
|
||||
}
|
||||
return validPaths
|
||||
} finally {
|
||||
node.isUploading = false
|
||||
node.graph?.setDirtyCanvas(true)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle drag & drop
|
||||
|
||||
780
src/composables/painter/usePainter.ts
Normal file
780
src/composables/painter/usePainter.ts
Normal file
@@ -0,0 +1,780 @@
|
||||
import type { Ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import {
|
||||
getEffectiveBrushSize,
|
||||
getEffectiveHardness
|
||||
} from '@/composables/maskeditor/brushUtils'
|
||||
import { StrokeProcessor } from '@/composables/maskeditor/StrokeProcessor'
|
||||
import { hexToRgb } from '@/utils/colorUtil'
|
||||
import type { Point } from '@/extensions/core/maskeditor/types'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import { useToastStore } from '@/platform/updates/common/toastStore'
|
||||
import { api } from '@/scripts/api'
|
||||
import { app } from '@/scripts/app'
|
||||
import { useNodeOutputStore } from '@/stores/imagePreviewStore'
|
||||
|
||||
type PainterTool = 'brush' | 'eraser'
|
||||
|
||||
export const PAINTER_TOOLS: Record<string, PainterTool> = {
|
||||
BRUSH: 'brush',
|
||||
ERASER: 'eraser'
|
||||
} as const
|
||||
|
||||
interface UsePainterOptions {
|
||||
canvasEl: Ref<HTMLCanvasElement | null>
|
||||
modelValue: Ref<string>
|
||||
}
|
||||
|
||||
export function usePainter(nodeId: string, options: UsePainterOptions) {
|
||||
const { canvasEl, modelValue } = options
|
||||
const { t } = useI18n()
|
||||
const nodeOutputStore = useNodeOutputStore()
|
||||
const toastStore = useToastStore()
|
||||
|
||||
const isDirty = ref(false)
|
||||
|
||||
const canvasWidth = ref(512)
|
||||
const canvasHeight = ref(512)
|
||||
|
||||
const cursorX = ref(0)
|
||||
const cursorY = ref(0)
|
||||
const cursorVisible = ref(false)
|
||||
|
||||
const inputImageUrl = ref<string | null>(null)
|
||||
const isImageInputConnected = ref(false)
|
||||
|
||||
let isDrawing = false
|
||||
let strokeProcessor: StrokeProcessor | null = null
|
||||
let lastPoint: Point | null = null
|
||||
|
||||
let cachedRect: DOMRect | null = null
|
||||
|
||||
let mainCtx: CanvasRenderingContext2D | null = null
|
||||
|
||||
let strokeCanvas: HTMLCanvasElement | null = null
|
||||
let strokeCtx: CanvasRenderingContext2D | null = null
|
||||
|
||||
let baseCanvas: HTMLCanvasElement | null = null
|
||||
let baseCtx: CanvasRenderingContext2D | null = null
|
||||
let hasBaseSnapshot = false
|
||||
let hasStrokes = false
|
||||
|
||||
let dirtyX0 = 0
|
||||
let dirtyY0 = 0
|
||||
let dirtyX1 = 0
|
||||
let dirtyY1 = 0
|
||||
let hasDirtyRect = false
|
||||
|
||||
let strokeBrush: {
|
||||
radius: number
|
||||
effectiveRadius: number
|
||||
effectiveHardness: number
|
||||
hardness: number
|
||||
r: number
|
||||
g: number
|
||||
b: number
|
||||
} | null = null
|
||||
|
||||
const litegraphNode = computed(() => {
|
||||
if (!nodeId || !app.canvas.graph) return null
|
||||
return app.canvas.graph.getNodeById(nodeId) as LGraphNode | null
|
||||
})
|
||||
|
||||
function getWidgetByName(name: string): IBaseWidget | undefined {
|
||||
return litegraphNode.value?.widgets?.find(
|
||||
(w: IBaseWidget) => w.name === name
|
||||
)
|
||||
}
|
||||
|
||||
const tool = ref<PainterTool>(PAINTER_TOOLS.BRUSH)
|
||||
const brushSize = ref(20)
|
||||
const brushColor = ref('#ffffff')
|
||||
const brushOpacity = ref(1)
|
||||
const brushHardness = ref(1)
|
||||
const backgroundColor = ref('#000000')
|
||||
|
||||
function restoreSettingsFromProperties() {
|
||||
const node = litegraphNode.value
|
||||
if (!node) return
|
||||
|
||||
const props = node.properties
|
||||
if (props.painterTool != null) tool.value = props.painterTool as PainterTool
|
||||
if (props.painterBrushSize != null)
|
||||
brushSize.value = props.painterBrushSize as number
|
||||
if (props.painterBrushColor != null)
|
||||
brushColor.value = props.painterBrushColor as string
|
||||
if (props.painterBrushOpacity != null)
|
||||
brushOpacity.value = props.painterBrushOpacity as number
|
||||
if (props.painterBrushHardness != null)
|
||||
brushHardness.value = props.painterBrushHardness as number
|
||||
|
||||
const bgColorWidget = getWidgetByName('bg_color')
|
||||
if (bgColorWidget) backgroundColor.value = bgColorWidget.value as string
|
||||
}
|
||||
|
||||
function saveSettingsToProperties() {
|
||||
const node = litegraphNode.value
|
||||
if (!node) return
|
||||
|
||||
node.properties.painterTool = tool.value
|
||||
node.properties.painterBrushSize = brushSize.value
|
||||
node.properties.painterBrushColor = brushColor.value
|
||||
node.properties.painterBrushOpacity = brushOpacity.value
|
||||
node.properties.painterBrushHardness = brushHardness.value
|
||||
}
|
||||
|
||||
function syncCanvasSizeToWidgets() {
|
||||
const widthWidget = getWidgetByName('width')
|
||||
const heightWidget = getWidgetByName('height')
|
||||
|
||||
if (widthWidget && widthWidget.value !== canvasWidth.value) {
|
||||
widthWidget.value = canvasWidth.value
|
||||
widthWidget.callback?.(canvasWidth.value)
|
||||
}
|
||||
if (heightWidget && heightWidget.value !== canvasHeight.value) {
|
||||
heightWidget.value = canvasHeight.value
|
||||
heightWidget.callback?.(canvasHeight.value)
|
||||
}
|
||||
}
|
||||
|
||||
function syncBackgroundColorToWidget() {
|
||||
const bgColorWidget = getWidgetByName('bg_color')
|
||||
if (bgColorWidget && bgColorWidget.value !== backgroundColor.value) {
|
||||
bgColorWidget.value = backgroundColor.value
|
||||
bgColorWidget.callback?.(backgroundColor.value)
|
||||
}
|
||||
}
|
||||
|
||||
function updateInputImageUrl() {
|
||||
const node = litegraphNode.value
|
||||
if (!node) {
|
||||
inputImageUrl.value = null
|
||||
isImageInputConnected.value = false
|
||||
return
|
||||
}
|
||||
|
||||
isImageInputConnected.value = node.isInputConnected(0)
|
||||
|
||||
const inputNode = node.getInputNode(0)
|
||||
if (!inputNode) {
|
||||
inputImageUrl.value = null
|
||||
return
|
||||
}
|
||||
|
||||
const urls = nodeOutputStore.getNodeImageUrls(inputNode)
|
||||
inputImageUrl.value = urls?.length ? urls[0] : null
|
||||
}
|
||||
|
||||
function syncCanvasSizeFromWidgets() {
|
||||
const w = getWidgetByName('width')
|
||||
const h = getWidgetByName('height')
|
||||
canvasWidth.value = (w?.value as number) ?? 512
|
||||
canvasHeight.value = (h?.value as number) ?? 512
|
||||
}
|
||||
|
||||
function activeHardness(): number {
|
||||
return tool.value === PAINTER_TOOLS.ERASER ? 1 : brushHardness.value
|
||||
}
|
||||
|
||||
const { width: canvasDisplayWidth } = useElementSize(canvasEl)
|
||||
|
||||
const displayBrushSize = computed(() => {
|
||||
if (!canvasDisplayWidth.value || !canvasWidth.value) return brushSize.value
|
||||
|
||||
const radius = brushSize.value / 2
|
||||
const effectiveRadius = getEffectiveBrushSize(radius, activeHardness())
|
||||
const effectiveDiameter = effectiveRadius * 2
|
||||
return effectiveDiameter * (canvasDisplayWidth.value / canvasWidth.value)
|
||||
})
|
||||
|
||||
function getCtx() {
|
||||
if (!mainCtx && canvasEl.value) {
|
||||
mainCtx = canvasEl.value.getContext('2d') ?? null
|
||||
}
|
||||
return mainCtx
|
||||
}
|
||||
|
||||
function cacheCanvasRect() {
|
||||
const el = canvasEl.value
|
||||
if (el) cachedRect = el.getBoundingClientRect()
|
||||
}
|
||||
|
||||
function getCanvasPoint(e: PointerEvent): Point | null {
|
||||
const el = canvasEl.value
|
||||
if (!el) return null
|
||||
const rect = cachedRect ?? el.getBoundingClientRect()
|
||||
return {
|
||||
x: ((e.clientX - rect.left) / rect.width) * el.width,
|
||||
y: ((e.clientY - rect.top) / rect.height) * el.height
|
||||
}
|
||||
}
|
||||
|
||||
function expandDirtyRect(cx: number, cy: number, r: number) {
|
||||
const x0 = cx - r
|
||||
const y0 = cy - r
|
||||
const x1 = cx + r
|
||||
const y1 = cy + r
|
||||
if (!hasDirtyRect) {
|
||||
dirtyX0 = x0
|
||||
dirtyY0 = y0
|
||||
dirtyX1 = x1
|
||||
dirtyY1 = y1
|
||||
hasDirtyRect = true
|
||||
} else {
|
||||
if (x0 < dirtyX0) dirtyX0 = x0
|
||||
if (y0 < dirtyY0) dirtyY0 = y0
|
||||
if (x1 > dirtyX1) dirtyX1 = x1
|
||||
if (y1 > dirtyY1) dirtyY1 = y1
|
||||
}
|
||||
}
|
||||
|
||||
function snapshotBrush() {
|
||||
const radius = brushSize.value / 2
|
||||
const hardness = activeHardness()
|
||||
const effectiveRadius = getEffectiveBrushSize(radius, hardness)
|
||||
strokeBrush = {
|
||||
radius,
|
||||
effectiveRadius,
|
||||
effectiveHardness: getEffectiveHardness(
|
||||
radius,
|
||||
hardness,
|
||||
effectiveRadius
|
||||
),
|
||||
hardness,
|
||||
...hexToRgb(brushColor.value)
|
||||
}
|
||||
}
|
||||
|
||||
function drawCircle(ctx: CanvasRenderingContext2D, point: Point) {
|
||||
const b = strokeBrush!
|
||||
|
||||
expandDirtyRect(point.x, point.y, b.effectiveRadius)
|
||||
|
||||
ctx.beginPath()
|
||||
ctx.arc(point.x, point.y, b.effectiveRadius, 0, Math.PI * 2)
|
||||
|
||||
if (b.hardness < 1) {
|
||||
const gradient = ctx.createRadialGradient(
|
||||
point.x,
|
||||
point.y,
|
||||
0,
|
||||
point.x,
|
||||
point.y,
|
||||
b.effectiveRadius
|
||||
)
|
||||
gradient.addColorStop(0, `rgba(${b.r}, ${b.g}, ${b.b}, 1)`)
|
||||
gradient.addColorStop(
|
||||
b.effectiveHardness,
|
||||
`rgba(${b.r}, ${b.g}, ${b.b}, 1)`
|
||||
)
|
||||
gradient.addColorStop(1, `rgba(${b.r}, ${b.g}, ${b.b}, 0)`)
|
||||
ctx.fillStyle = gradient
|
||||
}
|
||||
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
function drawSegment(ctx: CanvasRenderingContext2D, from: Point, to: Point) {
|
||||
const b = strokeBrush!
|
||||
|
||||
if (b.hardness < 1) {
|
||||
const dx = to.x - from.x
|
||||
const dy = to.y - from.y
|
||||
const dist = Math.hypot(dx, dy)
|
||||
const step = Math.max(1, b.effectiveRadius / 2)
|
||||
|
||||
if (dist > 0) {
|
||||
const steps = Math.ceil(dist / step)
|
||||
const dabPoint: Point = { x: 0, y: 0 }
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
const t = i / steps
|
||||
dabPoint.x = from.x + dx * t
|
||||
dabPoint.y = from.y + dy * t
|
||||
drawCircle(ctx, dabPoint)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
expandDirtyRect(from.x, from.y, b.effectiveRadius)
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(from.x, from.y)
|
||||
ctx.lineTo(to.x, to.y)
|
||||
ctx.stroke()
|
||||
drawCircle(ctx, to)
|
||||
}
|
||||
}
|
||||
|
||||
function applyBrushStyle(ctx: CanvasRenderingContext2D) {
|
||||
const b = strokeBrush!
|
||||
const color = `rgb(${b.r}, ${b.g}, ${b.b})`
|
||||
|
||||
ctx.globalCompositeOperation = 'source-over'
|
||||
ctx.globalAlpha = 1
|
||||
ctx.fillStyle = color
|
||||
ctx.strokeStyle = color
|
||||
ctx.lineWidth = b.effectiveRadius * 2
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
}
|
||||
|
||||
function ensureStrokeCanvas() {
|
||||
const el = canvasEl.value
|
||||
if (!el) return null
|
||||
|
||||
if (
|
||||
!strokeCanvas ||
|
||||
strokeCanvas.width !== el.width ||
|
||||
strokeCanvas.height !== el.height
|
||||
) {
|
||||
strokeCanvas = document.createElement('canvas')
|
||||
strokeCanvas.width = el.width
|
||||
strokeCanvas.height = el.height
|
||||
strokeCtx = strokeCanvas.getContext('2d')
|
||||
}
|
||||
|
||||
strokeCtx?.clearRect(0, 0, strokeCanvas.width, strokeCanvas.height)
|
||||
return strokeCtx
|
||||
}
|
||||
|
||||
function ensureBaseCanvas() {
|
||||
const el = canvasEl.value
|
||||
if (!el) return null
|
||||
|
||||
if (
|
||||
!baseCanvas ||
|
||||
baseCanvas.width !== el.width ||
|
||||
baseCanvas.height !== el.height
|
||||
) {
|
||||
baseCanvas = document.createElement('canvas')
|
||||
baseCanvas.width = el.width
|
||||
baseCanvas.height = el.height
|
||||
baseCtx = baseCanvas.getContext('2d')
|
||||
}
|
||||
|
||||
return baseCtx
|
||||
}
|
||||
|
||||
function compositeStrokeToMain(isPreview: boolean = false) {
|
||||
const el = canvasEl.value
|
||||
const ctx = getCtx()
|
||||
if (!el || !ctx || !strokeCanvas) return
|
||||
|
||||
const useDirty = hasDirtyRect
|
||||
const sx = Math.max(0, Math.floor(dirtyX0))
|
||||
const sy = Math.max(0, Math.floor(dirtyY0))
|
||||
const sr = Math.min(el.width, Math.ceil(dirtyX1))
|
||||
const sb = Math.min(el.height, Math.ceil(dirtyY1))
|
||||
const sw = sr - sx
|
||||
const sh = sb - sy
|
||||
hasDirtyRect = false
|
||||
|
||||
if (hasBaseSnapshot && baseCanvas) {
|
||||
if (useDirty && sw > 0 && sh > 0) {
|
||||
ctx.clearRect(sx, sy, sw, sh)
|
||||
ctx.drawImage(baseCanvas, sx, sy, sw, sh, sx, sy, sw, sh)
|
||||
} else {
|
||||
ctx.clearRect(0, 0, el.width, el.height)
|
||||
ctx.drawImage(baseCanvas, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
ctx.save()
|
||||
const isEraser = tool.value === PAINTER_TOOLS.ERASER
|
||||
ctx.globalAlpha = isEraser ? 1 : brushOpacity.value
|
||||
ctx.globalCompositeOperation = isEraser ? 'destination-out' : 'source-over'
|
||||
if (useDirty && sw > 0 && sh > 0) {
|
||||
ctx.drawImage(strokeCanvas, sx, sy, sw, sh, sx, sy, sw, sh)
|
||||
} else {
|
||||
ctx.drawImage(strokeCanvas, 0, 0)
|
||||
}
|
||||
ctx.restore()
|
||||
|
||||
if (!isPreview) {
|
||||
hasBaseSnapshot = false
|
||||
}
|
||||
}
|
||||
|
||||
function startStroke(e: PointerEvent) {
|
||||
const point = getCanvasPoint(e)
|
||||
if (!point) return
|
||||
|
||||
const el = canvasEl.value
|
||||
if (!el) return
|
||||
|
||||
const bCtx = ensureBaseCanvas()
|
||||
if (bCtx) {
|
||||
bCtx.clearRect(0, 0, el.width, el.height)
|
||||
bCtx.drawImage(el, 0, 0)
|
||||
hasBaseSnapshot = true
|
||||
}
|
||||
|
||||
isDrawing = true
|
||||
isDirty.value = true
|
||||
hasStrokes = true
|
||||
snapshotBrush()
|
||||
strokeProcessor = new StrokeProcessor(Math.max(1, strokeBrush!.radius / 2))
|
||||
strokeProcessor.addPoint(point)
|
||||
lastPoint = point
|
||||
|
||||
const ctx = ensureStrokeCanvas()
|
||||
if (!ctx) return
|
||||
ctx.save()
|
||||
applyBrushStyle(ctx)
|
||||
drawCircle(ctx, point)
|
||||
ctx.restore()
|
||||
|
||||
compositeStrokeToMain(true)
|
||||
}
|
||||
|
||||
function continueStroke(e: PointerEvent) {
|
||||
if (!isDrawing || !strokeProcessor || !strokeCtx) return
|
||||
|
||||
const point = getCanvasPoint(e)
|
||||
if (!point) return
|
||||
|
||||
const points = strokeProcessor.addPoint(point)
|
||||
if (points.length === 0 && lastPoint) {
|
||||
points.push(point)
|
||||
}
|
||||
|
||||
if (points.length === 0) return
|
||||
|
||||
strokeCtx.save()
|
||||
applyBrushStyle(strokeCtx)
|
||||
|
||||
let prev = lastPoint ?? points[0]
|
||||
for (const p of points) {
|
||||
drawSegment(strokeCtx, prev, p)
|
||||
prev = p
|
||||
}
|
||||
lastPoint = prev
|
||||
|
||||
strokeCtx.restore()
|
||||
|
||||
compositeStrokeToMain(true)
|
||||
}
|
||||
|
||||
function endStroke() {
|
||||
if (!isDrawing || !strokeProcessor) return
|
||||
|
||||
const points = strokeProcessor.endStroke()
|
||||
if (strokeCtx && points.length > 0) {
|
||||
strokeCtx.save()
|
||||
applyBrushStyle(strokeCtx)
|
||||
let prev = lastPoint ?? points[0]
|
||||
for (const p of points) {
|
||||
drawSegment(strokeCtx, prev, p)
|
||||
prev = p
|
||||
}
|
||||
strokeCtx.restore()
|
||||
}
|
||||
|
||||
compositeStrokeToMain()
|
||||
|
||||
isDrawing = false
|
||||
strokeProcessor = null
|
||||
strokeBrush = null
|
||||
lastPoint = null
|
||||
}
|
||||
|
||||
function resizeCanvas() {
|
||||
const el = canvasEl.value
|
||||
if (!el) return
|
||||
|
||||
let tmp: HTMLCanvasElement | null = null
|
||||
if (el.width > 0 && el.height > 0) {
|
||||
tmp = document.createElement('canvas')
|
||||
tmp.width = el.width
|
||||
tmp.height = el.height
|
||||
tmp.getContext('2d')!.drawImage(el, 0, 0)
|
||||
}
|
||||
|
||||
el.width = canvasWidth.value
|
||||
el.height = canvasHeight.value
|
||||
mainCtx = null
|
||||
|
||||
if (tmp) {
|
||||
getCtx()?.drawImage(tmp, 0, 0)
|
||||
}
|
||||
|
||||
strokeCanvas = null
|
||||
strokeCtx = null
|
||||
baseCanvas = null
|
||||
baseCtx = null
|
||||
hasBaseSnapshot = false
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
const el = canvasEl.value
|
||||
const ctx = getCtx()
|
||||
if (!el || !ctx) return
|
||||
ctx.clearRect(0, 0, el.width, el.height)
|
||||
isDirty.value = true
|
||||
hasStrokes = false
|
||||
}
|
||||
|
||||
function updateCursorPos(e: PointerEvent) {
|
||||
cursorX.value = e.offsetX
|
||||
cursorY.value = e.offsetY
|
||||
}
|
||||
|
||||
function handlePointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0) return
|
||||
;(e.target as HTMLElement).setPointerCapture(e.pointerId)
|
||||
cacheCanvasRect()
|
||||
updateCursorPos(e)
|
||||
startStroke(e)
|
||||
}
|
||||
|
||||
let pendingMoveEvent: PointerEvent | null = null
|
||||
let rafId: number | null = null
|
||||
|
||||
function flushPendingStroke() {
|
||||
if (pendingMoveEvent) {
|
||||
continueStroke(pendingMoveEvent)
|
||||
pendingMoveEvent = null
|
||||
}
|
||||
rafId = null
|
||||
}
|
||||
|
||||
function handlePointerMove(e: PointerEvent) {
|
||||
updateCursorPos(e)
|
||||
if (!isDrawing) return
|
||||
|
||||
pendingMoveEvent = e
|
||||
if (!rafId) {
|
||||
rafId = requestAnimationFrame(flushPendingStroke)
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerUp(e: PointerEvent) {
|
||||
if (e.button !== 0) return
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId)
|
||||
flushPendingStroke()
|
||||
}
|
||||
;(e.target as HTMLElement).releasePointerCapture(e.pointerId)
|
||||
endStroke()
|
||||
}
|
||||
|
||||
function handlePointerLeave() {
|
||||
cursorVisible.value = false
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId)
|
||||
flushPendingStroke()
|
||||
}
|
||||
endStroke()
|
||||
}
|
||||
|
||||
function handlePointerEnter() {
|
||||
cursorVisible.value = true
|
||||
}
|
||||
|
||||
function handleInputImageLoad(e: Event) {
|
||||
const img = e.target as HTMLImageElement
|
||||
const widthWidget = getWidgetByName('width')
|
||||
const heightWidget = getWidgetByName('height')
|
||||
if (widthWidget) {
|
||||
widthWidget.value = img.naturalWidth
|
||||
widthWidget.callback?.(img.naturalWidth)
|
||||
}
|
||||
if (heightWidget) {
|
||||
heightWidget.value = img.naturalHeight
|
||||
heightWidget.callback?.(img.naturalHeight)
|
||||
}
|
||||
canvasWidth.value = img.naturalWidth
|
||||
canvasHeight.value = img.naturalHeight
|
||||
}
|
||||
|
||||
function parseMaskFilename(value: string): {
|
||||
filename: string
|
||||
subfolder: string
|
||||
type: string
|
||||
} | null {
|
||||
const trimmed = value?.trim()
|
||||
if (!trimmed) return null
|
||||
|
||||
const typeMatch = trimmed.match(/^(.+?) \[([^\]]+)\]$/)
|
||||
const pathPart = typeMatch ? typeMatch[1] : trimmed
|
||||
const type = typeMatch ? typeMatch[2] : 'input'
|
||||
|
||||
const lastSlash = pathPart.lastIndexOf('/')
|
||||
const subfolder = lastSlash !== -1 ? pathPart.substring(0, lastSlash) : ''
|
||||
const filename =
|
||||
lastSlash !== -1 ? pathPart.substring(lastSlash + 1) : pathPart
|
||||
|
||||
return { filename, subfolder, type }
|
||||
}
|
||||
|
||||
function isCanvasEmpty(): boolean {
|
||||
return !hasStrokes
|
||||
}
|
||||
|
||||
async function serializeValue(): Promise<string> {
|
||||
const el = canvasEl.value
|
||||
if (!el) return ''
|
||||
|
||||
if (isCanvasEmpty()) return ''
|
||||
|
||||
if (!isDirty.value) return modelValue.value
|
||||
|
||||
const blob = await new Promise<Blob | null>((resolve) =>
|
||||
el.toBlob(resolve, 'image/png')
|
||||
)
|
||||
if (!blob) return modelValue.value
|
||||
|
||||
const name = `painter-${nodeId}-${Date.now()}.png`
|
||||
const body = new FormData()
|
||||
body.append('image', blob, name)
|
||||
if (!isCloud) body.append('subfolder', 'painter')
|
||||
body.append('type', isCloud ? 'input' : 'temp')
|
||||
|
||||
let resp: Response
|
||||
try {
|
||||
resp = await api.fetchApi('/upload/image', {
|
||||
method: 'POST',
|
||||
body
|
||||
})
|
||||
} catch (e) {
|
||||
const err = t('painter.uploadError', {
|
||||
status: 0,
|
||||
statusText: e instanceof Error ? e.message : String(e)
|
||||
})
|
||||
toastStore.addAlert(err)
|
||||
throw new Error(err)
|
||||
}
|
||||
|
||||
if (resp.status !== 200) {
|
||||
const err = t('painter.uploadError', {
|
||||
status: resp.status,
|
||||
statusText: resp.statusText
|
||||
})
|
||||
toastStore.addAlert(err)
|
||||
throw new Error(err)
|
||||
}
|
||||
|
||||
let data: { name: string }
|
||||
try {
|
||||
data = await resp.json()
|
||||
} catch (e) {
|
||||
const err = t('painter.uploadError', {
|
||||
status: resp.status,
|
||||
statusText: e instanceof Error ? e.message : String(e)
|
||||
})
|
||||
toastStore.addAlert(err)
|
||||
throw new Error(err)
|
||||
}
|
||||
|
||||
const result = isCloud
|
||||
? `${data.name} [input]`
|
||||
: `painter/${data.name} [temp]`
|
||||
modelValue.value = result
|
||||
isDirty.value = false
|
||||
return result
|
||||
}
|
||||
|
||||
function registerWidgetSerialization() {
|
||||
const node = litegraphNode.value
|
||||
if (!node?.widgets) return
|
||||
const targetWidget = node.widgets.find(
|
||||
(w: IBaseWidget) => w.name === 'mask'
|
||||
)
|
||||
if (targetWidget) {
|
||||
targetWidget.serializeValue = serializeValue
|
||||
}
|
||||
}
|
||||
|
||||
function restoreCanvas() {
|
||||
const parsed = parseMaskFilename(modelValue.value)
|
||||
if (!parsed) return
|
||||
|
||||
const params = new URLSearchParams()
|
||||
params.set('filename', parsed.filename)
|
||||
if (parsed.subfolder) params.set('subfolder', parsed.subfolder)
|
||||
params.set('type', parsed.type)
|
||||
|
||||
const url = api.apiURL('/view?' + params.toString())
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
img.onload = () => {
|
||||
const el = canvasEl.value
|
||||
if (!el) return
|
||||
canvasWidth.value = img.naturalWidth
|
||||
canvasHeight.value = img.naturalHeight
|
||||
mainCtx = null
|
||||
getCtx()?.drawImage(img, 0, 0)
|
||||
isDirty.value = false
|
||||
hasStrokes = true
|
||||
}
|
||||
img.onerror = () => {
|
||||
modelValue.value = ''
|
||||
}
|
||||
img.src = url
|
||||
}
|
||||
|
||||
watch(() => nodeOutputStore.nodeOutputs, updateInputImageUrl, { deep: true })
|
||||
watch(() => nodeOutputStore.nodePreviewImages, updateInputImageUrl, {
|
||||
deep: true
|
||||
})
|
||||
watch([canvasWidth, canvasHeight], resizeCanvas)
|
||||
|
||||
watch(
|
||||
[tool, brushSize, brushColor, brushOpacity, brushHardness],
|
||||
saveSettingsToProperties
|
||||
)
|
||||
|
||||
watch([canvasWidth, canvasHeight], syncCanvasSizeToWidgets)
|
||||
|
||||
watch(backgroundColor, syncBackgroundColorToWidget)
|
||||
|
||||
function initialize() {
|
||||
syncCanvasSizeFromWidgets()
|
||||
resizeCanvas()
|
||||
registerWidgetSerialization()
|
||||
restoreSettingsFromProperties()
|
||||
updateInputImageUrl()
|
||||
restoreCanvas()
|
||||
}
|
||||
|
||||
onMounted(initialize)
|
||||
|
||||
onUnmounted(() => {
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId)
|
||||
rafId = null
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
tool,
|
||||
brushSize,
|
||||
brushColor,
|
||||
brushOpacity,
|
||||
brushHardness,
|
||||
backgroundColor,
|
||||
|
||||
canvasWidth,
|
||||
canvasHeight,
|
||||
|
||||
cursorX,
|
||||
cursorY,
|
||||
cursorVisible,
|
||||
displayBrushSize,
|
||||
|
||||
inputImageUrl,
|
||||
isImageInputConnected,
|
||||
|
||||
handlePointerDown,
|
||||
handlePointerMove,
|
||||
handlePointerUp,
|
||||
handlePointerEnter,
|
||||
handlePointerLeave,
|
||||
|
||||
handleInputImageLoad,
|
||||
handleClear
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import type { TaskItemImpl } from '@/stores/queueStore'
|
||||
|
||||
type TestTask = {
|
||||
jobId: string
|
||||
queueIndex: number
|
||||
job: { priority: number }
|
||||
mockState: JobState
|
||||
executionTime?: number
|
||||
executionEndTimestamp?: number
|
||||
@@ -174,7 +174,7 @@ const createTask = (
|
||||
overrides: Partial<TestTask> & { mockState?: JobState } = {}
|
||||
): TestTask => ({
|
||||
jobId: overrides.jobId ?? `task-${Math.random().toString(36).slice(2, 7)}`,
|
||||
queueIndex: overrides.queueIndex ?? 0,
|
||||
job: overrides.job ?? { priority: 0 },
|
||||
mockState: overrides.mockState ?? 'pending',
|
||||
executionTime: overrides.executionTime,
|
||||
executionEndTimestamp: overrides.executionEndTimestamp,
|
||||
@@ -258,7 +258,7 @@ describe('useJobList', () => {
|
||||
it('tracks recently added pending jobs and clears the hint after expiry', async () => {
|
||||
vi.useFakeTimers()
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({ jobId: '1', queueIndex: 1, mockState: 'pending' })
|
||||
createTask({ jobId: '1', job: { priority: 1 }, mockState: 'pending' })
|
||||
]
|
||||
|
||||
const { jobItems } = initComposable()
|
||||
@@ -287,7 +287,7 @@ describe('useJobList', () => {
|
||||
vi.useFakeTimers()
|
||||
const taskId = '2'
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({ jobId: taskId, queueIndex: 1, mockState: 'pending' })
|
||||
createTask({ jobId: taskId, job: { priority: 1 }, mockState: 'pending' })
|
||||
]
|
||||
|
||||
const { jobItems } = initComposable()
|
||||
@@ -300,7 +300,7 @@ describe('useJobList', () => {
|
||||
|
||||
vi.mocked(buildJobDisplay).mockClear()
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({ jobId: taskId, queueIndex: 2, mockState: 'pending' })
|
||||
createTask({ jobId: taskId, job: { priority: 2 }, mockState: 'pending' })
|
||||
]
|
||||
await flush()
|
||||
jobItems.value
|
||||
@@ -314,7 +314,7 @@ describe('useJobList', () => {
|
||||
it('cleans up timeouts on unmount', async () => {
|
||||
vi.useFakeTimers()
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({ jobId: '3', queueIndex: 1, mockState: 'pending' })
|
||||
createTask({ jobId: '3', job: { priority: 1 }, mockState: 'pending' })
|
||||
]
|
||||
|
||||
initComposable()
|
||||
@@ -331,7 +331,7 @@ describe('useJobList', () => {
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({
|
||||
jobId: 'p',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'pending',
|
||||
createTime: 3000
|
||||
})
|
||||
@@ -339,7 +339,7 @@ describe('useJobList', () => {
|
||||
queueStoreMock.runningTasks = [
|
||||
createTask({
|
||||
jobId: 'r',
|
||||
queueIndex: 5,
|
||||
job: { priority: 5 },
|
||||
mockState: 'running',
|
||||
createTime: 2000
|
||||
})
|
||||
@@ -347,7 +347,7 @@ describe('useJobList', () => {
|
||||
queueStoreMock.historyTasks = [
|
||||
createTask({
|
||||
jobId: 'h',
|
||||
queueIndex: 3,
|
||||
job: { priority: 3 },
|
||||
mockState: 'completed',
|
||||
createTime: 1000,
|
||||
executionEndTimestamp: 5000
|
||||
@@ -366,9 +366,9 @@ describe('useJobList', () => {
|
||||
|
||||
it('filters by job tab and resets failed tab when failures disappear', async () => {
|
||||
queueStoreMock.historyTasks = [
|
||||
createTask({ jobId: 'c', queueIndex: 3, mockState: 'completed' }),
|
||||
createTask({ jobId: 'f', queueIndex: 2, mockState: 'failed' }),
|
||||
createTask({ jobId: 'p', queueIndex: 1, mockState: 'pending' })
|
||||
createTask({ jobId: 'c', job: { priority: 3 }, mockState: 'completed' }),
|
||||
createTask({ jobId: 'f', job: { priority: 2 }, mockState: 'failed' }),
|
||||
createTask({ jobId: 'p', job: { priority: 1 }, mockState: 'pending' })
|
||||
]
|
||||
|
||||
const instance = initComposable()
|
||||
@@ -384,7 +384,7 @@ describe('useJobList', () => {
|
||||
expect(instance.hasFailedJobs.value).toBe(true)
|
||||
|
||||
queueStoreMock.historyTasks = [
|
||||
createTask({ jobId: 'c', queueIndex: 3, mockState: 'completed' })
|
||||
createTask({ jobId: 'c', job: { priority: 3 }, mockState: 'completed' })
|
||||
]
|
||||
await flush()
|
||||
|
||||
@@ -396,13 +396,13 @@ describe('useJobList', () => {
|
||||
queueStoreMock.pendingTasks = [
|
||||
createTask({
|
||||
jobId: 'wf-1',
|
||||
queueIndex: 2,
|
||||
job: { priority: 2 },
|
||||
mockState: 'pending',
|
||||
workflowId: 'workflow-1'
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'wf-2',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'pending',
|
||||
workflowId: 'workflow-2'
|
||||
})
|
||||
@@ -426,14 +426,14 @@ describe('useJobList', () => {
|
||||
queueStoreMock.historyTasks = [
|
||||
createTask({
|
||||
jobId: 'alpha',
|
||||
queueIndex: 2,
|
||||
job: { priority: 2 },
|
||||
mockState: 'completed',
|
||||
createTime: 2000,
|
||||
executionEndTimestamp: 2000
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'beta',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'failed',
|
||||
createTime: 1000,
|
||||
executionEndTimestamp: 1000
|
||||
@@ -471,13 +471,13 @@ describe('useJobList', () => {
|
||||
queueStoreMock.runningTasks = [
|
||||
createTask({
|
||||
jobId: 'active',
|
||||
queueIndex: 3,
|
||||
job: { priority: 3 },
|
||||
mockState: 'running',
|
||||
executionTime: 7_200_000
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'other',
|
||||
queueIndex: 2,
|
||||
job: { priority: 2 },
|
||||
mockState: 'running',
|
||||
executionTime: 3_600_000
|
||||
})
|
||||
@@ -507,7 +507,7 @@ describe('useJobList', () => {
|
||||
queueStoreMock.runningTasks = [
|
||||
createTask({
|
||||
jobId: 'live-preview',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'running'
|
||||
})
|
||||
]
|
||||
@@ -526,7 +526,7 @@ describe('useJobList', () => {
|
||||
queueStoreMock.runningTasks = [
|
||||
createTask({
|
||||
jobId: 'disabled-preview',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'running'
|
||||
})
|
||||
]
|
||||
@@ -567,28 +567,28 @@ describe('useJobList', () => {
|
||||
queueStoreMock.historyTasks = [
|
||||
createTask({
|
||||
jobId: 'today-small',
|
||||
queueIndex: 4,
|
||||
job: { priority: 4 },
|
||||
mockState: 'completed',
|
||||
executionEndTimestamp: Date.now(),
|
||||
executionTime: 2_000
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'today-large',
|
||||
queueIndex: 3,
|
||||
job: { priority: 3 },
|
||||
mockState: 'completed',
|
||||
executionEndTimestamp: Date.now(),
|
||||
executionTime: 5_000
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'yesterday',
|
||||
queueIndex: 2,
|
||||
job: { priority: 2 },
|
||||
mockState: 'failed',
|
||||
executionEndTimestamp: Date.now() - 86_400_000,
|
||||
executionTime: 1_000
|
||||
}),
|
||||
createTask({
|
||||
jobId: 'undated',
|
||||
queueIndex: 1,
|
||||
job: { priority: 1 },
|
||||
mockState: 'pending'
|
||||
})
|
||||
]
|
||||
|
||||
@@ -4,64 +4,32 @@ import { useToast } from 'primevue/usetoast'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
export function useCopyToClipboard() {
|
||||
const { copy, copied } = useClipboard()
|
||||
const { copy, copied } = useClipboard({ legacy: true })
|
||||
const toast = useToast()
|
||||
const showSuccessToast = () => {
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: t('g.success'),
|
||||
detail: t('clipboard.successMessage'),
|
||||
life: 3000
|
||||
})
|
||||
}
|
||||
const showErrorToast = () => {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: t('g.error'),
|
||||
detail: t('clipboard.errorMessage')
|
||||
})
|
||||
}
|
||||
|
||||
function fallbackCopy(text: string) {
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.setAttribute('readonly', '')
|
||||
textarea.value = text
|
||||
textarea.style.position = 'absolute'
|
||||
textarea.style.left = '-9999px'
|
||||
textarea.setAttribute('aria-hidden', 'true')
|
||||
textarea.setAttribute('tabindex', '-1')
|
||||
textarea.style.width = '1px'
|
||||
textarea.style.height = '1px'
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
|
||||
try {
|
||||
// using legacy document.execCommand for fallback for old and linux browsers
|
||||
const successful = document.execCommand('copy')
|
||||
if (successful) {
|
||||
showSuccessToast()
|
||||
} else {
|
||||
showErrorToast()
|
||||
}
|
||||
} catch (err) {
|
||||
showErrorToast()
|
||||
} finally {
|
||||
textarea.remove()
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = async (text: string) => {
|
||||
async function copyToClipboard(text: string) {
|
||||
try {
|
||||
await copy(text)
|
||||
if (copied.value) {
|
||||
showSuccessToast()
|
||||
toast.add({
|
||||
severity: 'success',
|
||||
summary: t('g.success'),
|
||||
detail: t('clipboard.successMessage'),
|
||||
life: 3000
|
||||
})
|
||||
} else {
|
||||
// If VueUse copy failed, try fallback
|
||||
fallbackCopy(text)
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: t('g.error'),
|
||||
detail: t('clipboard.errorMessage')
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
// VueUse copy failed, try fallback
|
||||
fallbackCopy(text)
|
||||
} catch {
|
||||
toast.add({
|
||||
severity: 'error',
|
||||
summary: t('g.error'),
|
||||
detail: t('clipboard.errorMessage')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { computed, onBeforeUnmount, ref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
import { createMonotoneInterpolator } from '@/components/curve/curveUtils'
|
||||
import type { CurvePoint } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { CurvePoint } from '@/components/curve/types'
|
||||
|
||||
interface UseCurveEditorOptions {
|
||||
svgRef: Ref<SVGSVGElement | null>
|
||||
@@ -21,11 +21,12 @@ export function useCurveEditor({ svgRef, modelValue }: UseCurveEditorOptions) {
|
||||
const xMin = points[0][0]
|
||||
const xMax = points[points.length - 1][0]
|
||||
const segments = 128
|
||||
const range = xMax - xMin
|
||||
const parts: string[] = []
|
||||
for (let i = 0; i <= segments; i++) {
|
||||
const x = xMin + (xMax - xMin) * (i / segments)
|
||||
const x = xMin + range * (i / segments)
|
||||
const y = 1 - interpolate(x)
|
||||
parts.push(`${i === 0 ? 'M' : 'L'}${x.toFixed(4)},${y.toFixed(4)}`)
|
||||
parts.push(`${i === 0 ? 'M' : 'L'}${x},${y}`)
|
||||
}
|
||||
return parts.join('')
|
||||
})
|
||||
|
||||
44
src/composables/useMissingNodeScan.ts
Normal file
44
src/composables/useMissingNodeScan.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import type { LGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { useNodeReplacementStore } from '@/platform/nodeReplacement/nodeReplacementStore'
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import {
|
||||
collectAllNodes,
|
||||
getExecutionIdByNode
|
||||
} from '@/utils/graphTraversalUtil'
|
||||
import { getCnrIdFromNode } from '@/workbench/extensions/manager/utils/missingNodeErrorUtil'
|
||||
|
||||
/** Scan the live graph for unregistered node types and build a full MissingNodeType list. */
|
||||
function scanMissingNodes(rootGraph: LGraph): MissingNodeType[] {
|
||||
const nodeReplacementStore = useNodeReplacementStore()
|
||||
const missingNodeTypes: MissingNodeType[] = []
|
||||
|
||||
const allNodes = collectAllNodes(rootGraph)
|
||||
|
||||
for (const node of allNodes) {
|
||||
const originalType = node.last_serialization?.type ?? node.type ?? 'Unknown'
|
||||
|
||||
if (originalType in LiteGraph.registered_node_types) continue
|
||||
|
||||
const cnrId = getCnrIdFromNode(node)
|
||||
const replacement = nodeReplacementStore.getReplacementFor(originalType)
|
||||
const executionId = getExecutionIdByNode(rootGraph, node)
|
||||
|
||||
missingNodeTypes.push({
|
||||
type: originalType,
|
||||
nodeId: executionId ?? String(node.id),
|
||||
cnrId,
|
||||
isReplaceable: replacement !== null,
|
||||
replacement: replacement ?? undefined
|
||||
})
|
||||
}
|
||||
|
||||
return missingNodeTypes
|
||||
}
|
||||
|
||||
/** Re-scan the graph for missing nodes and update the error store. */
|
||||
export function rescanAndSurfaceMissingNodes(rootGraph: LGraph): void {
|
||||
const types = scanMissingNodes(rootGraph)
|
||||
useExecutionErrorStore().surfaceMissingNodes(types)
|
||||
}
|
||||
@@ -25,7 +25,10 @@ export const TOOLKIT_NODE_NAMES: ReadonlySet<string> = new Set([
|
||||
// API Nodes
|
||||
'RecraftRemoveBackgroundNode',
|
||||
'RecraftVectorizeImageNode',
|
||||
'KlingOmniProEditVideoNode'
|
||||
'KlingOmniProEditVideoNode',
|
||||
|
||||
// Shader Nodes
|
||||
'GLSLShader'
|
||||
])
|
||||
|
||||
/**
|
||||
|
||||
@@ -201,7 +201,8 @@ class PromotedWidgetView implements IPromotedWidgetView {
|
||||
projected.drawWidget(ctx, {
|
||||
width: widgetWidth,
|
||||
showText: !lowQuality,
|
||||
suppressPromotedOutline: true
|
||||
suppressPromotedOutline: true,
|
||||
previewImages: resolved.node.imgs
|
||||
})
|
||||
|
||||
projected.y = originalY
|
||||
|
||||
@@ -184,6 +184,17 @@ describe('getPromotableWidgets', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('adds virtual canvas preview widget for GLSLShader nodes', () => {
|
||||
const node = new LGraphNode('GLSLShader')
|
||||
node.type = 'GLSLShader'
|
||||
|
||||
const widgets = getPromotableWidgets(node)
|
||||
|
||||
expect(
|
||||
widgets.some((widget) => widget.name === CANVAS_IMAGE_PREVIEW_WIDGET)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not add virtual canvas preview widget for non-image nodes', () => {
|
||||
const node = new LGraphNode('TextNode')
|
||||
node.addOutput('TEXT', 'STRING')
|
||||
@@ -232,4 +243,25 @@ describe('promoteRecommendedWidgets', () => {
|
||||
|
||||
expect(updatePreviewsMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('eagerly promotes virtual preview widget for CANVAS_IMAGE_PREVIEW nodes', () => {
|
||||
const subgraph = createTestSubgraph()
|
||||
const subgraphNode = createTestSubgraphNode(subgraph)
|
||||
const glslNode = new LGraphNode('GLSLShader')
|
||||
glslNode.type = 'GLSLShader'
|
||||
subgraph.add(glslNode)
|
||||
|
||||
promoteRecommendedWidgets(subgraphNode)
|
||||
|
||||
const store = usePromotionStore()
|
||||
expect(
|
||||
store.isPromoted(
|
||||
subgraphNode.rootGraph.id,
|
||||
subgraphNode.id,
|
||||
String(glslNode.id),
|
||||
CANVAS_IMAGE_PREVIEW_WIDGET
|
||||
)
|
||||
).toBe(true)
|
||||
expect(updatePreviewsMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -227,6 +227,29 @@ export function promoteRecommendedWidgets(subgraphNode: SubgraphNode) {
|
||||
// defer. Core $$ preview widgets are the lazy path that needs updatePreviews.
|
||||
if (hasPreviewWidget()) continue
|
||||
|
||||
// Nodes in CANVAS_IMAGE_PREVIEW_NODE_TYPES support a virtual $$
|
||||
// preview widget. Eagerly promote it so getPseudoWidgetPreviewTargets
|
||||
// includes this node and onDrawBackground can call updatePreviews on it
|
||||
// once execution outputs arrive.
|
||||
if (supportsVirtualCanvasImagePreview(node)) {
|
||||
if (
|
||||
!store.isPromoted(
|
||||
subgraphNode.rootGraph.id,
|
||||
subgraphNode.id,
|
||||
String(node.id),
|
||||
CANVAS_IMAGE_PREVIEW_WIDGET
|
||||
)
|
||||
) {
|
||||
store.promote(
|
||||
subgraphNode.rootGraph.id,
|
||||
subgraphNode.id,
|
||||
String(node.id),
|
||||
CANVAS_IMAGE_PREVIEW_WIDGET
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Also schedule a deferred check: core $$ widgets are created lazily by
|
||||
// updatePreviews when node outputs are first loaded.
|
||||
requestAnimationFrame(() => updatePreviews(node, promotePreviewWidget))
|
||||
|
||||
@@ -19,6 +19,7 @@ if (!isCloud) {
|
||||
await import('./nodeTemplates')
|
||||
}
|
||||
import './noteNode'
|
||||
import './painter'
|
||||
import './previewAny'
|
||||
import './rerouteNode'
|
||||
import './saveImageExtraOutput'
|
||||
|
||||
22
src/extensions/core/painter.ts
Normal file
22
src/extensions/core/painter.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { useExtensionService } from '@/services/extensionService'
|
||||
|
||||
const HIDDEN_WIDGETS = new Set(['width', 'height', 'bg_color'])
|
||||
|
||||
useExtensionService().registerExtension({
|
||||
name: 'Comfy.Painter',
|
||||
|
||||
nodeCreated(node) {
|
||||
if (node.constructor.comfyClass !== 'Painter') return
|
||||
|
||||
const [oldWidth, oldHeight] = node.size
|
||||
node.setSize([Math.max(oldWidth, 450), Math.max(oldHeight, 550)])
|
||||
|
||||
node.hideOutputImages = true
|
||||
|
||||
for (const widget of node.widgets ?? []) {
|
||||
if (HIDDEN_WIDGETS.has(widget.name)) {
|
||||
widget.hidden = true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -43,7 +43,7 @@ async function uploadFile(
|
||||
file: File,
|
||||
updateNode: boolean,
|
||||
pasted: boolean = false
|
||||
) {
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
// Wrap file in formdata so it includes filename
|
||||
const body = new FormData()
|
||||
@@ -76,12 +76,15 @@ async function uploadFile(
|
||||
// Manually trigger the callback to update VueNodes
|
||||
audioWidget.callback?.(path)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
useToastStore().addAlert(resp.status + ' - ' + resp.statusText)
|
||||
return false
|
||||
}
|
||||
} catch (error) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
useToastStore().addAlert(error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,7 +235,17 @@ app.registerExtension({
|
||||
|
||||
const handleUpload = async (files: File[]) => {
|
||||
if (files?.length) {
|
||||
uploadFile(audioWidget, audioUIWidget, files[0], true)
|
||||
const previousValue = audioWidget.value
|
||||
audioWidget.value = files[0].name
|
||||
const success = await uploadFile(
|
||||
audioWidget,
|
||||
audioUIWidget,
|
||||
files[0],
|
||||
true
|
||||
)
|
||||
if (!success) {
|
||||
audioWidget.value = previousValue
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Bounds } from '@/renderer/core/layout/types'
|
||||
import type { CurvePoint } from '@/components/curve/types'
|
||||
|
||||
import type {
|
||||
CanvasColour,
|
||||
@@ -137,6 +138,7 @@ export type IWidget =
|
||||
| IImageCropWidget
|
||||
| IBoundingBoxWidget
|
||||
| ICurveWidget
|
||||
| IPainterWidget
|
||||
|
||||
export interface IBooleanWidget extends IBaseWidget<boolean, 'toggle'> {
|
||||
type: 'toggle'
|
||||
@@ -329,13 +331,16 @@ export interface IBoundingBoxWidget extends IBaseWidget<Bounds, 'boundingbox'> {
|
||||
value: Bounds
|
||||
}
|
||||
|
||||
export type CurvePoint = [x: number, y: number]
|
||||
|
||||
export interface ICurveWidget extends IBaseWidget<CurvePoint[], 'curve'> {
|
||||
type: 'curve'
|
||||
value: CurvePoint[]
|
||||
}
|
||||
|
||||
export interface IPainterWidget extends IBaseWidget<string, 'painter'> {
|
||||
type: 'painter'
|
||||
value: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid widget types. TS cannot provide easily extensible type safety for this at present.
|
||||
* Override linkedWidgets[]
|
||||
|
||||
@@ -162,6 +162,38 @@ describe('BaseWidget store integration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('DOM widget value registration', () => {
|
||||
it('registers value from getter when value property is overridden', () => {
|
||||
const defaultValue = 'You are an expert image-generation engine.'
|
||||
const widget = createTestWidget(node, {
|
||||
name: 'system_prompt',
|
||||
value: undefined as unknown as number
|
||||
})
|
||||
|
||||
// Simulate what addDOMWidget does: override value with getter/setter
|
||||
// that falls back to a default (like inputEl.value for textarea widgets)
|
||||
Object.defineProperty(widget, 'value', {
|
||||
get() {
|
||||
const graphId = widget.node.graph?.rootGraph.id
|
||||
if (!graphId) return defaultValue
|
||||
const state = store.getWidget(graphId, node.id, 'system_prompt')
|
||||
return (state?.value as string) ?? defaultValue
|
||||
},
|
||||
set(v: string) {
|
||||
const graphId = widget.node.graph?.rootGraph.id
|
||||
if (!graphId) return
|
||||
const state = store.getWidget(graphId, node.id, 'system_prompt')
|
||||
if (state) state.value = v
|
||||
}
|
||||
})
|
||||
|
||||
widget.setNodeId(node.id)
|
||||
|
||||
const state = store.getWidget(graph.id, node.id, 'system_prompt')
|
||||
expect(state?.value).toBe(defaultValue)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fallback behavior', () => {
|
||||
it('uses internal value before registration', () => {
|
||||
const widget = createTestWidget(node, {
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface DrawWidgetOptions {
|
||||
showText?: boolean
|
||||
/** When true, suppresses the promoted outline color (e.g. for projected copies on SubgraphNode). */
|
||||
suppressPromotedOutline?: boolean
|
||||
/** Transient image source for preview widgets rendered on behalf of another node (e.g. subgraph promotion). */
|
||||
previewImages?: HTMLImageElement[]
|
||||
}
|
||||
|
||||
interface DrawTruncatingTextOptions extends DrawWidgetOptions {
|
||||
@@ -140,6 +142,10 @@ export abstract class BaseWidget<TWidget extends IBaseWidget = IBaseWidget>
|
||||
|
||||
this._state = useWidgetValueStore().registerWidget(graphId, {
|
||||
...this._state,
|
||||
// BaseWidget: this.value getter returns this._state.value. So value: this.value === value: this._state.value.
|
||||
// BaseDOMWidgetImpl: this.value getter returns options.getValue?.() ?? ''. Resolves the correct initial value instead of undefined.
|
||||
// I.e., calls overriden getter -> options.getValue() -> correct value (https://github.com/Comfy-Org/ComfyUI_frontend/issues/9194).
|
||||
value: this.value,
|
||||
nodeId
|
||||
})
|
||||
}
|
||||
|
||||
22
src/lib/litegraph/src/widgets/PainterWidget.ts
Normal file
22
src/lib/litegraph/src/widgets/PainterWidget.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { IPainterWidget } from '../types/widgets'
|
||||
import { BaseWidget } from './BaseWidget'
|
||||
import type { DrawWidgetOptions, WidgetEventOptions } from './BaseWidget'
|
||||
|
||||
/**
|
||||
* Widget for the Painter node canvas drawing tool.
|
||||
* This is a widget that only has a Vue widgets implementation.
|
||||
*/
|
||||
export class PainterWidget
|
||||
extends BaseWidget<IPainterWidget>
|
||||
implements IPainterWidget
|
||||
{
|
||||
override type = 'painter' as const
|
||||
|
||||
drawWidget(ctx: CanvasRenderingContext2D, options: DrawWidgetOptions): void {
|
||||
this.drawVueOnlyWarning(ctx, options, 'Painter')
|
||||
}
|
||||
|
||||
onClick(_options: WidgetEventOptions): void {
|
||||
// This is a widget that only has a Vue widgets implementation
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { FileUploadWidget } from './FileUploadWidget'
|
||||
import { GalleriaWidget } from './GalleriaWidget'
|
||||
import { GradientSliderWidget } from './GradientSliderWidget'
|
||||
import { ImageCompareWidget } from './ImageCompareWidget'
|
||||
import { PainterWidget } from './PainterWidget'
|
||||
import { ImageCropWidget } from './ImageCropWidget'
|
||||
import { KnobWidget } from './KnobWidget'
|
||||
import { LegacyWidget } from './LegacyWidget'
|
||||
@@ -58,6 +59,7 @@ export type WidgetTypeMap = {
|
||||
imagecrop: ImageCropWidget
|
||||
boundingbox: BoundingBoxWidget
|
||||
curve: CurveWidget
|
||||
painter: PainterWidget
|
||||
[key: string]: BaseWidget
|
||||
}
|
||||
|
||||
@@ -136,6 +138,8 @@ export function toConcreteWidget<TWidget extends IWidget | IBaseWidget>(
|
||||
return toClass(BoundingBoxWidget, narrowedWidget, node)
|
||||
case 'curve':
|
||||
return toClass(CurveWidget, narrowedWidget, node)
|
||||
case 'painter':
|
||||
return toClass(PainterWidget, narrowedWidget, node)
|
||||
default: {
|
||||
if (wrapLegacyWidgets) return toClass(LegacyWidget, widget, node)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
"error": "Error",
|
||||
"enter": "Enter",
|
||||
"enterSubgraph": "Enter Subgraph",
|
||||
"inSubgraph": "in subgraph '{name}'",
|
||||
"resizeFromBottomRight": "Resize from bottom-right corner",
|
||||
"resizeFromTopRight": "Resize from top-right corner",
|
||||
"resizeFromBottomLeft": "Resize from bottom-left corner",
|
||||
@@ -174,6 +175,7 @@
|
||||
"control_after_generate": "control after generate",
|
||||
"control_before_generate": "control before generate",
|
||||
"choose_file_to_upload": "choose file to upload",
|
||||
"uploadAlreadyInProgress": "Upload already in progress",
|
||||
"capture": "capture",
|
||||
"nodes": "Nodes",
|
||||
"nodesCount": "{count} nodes | {count} node | {count} nodes",
|
||||
@@ -449,6 +451,9 @@
|
||||
"import_failed": "Import Failed"
|
||||
},
|
||||
"warningTooltip": "This package may have compatibility issues with your current environment"
|
||||
},
|
||||
"packInstall": {
|
||||
"nodeIdRequired": "Node ID is required for installation"
|
||||
}
|
||||
},
|
||||
"importFailed": {
|
||||
@@ -1883,6 +1888,19 @@
|
||||
"unlockRatio": "Unlock aspect ratio",
|
||||
"custom": "Custom"
|
||||
},
|
||||
"painter": {
|
||||
"tool": "Tool",
|
||||
"brush": "Brush",
|
||||
"eraser": "Eraser",
|
||||
"size": "Cursor Size",
|
||||
"color": "Color Picker",
|
||||
"hardness": "Hardness",
|
||||
"width": "Width",
|
||||
"height": "Height",
|
||||
"background": "Background",
|
||||
"clear": "Clear",
|
||||
"uploadError": "Failed to upload painter image: {status} - {statusText}"
|
||||
},
|
||||
"boundingBox": {
|
||||
"x": "X",
|
||||
"y": "Y",
|
||||
@@ -3055,7 +3073,14 @@
|
||||
"openNodeManager": "Open Node Manager",
|
||||
"skipForNow": "Skip for Now",
|
||||
"installMissingNodes": "Install Missing Nodes",
|
||||
"replaceWarning": "This will permanently modify the workflow. Save a copy first if unsure."
|
||||
"replaceWarning": "This will permanently modify the workflow. Save a copy first if unsure.",
|
||||
"swapNodesGuide": "The following nodes can be automatically replaced with compatible alternatives.",
|
||||
"willBeReplacedBy": "This node will be replaced by:",
|
||||
"replaceNode": "Replace Node",
|
||||
"replaceAll": "Replace All",
|
||||
"unknownNode": "Unknown",
|
||||
"replaceAllWarning": "Replaces all available nodes in this group.",
|
||||
"swapNodesTitle": "Swap Nodes"
|
||||
},
|
||||
"rightSidePanel": {
|
||||
"togglePanel": "Toggle properties panel",
|
||||
@@ -3135,7 +3160,23 @@
|
||||
"errorHelpGithub": "submit a GitHub issue",
|
||||
"errorHelpSupport": "contact our support",
|
||||
"resetToDefault": "Reset to default",
|
||||
"resetAllParameters": "Reset all parameters"
|
||||
"resetAllParameters": "Reset all parameters",
|
||||
"missingNodePacks": {
|
||||
"title": "Missing Node Packs",
|
||||
"unsupportedTitle": "Unsupported Node Packs",
|
||||
"cloudMessage": "This workflow requires custom nodes not yet available on Comfy Cloud.",
|
||||
"ossMessage": "This workflow uses custom nodes you haven't installed yet.",
|
||||
"installAll": "Install All",
|
||||
"installNodePack": "Install node pack",
|
||||
"unknownPack": "Unknown pack",
|
||||
"installing": "Installing...",
|
||||
"installed": "Installed",
|
||||
"applyChanges": "Apply Changes",
|
||||
"searchInManager": "Search in Node Manager",
|
||||
"viewInManager": "View in Manager",
|
||||
"collapse": "Collapse",
|
||||
"expand": "Expand"
|
||||
}
|
||||
},
|
||||
"errorOverlay": {
|
||||
"errorCount": "{count} ERRORS | {count} ERROR | {count} ERRORS",
|
||||
|
||||
@@ -35,4 +35,29 @@ describe('AssetsListItem', () => {
|
||||
expect(wrapper.find('video').exists()).toBe(false)
|
||||
expect(wrapper.find('.icon-\\[lucide--play\\]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('emits preview-click when preview is clicked', async () => {
|
||||
const wrapper = mount(AssetsListItem, {
|
||||
props: {
|
||||
previewUrl: 'https://example.com/preview.jpg',
|
||||
previewAlt: 'image.png'
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('img').trigger('click')
|
||||
|
||||
expect(wrapper.emitted('preview-click')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('emits preview-click when fallback icon is clicked', async () => {
|
||||
const wrapper = mount(AssetsListItem, {
|
||||
props: {
|
||||
iconName: 'icon-[lucide--box]'
|
||||
}
|
||||
})
|
||||
|
||||
await wrapper.find('i').trigger('click')
|
||||
|
||||
expect(wrapper.emitted('preview-click')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -35,7 +35,11 @@
|
||||
:icon-class="iconClass"
|
||||
:icon-aria-label="iconAriaLabel"
|
||||
>
|
||||
<div v-if="previewUrl" class="relative size-full">
|
||||
<div
|
||||
v-if="previewUrl"
|
||||
class="relative size-full"
|
||||
@click="emit('preview-click')"
|
||||
>
|
||||
<template v-if="isVideoPreview">
|
||||
<video
|
||||
:src="previewUrl"
|
||||
@@ -53,7 +57,11 @@
|
||||
class="size-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="flex size-full items-center justify-center">
|
||||
<div
|
||||
v-else
|
||||
class="flex size-full items-center justify-center"
|
||||
@click="emit('preview-click')"
|
||||
>
|
||||
<i
|
||||
aria-hidden="true"
|
||||
:class="
|
||||
@@ -135,6 +143,7 @@ import VideoPlayOverlay from './VideoPlayOverlay.vue'
|
||||
|
||||
const emit = defineEmits<{
|
||||
'stack-toggle': []
|
||||
'preview-click': []
|
||||
}>()
|
||||
|
||||
const {
|
||||
|
||||
@@ -282,7 +282,6 @@ const getCheckoutTier = (
|
||||
|
||||
const getCheckoutAttributionForCloud =
|
||||
async (): Promise<CheckoutAttributionMetadata> => {
|
||||
// eslint-disable-next-line no-undef
|
||||
if (__DISTRIBUTION__ !== 'cloud') {
|
||||
return {}
|
||||
}
|
||||
|
||||
@@ -229,7 +229,12 @@ export function useNodeReplacement() {
|
||||
try {
|
||||
const placeholders = collectAllNodes(
|
||||
graph,
|
||||
(n) => !!n.has_errors && !!n.last_serialization
|
||||
(n) =>
|
||||
!!n.last_serialization &&
|
||||
!(
|
||||
(n.last_serialization.type ?? n.type ?? '') in
|
||||
LiteGraph.registered_node_types
|
||||
)
|
||||
)
|
||||
|
||||
for (const node of placeholders) {
|
||||
@@ -261,6 +266,10 @@ export function useNodeReplacement() {
|
||||
}
|
||||
replaceWithMapping(node, newNode, effectiveReplacement, nodeGraph, idx)
|
||||
|
||||
// Refresh Vue node data — replaceWithMapping bypasses graph.add()
|
||||
// so onNodeAdded must be called explicitly to update VueNodeData.
|
||||
nodeGraph.onNodeAdded?.(newNode)
|
||||
|
||||
if (!replacedTypes.includes(match.type)) {
|
||||
replacedTypes.push(match.type)
|
||||
}
|
||||
@@ -279,6 +288,19 @@ export function useNodeReplacement() {
|
||||
life: 3000
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to replace nodes:', error)
|
||||
if (replacedTypes.length > 0) {
|
||||
graph.updateExecutionOrder()
|
||||
graph.setDirtyCanvas(true, true)
|
||||
}
|
||||
toastStore.add({
|
||||
severity: 'error',
|
||||
summary: t('g.error', 'Error'),
|
||||
detail: t('nodeReplacement.replaceFailed', 'Failed to replace nodes'),
|
||||
life: 5000
|
||||
})
|
||||
return replacedTypes
|
||||
} finally {
|
||||
changeTracker?.afterChange()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { useMissingModelsDialog } from '@/composables/useMissingModelsDialog'
|
||||
import { useMissingNodesDialog } from '@/composables/useMissingNodesDialog'
|
||||
import { useDialogService } from '@/services/dialogService'
|
||||
import { useDomWidgetStore } from '@/stores/domWidgetStore'
|
||||
import { useExecutionErrorStore } from '@/stores/executionErrorStore'
|
||||
import { useWorkspaceStore } from '@/stores/workspaceStore'
|
||||
import { appendJsonExt } from '@/utils/formatUtil'
|
||||
|
||||
@@ -33,6 +34,7 @@ export const useWorkflowService = () => {
|
||||
const missingNodesDialog = useMissingNodesDialog()
|
||||
const workflowThumbnail = useWorkflowThumbnail()
|
||||
const domWidgetStore = useDomWidgetStore()
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
const workflowDraftStore = useWorkflowDraftStore()
|
||||
|
||||
async function getFilename(defaultName: string): Promise<string | null> {
|
||||
@@ -467,12 +469,15 @@ export const useWorkflowService = () => {
|
||||
const { missingNodeTypes, missingModels } = wf.pendingWarnings
|
||||
wf.pendingWarnings = null
|
||||
|
||||
if (
|
||||
missingNodeTypes?.length &&
|
||||
settingStore.get('Comfy.Workflow.ShowMissingNodesWarning')
|
||||
) {
|
||||
missingNodesDialog.show({ missingNodeTypes })
|
||||
if (missingNodeTypes?.length) {
|
||||
// Remove modal once Node Replacement is implemented in TabErrors.
|
||||
if (settingStore.get('Comfy.Workflow.ShowMissingNodesWarning')) {
|
||||
missingNodesDialog.show({ missingNodeTypes })
|
||||
}
|
||||
|
||||
executionErrorStore.surfaceMissingNodes(missingNodeTypes)
|
||||
}
|
||||
|
||||
if (
|
||||
missingModels &&
|
||||
settingStore.get('Comfy.Workflow.ShowMissingModelsWarning')
|
||||
|
||||
@@ -553,7 +553,6 @@ export type ComfyApiWorkflow = z.infer<typeof zComfyApiWorkflow>
|
||||
* where that definition is instantiated in the workflow.
|
||||
*
|
||||
* "def-A" → ["5", "10"] for each container node instantiating that subgraph definition.
|
||||
* @knipIgnoreUsedByStackedPR
|
||||
*/
|
||||
export function buildSubgraphExecutionPaths(
|
||||
rootNodes: ComfyNode[],
|
||||
|
||||
@@ -356,7 +356,8 @@ const hasAnyError = computed((): boolean => {
|
||||
error ||
|
||||
executionErrorStore.getNodeErrors(nodeLocatorId.value) ||
|
||||
(lgraphNode.value &&
|
||||
executionErrorStore.isContainerWithInternalError(lgraphNode.value))
|
||||
(executionErrorStore.isContainerWithInternalError(lgraphNode.value) ||
|
||||
executionErrorStore.isContainerWithMissingNode(lgraphNode.value)))
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -189,25 +189,36 @@ export function useNodeResize(
|
||||
}
|
||||
}
|
||||
|
||||
const cleanup = () => {
|
||||
if (!isResizing.value) return
|
||||
isResizing.value = false
|
||||
layoutStore.isResizingVueNodes.value = false
|
||||
resizeStartPointer.value = null
|
||||
resizeStartSize.value = null
|
||||
resizeStartPosition.value = null
|
||||
|
||||
// Stop tracking shift key state
|
||||
stopShiftSync()
|
||||
|
||||
stopMoveListen()
|
||||
stopUpListen()
|
||||
stopCancelListen()
|
||||
}
|
||||
|
||||
const handlePointerUp = (upEvent: PointerEvent) => {
|
||||
if (isResizing.value) {
|
||||
isResizing.value = false
|
||||
layoutStore.isResizingVueNodes.value = false
|
||||
resizeStartPointer.value = null
|
||||
resizeStartSize.value = null
|
||||
resizeStartPosition.value = null
|
||||
|
||||
// Stop tracking shift key state
|
||||
stopShiftSync()
|
||||
|
||||
target.releasePointerCapture(upEvent.pointerId)
|
||||
stopMoveListen()
|
||||
stopUpListen()
|
||||
try {
|
||||
target.releasePointerCapture(upEvent.pointerId)
|
||||
} catch {
|
||||
// Pointer capture may already be released
|
||||
}
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
const stopMoveListen = useEventListener('pointermove', handlePointerMove)
|
||||
const stopUpListen = useEventListener('pointerup', handlePointerUp)
|
||||
const stopCancelListen = useEventListener('pointercancel', cleanup)
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -92,9 +92,15 @@ watch([elementX, elementWidth, isOutside], ([x, width, outside]) => {
|
||||
}
|
||||
})
|
||||
|
||||
function isSingleImage(
|
||||
value: ImageCompareValue | string | undefined
|
||||
): value is string {
|
||||
return typeof value === 'string'
|
||||
}
|
||||
|
||||
const parsedValue = computed(() => {
|
||||
const value = props.widget.value
|
||||
return typeof value === 'string' ? null : value
|
||||
return isSingleImage(value) ? null : value
|
||||
})
|
||||
|
||||
const beforeBatchCount = computed(
|
||||
@@ -126,26 +132,26 @@ watch(
|
||||
|
||||
const beforeImage = computed(() => {
|
||||
const value = props.widget.value
|
||||
if (typeof value === 'string') return value
|
||||
if (isSingleImage(value)) return value
|
||||
return value?.beforeImages?.[beforeIndex.value] ?? ''
|
||||
})
|
||||
|
||||
const afterImage = computed(() => {
|
||||
const value = props.widget.value
|
||||
if (typeof value === 'string') return ''
|
||||
if (isSingleImage(value)) return ''
|
||||
return value?.afterImages?.[afterIndex.value] ?? ''
|
||||
})
|
||||
|
||||
const beforeAlt = computed(() => {
|
||||
const value = props.widget.value
|
||||
return typeof value === 'object' && value?.beforeAlt
|
||||
return !isSingleImage(value) && value?.beforeAlt
|
||||
? value.beforeAlt
|
||||
: 'Before image'
|
||||
})
|
||||
|
||||
const afterAlt = computed(() => {
|
||||
const value = props.widget.value
|
||||
return typeof value === 'object' && value?.afterAlt
|
||||
return !isSingleImage(value) && value?.afterAlt
|
||||
? value.afterAlt
|
||||
: 'After image'
|
||||
})
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
IBaseWidget,
|
||||
IWidgetOptions
|
||||
} from '@/lib/litegraph/src/types/widgets'
|
||||
import type { DrawWidgetOptions } from '@/lib/litegraph/src/widgets/BaseWidget'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
@@ -43,14 +44,51 @@ function scheduleDeferredImageRender() {
|
||||
})
|
||||
}
|
||||
|
||||
const renderPreview = (
|
||||
const TWO_PI = Math.PI * 2
|
||||
const SPINNER_ARC_LENGTH = Math.PI * 1.5
|
||||
|
||||
function renderUploadSpinner(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
node: LGraphNode,
|
||||
shiftY: number,
|
||||
computedHeight: number | undefined
|
||||
) {
|
||||
const dw = node.size[0]
|
||||
const dh = computedHeight ?? 220
|
||||
const centerX = dw / 2
|
||||
const centerY = shiftY + dh / 2
|
||||
const radius = 16
|
||||
const angle = ((Date.now() % 1000) / 1000) * TWO_PI
|
||||
|
||||
ctx.save()
|
||||
ctx.strokeStyle = LiteGraph.NODE_TEXT_COLOR
|
||||
ctx.lineWidth = 3
|
||||
ctx.lineCap = 'round'
|
||||
ctx.beginPath()
|
||||
ctx.arc(centerX, centerY, radius, angle, angle + SPINNER_ARC_LENGTH)
|
||||
ctx.stroke()
|
||||
ctx.restore()
|
||||
|
||||
// Schedule next frame to keep spinner animating continuously.
|
||||
// Only runs while node.isUploading is true (checked by caller).
|
||||
node.graph?.setDirtyCanvas(true)
|
||||
}
|
||||
|
||||
const renderPreview = (
|
||||
ctx: CanvasRenderingContext2D,
|
||||
node: LGraphNode,
|
||||
shiftY: number,
|
||||
computedHeight: number | undefined,
|
||||
imgs: HTMLImageElement[],
|
||||
width: number
|
||||
) => {
|
||||
if (!node.size) return
|
||||
|
||||
if (node.isUploading) {
|
||||
renderUploadSpinner(ctx, node, shiftY, computedHeight)
|
||||
return
|
||||
}
|
||||
|
||||
const canvas = useCanvasStore().getCanvas()
|
||||
const mouse = canvas.graph_mouse
|
||||
|
||||
@@ -64,7 +102,8 @@ const renderPreview = (
|
||||
node.pointerDown = null
|
||||
}
|
||||
|
||||
const imgs = node.imgs ?? []
|
||||
if (imgs.length === 0) return
|
||||
|
||||
let { imageIndex } = node
|
||||
const numImages = imgs.length
|
||||
if (numImages === 1 && !imageIndex) {
|
||||
@@ -75,7 +114,7 @@ const renderPreview = (
|
||||
const settingStore = useSettingStore()
|
||||
const allowImageSizeDraw = settingStore.get('Comfy.Node.AllowImageSizeDraw')
|
||||
const IMAGE_TEXT_SIZE_TEXT_HEIGHT = allowImageSizeDraw ? 15 : 0
|
||||
const dw = node.size[0]
|
||||
const dw = width
|
||||
const dh = computedHeight ? computedHeight - IMAGE_TEXT_SIZE_TEXT_HEIGHT : 0
|
||||
|
||||
if (imageIndex == null) {
|
||||
@@ -321,8 +360,29 @@ class ImagePreviewWidget extends BaseWidget {
|
||||
this.serialize = false
|
||||
}
|
||||
|
||||
override drawWidget(ctx: CanvasRenderingContext2D): void {
|
||||
renderPreview(ctx, this.node, this.y, this.computedHeight)
|
||||
override drawWidget(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
options: DrawWidgetOptions
|
||||
): void {
|
||||
const imgs = options.previewImages ?? this.node.imgs ?? []
|
||||
renderPreview(
|
||||
ctx,
|
||||
this.node,
|
||||
this.y,
|
||||
this.computedHeight,
|
||||
imgs,
|
||||
options.width
|
||||
)
|
||||
}
|
||||
|
||||
override createCopyForNode(node: LGraphNode): this {
|
||||
const copy = new ImagePreviewWidget(
|
||||
node,
|
||||
this.name,
|
||||
this.options as IWidgetOptions<string | object>
|
||||
) as this
|
||||
copy.value = this.value
|
||||
return copy
|
||||
}
|
||||
|
||||
override onPointerDown(pointer: CanvasPointer, node: LGraphNode): boolean {
|
||||
|
||||
@@ -54,12 +54,27 @@ export const useImageUploadWidget = () => {
|
||||
createAnnotatedPath(value, { rootFolder: image_folder })
|
||||
|
||||
// Setup file upload handling
|
||||
let rollback: (() => void) | undefined
|
||||
const { openFileSelection } = useNodeImageUpload(node, {
|
||||
allow_batch,
|
||||
fileFilter,
|
||||
accept,
|
||||
folder,
|
||||
onUploadStart: (files) => {
|
||||
if (files.length > 0) {
|
||||
const prev = fileComboWidget.value
|
||||
fileComboWidget.value = files[0].name
|
||||
rollback = () => {
|
||||
fileComboWidget.value = prev
|
||||
}
|
||||
}
|
||||
},
|
||||
onUploadError: () => {
|
||||
rollback?.()
|
||||
rollback = undefined
|
||||
},
|
||||
onUploadComplete: (output) => {
|
||||
rollback = undefined
|
||||
const annotated = output.map(formatPath)
|
||||
annotated.forEach((path) => {
|
||||
addToComboValues(fileComboWidget, path)
|
||||
@@ -88,6 +103,7 @@ export const useImageUploadWidget = () => {
|
||||
|
||||
// Add our own callback to the combo widget to render an image when it changes
|
||||
fileComboWidget.callback = function () {
|
||||
node.imgs = undefined
|
||||
nodeOutputStore.setNodeOutputs(node, String(fileComboWidget.value), {
|
||||
isAnimated
|
||||
})
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
|
||||
export const usePainterWidget = (): ComfyWidgetConstructorV2 => {
|
||||
return (node: LGraphNode, inputSpec: InputSpecV2): IBaseWidget => {
|
||||
return node.addWidget(
|
||||
'painter',
|
||||
inputSpec.name,
|
||||
(inputSpec.default as string) ?? '',
|
||||
null,
|
||||
{ serialize: true, canvasOnly: false }
|
||||
) as IBaseWidget
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,9 @@ const WidgetBoundingBox = defineAsyncComponent(
|
||||
const WidgetCurve = defineAsyncComponent(
|
||||
() => import('@/components/curve/WidgetCurve.vue')
|
||||
)
|
||||
const WidgetPainter = defineAsyncComponent(
|
||||
() => import('@/components/painter/WidgetPainter.vue')
|
||||
)
|
||||
|
||||
export const FOR_TESTING = {
|
||||
WidgetButton,
|
||||
@@ -186,6 +189,14 @@ const coreWidgetDefinitions: Array<[string, WidgetDefinition]> = [
|
||||
aliases: ['CURVE'],
|
||||
essential: false
|
||||
}
|
||||
],
|
||||
[
|
||||
'painter',
|
||||
{
|
||||
component: WidgetPainter,
|
||||
aliases: ['PAINTER'],
|
||||
essential: false
|
||||
}
|
||||
]
|
||||
]
|
||||
|
||||
@@ -217,7 +228,13 @@ export const shouldRenderAsVue = (widget: Partial<SafeWidgetData>): boolean => {
|
||||
return !widget.options?.canvasOnly && !!widget.type
|
||||
}
|
||||
|
||||
const EXPANDING_TYPES = ['textarea', 'markdown', 'load3D', 'curve'] as const
|
||||
const EXPANDING_TYPES = [
|
||||
'textarea',
|
||||
'markdown',
|
||||
'load3D',
|
||||
'curve',
|
||||
'painter'
|
||||
] as const
|
||||
|
||||
export function shouldExpand(type: string): boolean {
|
||||
const canonicalType = getCanonicalType(type)
|
||||
|
||||
@@ -27,12 +27,15 @@ import { useWorkflowService } from '@/platform/workflow/core/services/workflowSe
|
||||
import type { PendingWarnings } from '@/platform/workflow/management/stores/comfyWorkflow'
|
||||
import { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
|
||||
import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation'
|
||||
import type {
|
||||
ComfyApiWorkflow,
|
||||
ComfyWorkflowJSON,
|
||||
ModelFile,
|
||||
NodeId
|
||||
} from '@/platform/workflow/validation/schemas/workflowSchema'
|
||||
import {
|
||||
type ComfyApiWorkflow,
|
||||
type ComfyWorkflowJSON,
|
||||
type ModelFile,
|
||||
type NodeId,
|
||||
isSubgraphDefinition
|
||||
isSubgraphDefinition,
|
||||
buildSubgraphExecutionPaths
|
||||
} from '@/platform/workflow/validation/schemas/workflowSchema'
|
||||
import type {
|
||||
ExecutionErrorWsMessage,
|
||||
@@ -76,11 +79,12 @@ import type { ComfyExtension, MissingNodeType } from '@/types/comfy'
|
||||
import type { ExtensionManager } from '@/types/extensionTypes'
|
||||
import type { NodeExecutionId } from '@/types/nodeIdentification'
|
||||
import { graphToPrompt } from '@/utils/executionUtil'
|
||||
import type { MissingNodeTypeExtraInfo } from '@/workbench/extensions/manager/types/missingNodeErrorTypes'
|
||||
import { createMissingNodeTypeFromError } from '@/workbench/extensions/manager/utils/missingNodeErrorUtil'
|
||||
import { getCnrIdFromProperties } from '@/workbench/extensions/manager/utils/missingNodeErrorUtil'
|
||||
import { rescanAndSurfaceMissingNodes } from '@/composables/useMissingNodeScan'
|
||||
import { anyItemOverlapsRect } from '@/utils/mathUtil'
|
||||
import { collectAllNodes, forEachNode } from '@/utils/graphTraversalUtil'
|
||||
import {
|
||||
collectAllNodes,
|
||||
forEachNode,
|
||||
getNodeByExecutionId,
|
||||
triggerCallbackOnAllNodes
|
||||
} from '@/utils/graphTraversalUtil'
|
||||
@@ -1097,9 +1101,13 @@ export class ComfyApp {
|
||||
}
|
||||
|
||||
private showMissingNodesError(missingNodeTypes: MissingNodeType[]) {
|
||||
// Remove modal once Node Replacement is implemented in TabErrors.
|
||||
if (useSettingStore().get('Comfy.Workflow.ShowMissingNodesWarning')) {
|
||||
useMissingNodesDialog().show({ missingNodeTypes })
|
||||
}
|
||||
|
||||
const executionErrorStore = useExecutionErrorStore()
|
||||
executionErrorStore.surfaceMissingNodes(missingNodeTypes)
|
||||
}
|
||||
|
||||
async loadGraphData(
|
||||
@@ -1178,15 +1186,16 @@ export class ComfyApp {
|
||||
const embeddedModels: ModelFile[] = []
|
||||
|
||||
const nodeReplacementStore = useNodeReplacementStore()
|
||||
|
||||
await nodeReplacementStore.load()
|
||||
const collectMissingNodesAndModels = (
|
||||
nodes: ComfyWorkflowJSON['nodes'],
|
||||
path: string = ''
|
||||
pathPrefix: string = '',
|
||||
displayName: string = ''
|
||||
) => {
|
||||
if (!Array.isArray(nodes)) {
|
||||
console.warn(
|
||||
'Workflow nodes data is missing or invalid, skipping node processing',
|
||||
{ nodes, path }
|
||||
{ nodes, pathPrefix }
|
||||
)
|
||||
return
|
||||
}
|
||||
@@ -1195,9 +1204,23 @@ export class ComfyApp {
|
||||
if (!(n.type in LiteGraph.registered_node_types)) {
|
||||
const replacement = nodeReplacementStore.getReplacementFor(n.type)
|
||||
|
||||
// To access missing node information in the error tab
|
||||
// we collect the cnr_id and execution_id here.
|
||||
const cnrId = getCnrIdFromProperties(
|
||||
n.properties as Record<string, unknown> | undefined
|
||||
)
|
||||
|
||||
const executionId = pathPrefix
|
||||
? `${pathPrefix}:${n.id}`
|
||||
: String(n.id)
|
||||
|
||||
missingNodeTypes.push({
|
||||
type: n.type,
|
||||
...(path && { hint: `in subgraph '${path}'` }),
|
||||
nodeId: executionId,
|
||||
cnrId,
|
||||
...(displayName && {
|
||||
hint: t('g.inSubgraph', { name: displayName })
|
||||
}),
|
||||
isReplaceable: replacement !== null,
|
||||
replacement: replacement ?? undefined
|
||||
})
|
||||
@@ -1216,14 +1239,25 @@ export class ComfyApp {
|
||||
// Process nodes at the top level
|
||||
collectMissingNodesAndModels(graphData.nodes)
|
||||
|
||||
// Build map: subgraph definition UUID → full execution path prefix.
|
||||
// Handles arbitrary nesting depth (e.g. root node 11 → "11", node 14 in sg 11 → "11:14").
|
||||
const subgraphContainerIdMap = buildSubgraphExecutionPaths(
|
||||
graphData.nodes,
|
||||
graphData.definitions?.subgraphs ?? []
|
||||
)
|
||||
|
||||
// Process nodes in subgraphs
|
||||
if (graphData.definitions?.subgraphs) {
|
||||
for (const subgraph of graphData.definitions.subgraphs) {
|
||||
if (isSubgraphDefinition(subgraph)) {
|
||||
collectMissingNodesAndModels(
|
||||
subgraph.nodes,
|
||||
subgraph.name || subgraph.id
|
||||
)
|
||||
const paths = subgraphContainerIdMap.get(subgraph.id) ?? []
|
||||
for (const pathPrefix of paths) {
|
||||
collectMissingNodesAndModels(
|
||||
subgraph.nodes,
|
||||
pathPrefix,
|
||||
subgraph.name || subgraph.id
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1489,10 +1523,8 @@ export class ComfyApp {
|
||||
typeof error.response.error === 'object' &&
|
||||
error.response.error?.type === 'missing_node_type'
|
||||
) {
|
||||
const extraInfo = (error.response.error.extra_info ??
|
||||
{}) as MissingNodeTypeExtraInfo
|
||||
const missingNodeType = createMissingNodeTypeFromError(extraInfo)
|
||||
this.showMissingNodesError([missingNodeType])
|
||||
// Re-scan the full graph instead of using the server's single-node response.
|
||||
rescanAndSurfaceMissingNodes(this.rootGraph)
|
||||
} else if (
|
||||
!useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab') ||
|
||||
!(error instanceof PromptExecutionError)
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
LegacyWidget,
|
||||
LiteGraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type { NodeId } from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
IBaseWidget,
|
||||
IWidgetOptions
|
||||
@@ -15,7 +14,6 @@ import type {
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { useDomWidgetStore } from '@/stores/domWidgetStore'
|
||||
import { usePromotionStore } from '@/stores/promotionStore'
|
||||
import { useWidgetValueStore } from '@/stores/widgetValueStore'
|
||||
import { generateUUID } from '@/utils/formatUtil'
|
||||
|
||||
export interface BaseDOMWidget<
|
||||
@@ -152,18 +150,6 @@ abstract class BaseDOMWidgetImpl<V extends object | string>
|
||||
this.callback?.(this.value)
|
||||
}
|
||||
|
||||
override setNodeId(nodeId: NodeId): void {
|
||||
// Capture the DOM-resolved value before registration, since the base class
|
||||
// registers _state.value which is undefined for DOM widgets (their value
|
||||
// lives in the DOM element / options.getValue).
|
||||
const resolvedValue = this.value
|
||||
super.setNodeId(nodeId)
|
||||
const graphId = this.node.graph?.rootGraph.id
|
||||
if (!graphId) return
|
||||
const state = useWidgetValueStore().getWidget(graphId, nodeId, this.name)
|
||||
if (state) state.value = resolvedValue
|
||||
}
|
||||
|
||||
get margin(): number {
|
||||
return this.options.margin ?? BaseDOMWidgetImpl.DEFAULT_MARGIN
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { createTestingPinia } from '@pinia/testing'
|
||||
import { setActivePinia } from 'pinia'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { DOMWidgetImpl } from '@/scripts/domWidget'
|
||||
import { useWidgetValueStore } from '@/stores/widgetValueStore'
|
||||
|
||||
describe('DOMWidgetImpl store integration', () => {
|
||||
let graph: LGraph
|
||||
let node: LGraphNode
|
||||
let store: ReturnType<typeof useWidgetValueStore>
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createTestingPinia({ stubActions: false }))
|
||||
store = useWidgetValueStore()
|
||||
graph = new LGraph()
|
||||
node = new LGraphNode('TestNode')
|
||||
node.id = 1
|
||||
graph.add(node)
|
||||
})
|
||||
|
||||
it('registers DOM-resolved value in store via setNodeId', () => {
|
||||
const defaultValue = 'You are an expert image-generation engine.'
|
||||
const element = document.createElement('textarea')
|
||||
element.value = defaultValue
|
||||
|
||||
const widget = new DOMWidgetImpl({
|
||||
node,
|
||||
name: 'system_prompt',
|
||||
type: 'customtext',
|
||||
element,
|
||||
options: {
|
||||
getValue: () => element.value as string,
|
||||
setValue: (v: string) => {
|
||||
element.value = v
|
||||
const state = store.getWidget(graph.id, node.id, 'system_prompt')
|
||||
if (state) state.value = v
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
widget.setNodeId(node.id)
|
||||
|
||||
const state = store.getWidget(graph.id, node.id, 'system_prompt')
|
||||
expect(state?.value).toBe(defaultValue)
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@ import { useImageCompareWidget } from '@/renderer/extensions/vueNodes/widgets/co
|
||||
import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget'
|
||||
import { useIntWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useIntWidget'
|
||||
import { useMarkdownWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useMarkdownWidget'
|
||||
import { usePainterWidget } from '@/renderer/extensions/vueNodes/widgets/composables/usePainterWidget'
|
||||
import { useStringWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useStringWidget'
|
||||
import { useTextareaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useTextareaWidget'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
@@ -306,6 +307,7 @@ export const ComfyWidgets = {
|
||||
BOUNDING_BOX: transformWidgetConstructorV2ToV1(useBoundingBoxWidget()),
|
||||
CHART: transformWidgetConstructorV2ToV1(useChartWidget()),
|
||||
GALLERIA: transformWidgetConstructorV2ToV1(useGalleriaWidget()),
|
||||
PAINTER: transformWidgetConstructorV2ToV1(usePainterWidget()),
|
||||
TEXTAREA: transformWidgetConstructorV2ToV1(useTextareaWidget()),
|
||||
CURVE: transformWidgetConstructorV2ToV1(useCurveWidget()),
|
||||
...dynamicWidgets
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
|
||||
import { st } from '@/i18n'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
|
||||
import { app } from '@/scripts/app'
|
||||
import type {
|
||||
@@ -10,8 +13,13 @@ import type {
|
||||
PromptError
|
||||
} from '@/schemas/apiSchema'
|
||||
import type { NodeId } from '@/platform/workflow/validation/schemas/workflowSchema'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
getAncestorExecutionIds,
|
||||
getParentExecutionIds
|
||||
} from '@/types/nodeIdentification'
|
||||
import type { NodeExecutionId, NodeLocatorId } from '@/types/nodeIdentification'
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
import {
|
||||
executionIdToNodeLocatorId,
|
||||
forEachNode,
|
||||
@@ -19,13 +27,50 @@ import {
|
||||
getExecutionIdByNode
|
||||
} from '@/utils/graphTraversalUtil'
|
||||
|
||||
/**
|
||||
* Store dedicated to execution error state management.
|
||||
*
|
||||
* Extracted from executionStore to separate error-related concerns
|
||||
* (state, computed properties, graph flag propagation, overlay UI)
|
||||
* from execution flow management (progress, queuing, events).
|
||||
*/
|
||||
interface MissingNodesError {
|
||||
message: string
|
||||
nodeTypes: MissingNodeType[]
|
||||
}
|
||||
|
||||
function clearAllNodeErrorFlags(rootGraph: LGraph): void {
|
||||
forEachNode(rootGraph, (node) => {
|
||||
node.has_errors = false
|
||||
if (node.inputs) {
|
||||
for (const slot of node.inputs) {
|
||||
slot.hasErrors = false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function markNodeSlotErrors(node: LGraphNode, nodeError: NodeError): void {
|
||||
if (!node.inputs) return
|
||||
for (const error of nodeError.errors) {
|
||||
const slotName = error.extra_info?.input_name
|
||||
if (!slotName) continue
|
||||
const slot = node.inputs.find((s) => s.name === slotName)
|
||||
if (slot) slot.hasErrors = true
|
||||
}
|
||||
}
|
||||
|
||||
function applyNodeError(
|
||||
rootGraph: LGraph,
|
||||
executionId: NodeExecutionId,
|
||||
nodeError: NodeError
|
||||
): void {
|
||||
const node = getNodeByExecutionId(rootGraph, executionId)
|
||||
if (!node) return
|
||||
|
||||
node.has_errors = true
|
||||
markNodeSlotErrors(node, nodeError)
|
||||
|
||||
for (const parentId of getParentExecutionIds(executionId)) {
|
||||
const parentNode = getNodeByExecutionId(rootGraph, parentId)
|
||||
if (parentNode) parentNode.has_errors = true
|
||||
}
|
||||
}
|
||||
|
||||
/** Execution error state: node errors, runtime errors, prompt errors, and missing nodes. */
|
||||
export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const canvasStore = useCanvasStore()
|
||||
@@ -33,6 +78,7 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
const lastNodeErrors = ref<Record<NodeId, NodeError> | null>(null)
|
||||
const lastExecutionError = ref<ExecutionErrorWsMessage | null>(null)
|
||||
const lastPromptError = ref<PromptError | null>(null)
|
||||
const missingNodesError = ref<MissingNodesError | null>(null)
|
||||
|
||||
const isErrorOverlayOpen = ref(false)
|
||||
|
||||
@@ -49,6 +95,7 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
lastExecutionError.value = null
|
||||
lastPromptError.value = null
|
||||
lastNodeErrors.value = null
|
||||
missingNodesError.value = null
|
||||
isErrorOverlayOpen.value = false
|
||||
}
|
||||
|
||||
@@ -57,6 +104,59 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
lastPromptError.value = null
|
||||
}
|
||||
|
||||
/** Set missing node types and open the error overlay if the Errors tab is enabled. */
|
||||
function surfaceMissingNodes(types: MissingNodeType[]) {
|
||||
setMissingNodeTypes(types)
|
||||
if (useSettingStore().get('Comfy.RightSidePanel.ShowErrorsTab')) {
|
||||
showErrorOverlay()
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove specific node types from the missing nodes list (e.g. after replacement). */
|
||||
function removeMissingNodesByType(typesToRemove: string[]) {
|
||||
if (!missingNodesError.value) return
|
||||
const removeSet = new Set(typesToRemove)
|
||||
const remaining = missingNodesError.value.nodeTypes.filter((node) => {
|
||||
const nodeType = typeof node === 'string' ? node : node.type
|
||||
return !removeSet.has(nodeType)
|
||||
})
|
||||
setMissingNodeTypes(remaining)
|
||||
}
|
||||
|
||||
function setMissingNodeTypes(types: MissingNodeType[]) {
|
||||
if (!types.length) {
|
||||
missingNodesError.value = null
|
||||
return
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
const uniqueTypes = types.filter((node) => {
|
||||
// For string entries (group nodes), deduplicate by the string itself.
|
||||
// For object entries, prefer nodeId so multiple instances of the same
|
||||
// type are kept as separate rows; fall back to type if nodeId is absent.
|
||||
const isString = typeof node === 'string'
|
||||
let key: string
|
||||
if (isString) {
|
||||
key = node
|
||||
} else if (node.nodeId != null) {
|
||||
key = String(node.nodeId)
|
||||
} else {
|
||||
key = node.type
|
||||
}
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
})
|
||||
missingNodesError.value = {
|
||||
message: isCloud
|
||||
? st(
|
||||
'rightSidePanel.missingNodePacks.unsupportedTitle',
|
||||
'Unsupported Node Packs'
|
||||
)
|
||||
: st('rightSidePanel.missingNodePacks.title', 'Missing Node Packs'),
|
||||
nodeTypes: uniqueTypes
|
||||
}
|
||||
}
|
||||
|
||||
const lastExecutionErrorNodeLocatorId = computed(() => {
|
||||
const err = lastExecutionError.value
|
||||
if (!err) return null
|
||||
@@ -81,9 +181,16 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
() => !!lastNodeErrors.value && Object.keys(lastNodeErrors.value).length > 0
|
||||
)
|
||||
|
||||
/** Whether any error (node validation, runtime execution, or prompt-level) is present */
|
||||
/** Whether any missing node types are present in the current workflow */
|
||||
const hasMissingNodes = computed(() => !!missingNodesError.value)
|
||||
|
||||
/** Whether any error (node validation, runtime execution, prompt-level, or missing nodes) is present */
|
||||
const hasAnyError = computed(
|
||||
() => hasExecutionError.value || hasPromptError.value || hasNodeError.value
|
||||
() =>
|
||||
hasExecutionError.value ||
|
||||
hasPromptError.value ||
|
||||
hasNodeError.value ||
|
||||
hasMissingNodes.value
|
||||
)
|
||||
|
||||
const allErrorExecutionIds = computed<string[]>(() => {
|
||||
@@ -116,13 +223,19 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
/** Count of runtime execution errors (0 or 1) */
|
||||
const executionErrorCount = computed(() => (lastExecutionError.value ? 1 : 0))
|
||||
|
||||
/** Count of missing node errors (0 or 1) */
|
||||
const missingNodeCount = computed(() => (missingNodesError.value ? 1 : 0))
|
||||
|
||||
/** Total count of all individual errors */
|
||||
const totalErrorCount = computed(
|
||||
() =>
|
||||
promptErrorCount.value + nodeErrorCount.value + executionErrorCount.value
|
||||
promptErrorCount.value +
|
||||
nodeErrorCount.value +
|
||||
executionErrorCount.value +
|
||||
missingNodeCount.value
|
||||
)
|
||||
|
||||
/** Pre-computed Set of graph node IDs (as strings) that have errors in the current graph scope. */
|
||||
/** Graph node IDs (as strings) that have errors in the current graph scope. */
|
||||
const activeGraphErrorNodeIds = computed<Set<string>>(() => {
|
||||
const ids = new Set<string>()
|
||||
if (!app.rootGraph) return ids
|
||||
@@ -150,6 +263,44 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
return ids
|
||||
})
|
||||
|
||||
/**
|
||||
* Set of all execution ID prefixes derived from missing node execution IDs,
|
||||
* including the missing nodes themselves.
|
||||
*
|
||||
* Example: missing node at "65:70:63" → Set { "65", "65:70", "65:70:63" }
|
||||
*/
|
||||
const missingAncestorExecutionIds = computed<Set<NodeExecutionId>>(() => {
|
||||
const ids = new Set<NodeExecutionId>()
|
||||
const error = missingNodesError.value
|
||||
if (!error) return ids
|
||||
|
||||
for (const nodeType of error.nodeTypes) {
|
||||
if (typeof nodeType === 'string') continue
|
||||
if (nodeType.nodeId == null) continue
|
||||
for (const id of getAncestorExecutionIds(String(nodeType.nodeId))) {
|
||||
ids.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
})
|
||||
|
||||
const activeMissingNodeGraphIds = computed<Set<string>>(() => {
|
||||
const ids = new Set<string>()
|
||||
if (!app.rootGraph) return ids
|
||||
|
||||
const activeGraph = canvasStore.currentGraph ?? app.rootGraph
|
||||
|
||||
for (const executionId of missingAncestorExecutionIds.value) {
|
||||
const graphNode = getNodeByExecutionId(app.rootGraph, executionId)
|
||||
if (graphNode?.graph === activeGraph) {
|
||||
ids.add(String(graphNode.id))
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
})
|
||||
|
||||
/** Map of node errors indexed by locator ID. */
|
||||
const nodeErrorsByLocatorId = computed<Record<NodeLocatorId, NodeError>>(
|
||||
() => {
|
||||
@@ -196,15 +347,11 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
*/
|
||||
const errorAncestorExecutionIds = computed<Set<NodeExecutionId>>(() => {
|
||||
const ids = new Set<NodeExecutionId>()
|
||||
|
||||
for (const executionId of allErrorExecutionIds.value) {
|
||||
const parts = executionId.split(':')
|
||||
// Add every prefix including the full ID (error leaf node itself)
|
||||
for (let i = 1; i <= parts.length; i++) {
|
||||
ids.add(parts.slice(0, i).join(':'))
|
||||
for (const id of getAncestorExecutionIds(executionId)) {
|
||||
ids.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
return ids
|
||||
})
|
||||
|
||||
@@ -216,59 +363,26 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
return errorAncestorExecutionIds.value.has(execId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update node and slot error flags when validation errors change.
|
||||
* Propagates errors up subgraph chains.
|
||||
*/
|
||||
watch(lastNodeErrors, () => {
|
||||
if (!app.rootGraph) return
|
||||
/** True if the node has a missing node inside it at any nesting depth. */
|
||||
function isContainerWithMissingNode(node: LGraphNode): boolean {
|
||||
if (!app.rootGraph) return false
|
||||
const execId = getExecutionIdByNode(app.rootGraph, node)
|
||||
if (!execId) return false
|
||||
return missingAncestorExecutionIds.value.has(execId)
|
||||
}
|
||||
|
||||
// Clear all error flags
|
||||
forEachNode(app.rootGraph, (node) => {
|
||||
node.has_errors = false
|
||||
if (node.inputs) {
|
||||
for (const slot of node.inputs) {
|
||||
slot.hasErrors = false
|
||||
}
|
||||
}
|
||||
})
|
||||
watch(lastNodeErrors, () => {
|
||||
const rootGraph = app.rootGraph
|
||||
if (!rootGraph) return
|
||||
|
||||
clearAllNodeErrorFlags(rootGraph)
|
||||
|
||||
if (!lastNodeErrors.value) return
|
||||
|
||||
// Set error flags on nodes and slots
|
||||
for (const [executionId, nodeError] of Object.entries(
|
||||
lastNodeErrors.value
|
||||
)) {
|
||||
const node = getNodeByExecutionId(app.rootGraph, executionId)
|
||||
if (!node) continue
|
||||
|
||||
node.has_errors = true
|
||||
|
||||
// Mark input slots with errors
|
||||
if (node.inputs) {
|
||||
for (const error of nodeError.errors) {
|
||||
const slotName = error.extra_info?.input_name
|
||||
if (!slotName) continue
|
||||
|
||||
const slot = node.inputs.find((s) => s.name === slotName)
|
||||
if (slot) {
|
||||
slot.hasErrors = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate errors to parent subgraph nodes
|
||||
const parts = executionId.split(':')
|
||||
for (let i = parts.length - 1; i > 0; i--) {
|
||||
const parentExecutionId = parts.slice(0, i).join(':')
|
||||
const parentNode = getNodeByExecutionId(
|
||||
app.rootGraph,
|
||||
parentExecutionId
|
||||
)
|
||||
if (parentNode) {
|
||||
parentNode.has_errors = true
|
||||
}
|
||||
}
|
||||
applyNodeError(rootGraph, executionId, nodeError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -277,6 +391,7 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
lastNodeErrors,
|
||||
lastExecutionError,
|
||||
lastPromptError,
|
||||
missingNodesError,
|
||||
|
||||
// Clearing
|
||||
clearAllErrors,
|
||||
@@ -291,16 +406,23 @@ export const useExecutionErrorStore = defineStore('executionError', () => {
|
||||
hasExecutionError,
|
||||
hasPromptError,
|
||||
hasNodeError,
|
||||
hasMissingNodes,
|
||||
hasAnyError,
|
||||
allErrorExecutionIds,
|
||||
totalErrorCount,
|
||||
lastExecutionErrorNodeId,
|
||||
activeGraphErrorNodeIds,
|
||||
activeMissingNodeGraphIds,
|
||||
|
||||
// Missing node actions
|
||||
setMissingNodeTypes,
|
||||
surfaceMissingNodes,
|
||||
removeMissingNodesByType,
|
||||
|
||||
// Lookup helpers
|
||||
getNodeErrors,
|
||||
slotHasError,
|
||||
errorAncestorExecutionIds,
|
||||
isContainerWithInternalError
|
||||
isContainerWithInternalError,
|
||||
isContainerWithMissingNode
|
||||
}
|
||||
})
|
||||
|
||||
@@ -345,3 +345,100 @@ describe('useExecutionErrorStore - Node Error Lookups', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('useExecutionErrorStore - setMissingNodeTypes', () => {
|
||||
let store: ReturnType<typeof useExecutionErrorStore>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
setActivePinia(createTestingPinia({ stubActions: false }))
|
||||
store = useExecutionErrorStore()
|
||||
})
|
||||
|
||||
it('clears missingNodesError when called with an empty array', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeA' }])
|
||||
store.setMissingNodeTypes([])
|
||||
expect(store.missingNodesError).toBeNull()
|
||||
})
|
||||
|
||||
it('hasMissingNodes is false when error is null', () => {
|
||||
store.setMissingNodeTypes([])
|
||||
expect(store.hasMissingNodes).toBe(false)
|
||||
})
|
||||
|
||||
it('hasMissingNodes is true after setting non-empty types', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeA' }])
|
||||
expect(store.hasMissingNodes).toBe(true)
|
||||
})
|
||||
|
||||
it('deduplicates string entries by value', () => {
|
||||
store.setMissingNodeTypes(['GroupNode', 'GroupNode', 'OtherGroup'])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(2)
|
||||
expect(store.missingNodesError?.nodeTypes).toEqual([
|
||||
'GroupNode',
|
||||
'OtherGroup'
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a single string entry unchanged', () => {
|
||||
store.setMissingNodeTypes(['GroupNode'])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('deduplicates object entries with the same nodeId', () => {
|
||||
store.setMissingNodeTypes([
|
||||
{ type: 'NodeA', nodeId: 1 },
|
||||
{ type: 'NodeA', nodeId: 1 }
|
||||
])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps object entries with different nodeIds even if same type', () => {
|
||||
store.setMissingNodeTypes([
|
||||
{ type: 'NodeA', nodeId: 1 },
|
||||
{ type: 'NodeA', nodeId: 2 }
|
||||
])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('deduplicates object entries by type when nodeId is absent', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeB' }, { type: 'NodeB' }])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps distinct types when nodeId is absent', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeB' }, { type: 'NodeC' }])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('treats absent nodeId the same as type-only key (falls back to type)', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeD' }, { type: 'NodeD' }])
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('handles a mix of string and object entries correctly', () => {
|
||||
store.setMissingNodeTypes([
|
||||
'GroupNode',
|
||||
'GroupNode', // string dup
|
||||
{ type: 'NodeA', nodeId: 1 },
|
||||
{ type: 'NodeA', nodeId: 1 }, // object dup by nodeId
|
||||
{ type: 'NodeA', nodeId: 2 }, // same type, different nodeId → kept
|
||||
{ type: 'NodeB' },
|
||||
{ type: 'NodeB' } // object dup by type
|
||||
])
|
||||
// Unique: 'GroupNode', {NodeA,1}, {NodeA,2}, {NodeB} → 4
|
||||
expect(store.missingNodesError?.nodeTypes).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('stores a non-empty message string in missingNodesError', () => {
|
||||
store.setMissingNodeTypes([{ type: 'NodeA' }])
|
||||
expect(typeof store.missingNodesError?.message).toBe('string')
|
||||
expect(store.missingNodesError!.message.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('stores the deduplicated nodeTypes array in missingNodesError', () => {
|
||||
const input = [{ type: 'NodeA' }, { type: 'NodeB' }]
|
||||
store.setMissingNodeTypes(input)
|
||||
expect(store.missingNodesError?.nodeTypes).toEqual(input)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -190,78 +190,28 @@ describe('useModelToNodeStore', () => {
|
||||
expect(provider?.key).toBe('')
|
||||
})
|
||||
|
||||
it('should return provider for new extension model types', () => {
|
||||
const modelToNodeStore = useModelToNodeStore()
|
||||
modelToNodeStore.registerDefaults()
|
||||
it.each([
|
||||
['sam2', 'DownloadAndLoadSAM2Model', 'model'],
|
||||
['sams', 'SAMLoader', 'model_name'],
|
||||
['ipadapter', 'IPAdapterModelLoader', 'ipadapter_file'],
|
||||
['depthanything', 'DownloadAndLoadDepthAnythingV2Model', 'model'],
|
||||
['ultralytics/bbox', 'UltralyticsDetectorProvider', 'model_name'],
|
||||
['ultralytics/segm', 'UltralyticsDetectorProvider', 'model_name'],
|
||||
['FlashVSR', 'FlashVSRNode', ''],
|
||||
['FlashVSR-v1.1', 'FlashVSRNode', ''],
|
||||
['segformer_b2_clothes', 'LS_LoadSegformerModel', 'model_name'],
|
||||
['segformer_b3_fashion', 'LS_LoadSegformerModel', 'model_name']
|
||||
])(
|
||||
'should return correct provider for %s',
|
||||
(modelType, expectedNodeName, expectedKey) => {
|
||||
const modelToNodeStore = useModelToNodeStore()
|
||||
modelToNodeStore.registerDefaults()
|
||||
|
||||
// SAM2
|
||||
const sam2Provider = modelToNodeStore.getNodeProvider('sam2')
|
||||
expect(sam2Provider?.nodeDef?.name).toBe('DownloadAndLoadSAM2Model')
|
||||
expect(sam2Provider?.key).toBe('model')
|
||||
|
||||
// SAMLoader (original SAM)
|
||||
const samsProvider = modelToNodeStore.getNodeProvider('sams')
|
||||
expect(samsProvider?.nodeDef?.name).toBe('SAMLoader')
|
||||
expect(samsProvider?.key).toBe('model_name')
|
||||
|
||||
// IP-Adapter
|
||||
const ipadapterProvider = modelToNodeStore.getNodeProvider('ipadapter')
|
||||
expect(ipadapterProvider?.nodeDef?.name).toBe('IPAdapterModelLoader')
|
||||
expect(ipadapterProvider?.key).toBe('ipadapter_file')
|
||||
|
||||
// DepthAnything
|
||||
const depthProvider = modelToNodeStore.getNodeProvider('depthanything')
|
||||
expect(depthProvider?.nodeDef?.name).toBe(
|
||||
'DownloadAndLoadDepthAnythingV2Model'
|
||||
)
|
||||
expect(depthProvider?.key).toBe('model')
|
||||
})
|
||||
|
||||
it('should use hierarchical fallback for ultralytics subcategories', () => {
|
||||
const modelToNodeStore = useModelToNodeStore()
|
||||
modelToNodeStore.registerDefaults()
|
||||
|
||||
// ultralytics/bbox should fall back to ultralytics
|
||||
const bboxProvider = modelToNodeStore.getNodeProvider('ultralytics/bbox')
|
||||
expect(bboxProvider?.nodeDef?.name).toBe('UltralyticsDetectorProvider')
|
||||
expect(bboxProvider?.key).toBe('model_name')
|
||||
|
||||
// ultralytics/segm should also fall back to ultralytics
|
||||
const segmProvider = modelToNodeStore.getNodeProvider('ultralytics/segm')
|
||||
expect(segmProvider?.nodeDef?.name).toBe('UltralyticsDetectorProvider')
|
||||
})
|
||||
|
||||
it('should return provider for FlashVSR nodes with empty key (auto-load)', () => {
|
||||
const modelToNodeStore = useModelToNodeStore()
|
||||
modelToNodeStore.registerDefaults()
|
||||
|
||||
const flashVSRProvider = modelToNodeStore.getNodeProvider('FlashVSR')
|
||||
expect(flashVSRProvider?.nodeDef?.name).toBe('FlashVSRNode')
|
||||
expect(flashVSRProvider?.key).toBe('')
|
||||
|
||||
const flashVSR11Provider =
|
||||
modelToNodeStore.getNodeProvider('FlashVSR-v1.1')
|
||||
expect(flashVSR11Provider?.nodeDef?.name).toBe('FlashVSRNode')
|
||||
expect(flashVSR11Provider?.key).toBe('')
|
||||
})
|
||||
|
||||
it('should return provider for segformer models', () => {
|
||||
const modelToNodeStore = useModelToNodeStore()
|
||||
modelToNodeStore.registerDefaults()
|
||||
|
||||
const segformerB2Provider = modelToNodeStore.getNodeProvider(
|
||||
'segformer_b2_clothes'
|
||||
)
|
||||
expect(segformerB2Provider?.nodeDef?.name).toBe('LS_LoadSegformerModel')
|
||||
expect(segformerB2Provider?.key).toBe('model_name')
|
||||
|
||||
const segformerB3FashionProvider = modelToNodeStore.getNodeProvider(
|
||||
'segformer_b3_fashion'
|
||||
)
|
||||
expect(segformerB3FashionProvider?.nodeDef?.name).toBe(
|
||||
'LS_LoadSegformerModel'
|
||||
)
|
||||
})
|
||||
const provider = modelToNodeStore.getNodeProvider(modelType)
|
||||
expect(provider?.nodeDef?.name).toBe(expectedNodeName)
|
||||
expect(provider?.key).toBe(expectedKey)
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
describe('getAllNodeProviders', () => {
|
||||
|
||||
@@ -334,7 +334,7 @@ describe('useQueueStore', () => {
|
||||
})
|
||||
|
||||
describe('update() - sorting', () => {
|
||||
it('should sort tasks by queueIndex descending', async () => {
|
||||
it('should sort tasks by job.priority descending', async () => {
|
||||
const job1 = createHistoryJob(1, 'hist-1')
|
||||
const job2 = createHistoryJob(5, 'hist-2')
|
||||
const job3 = createHistoryJob(3, 'hist-3')
|
||||
@@ -344,9 +344,9 @@ describe('useQueueStore', () => {
|
||||
|
||||
await store.update()
|
||||
|
||||
expect(store.historyTasks[0].queueIndex).toBe(5)
|
||||
expect(store.historyTasks[1].queueIndex).toBe(3)
|
||||
expect(store.historyTasks[2].queueIndex).toBe(1)
|
||||
expect(store.historyTasks[0].job.priority).toBe(5)
|
||||
expect(store.historyTasks[1].job.priority).toBe(3)
|
||||
expect(store.historyTasks[2].job.priority).toBe(1)
|
||||
})
|
||||
|
||||
it('should preserve API sort order for pending tasks', async () => {
|
||||
@@ -363,14 +363,14 @@ describe('useQueueStore', () => {
|
||||
|
||||
await store.update()
|
||||
|
||||
expect(store.pendingTasks[0].queueIndex).toBe(15)
|
||||
expect(store.pendingTasks[1].queueIndex).toBe(12)
|
||||
expect(store.pendingTasks[2].queueIndex).toBe(10)
|
||||
expect(store.pendingTasks[0].job.priority).toBe(15)
|
||||
expect(store.pendingTasks[1].job.priority).toBe(12)
|
||||
expect(store.pendingTasks[2].job.priority).toBe(10)
|
||||
})
|
||||
})
|
||||
|
||||
describe('update() - queue index collision (THE BUG FIX)', () => {
|
||||
it('should NOT confuse different prompts with same queueIndex', async () => {
|
||||
it('should NOT confuse different prompts with same job.priority', async () => {
|
||||
const hist1 = createHistoryJob(50, 'prompt-uuid-aaa')
|
||||
|
||||
mockGetQueue.mockResolvedValue({ Running: [], Pending: [] })
|
||||
@@ -387,10 +387,10 @@ describe('useQueueStore', () => {
|
||||
|
||||
expect(store.historyTasks).toHaveLength(1)
|
||||
expect(store.historyTasks[0].jobId).toBe('prompt-uuid-bbb')
|
||||
expect(store.historyTasks[0].queueIndex).toBe(51)
|
||||
expect(store.historyTasks[0].job.priority).toBe(51)
|
||||
})
|
||||
|
||||
it('should correctly reconcile when queueIndex is reused', async () => {
|
||||
it('should correctly reconcile when job.priority is reused', async () => {
|
||||
const hist1 = createHistoryJob(100, 'first-prompt-at-100')
|
||||
const hist2 = createHistoryJob(99, 'prompt-at-99')
|
||||
|
||||
@@ -412,7 +412,7 @@ describe('useQueueStore', () => {
|
||||
expect(jobIds).not.toContain('first-prompt-at-100')
|
||||
})
|
||||
|
||||
it('should handle multiple queueIndex collisions simultaneously', async () => {
|
||||
it('should handle multiple job.priority collisions simultaneously', async () => {
|
||||
const hist1 = createHistoryJob(10, 'old-at-10')
|
||||
const hist2 = createHistoryJob(20, 'old-at-20')
|
||||
const hist3 = createHistoryJob(30, 'keep-at-30')
|
||||
@@ -563,9 +563,9 @@ describe('useQueueStore', () => {
|
||||
await store.update()
|
||||
|
||||
expect(store.historyTasks).toHaveLength(3)
|
||||
expect(store.historyTasks[0].queueIndex).toBe(10)
|
||||
expect(store.historyTasks[1].queueIndex).toBe(9)
|
||||
expect(store.historyTasks[2].queueIndex).toBe(8)
|
||||
expect(store.historyTasks[0].job.priority).toBe(10)
|
||||
expect(store.historyTasks[1].job.priority).toBe(9)
|
||||
expect(store.historyTasks[2].job.priority).toBe(8)
|
||||
})
|
||||
|
||||
it('should respect maxHistoryItems when combining new and existing', async () => {
|
||||
@@ -589,7 +589,7 @@ describe('useQueueStore', () => {
|
||||
await store.update()
|
||||
|
||||
expect(store.historyTasks).toHaveLength(5)
|
||||
expect(store.historyTasks[0].queueIndex).toBe(23)
|
||||
expect(store.historyTasks[0].job.priority).toBe(23)
|
||||
})
|
||||
|
||||
it('should handle maxHistoryItems = 0', async () => {
|
||||
@@ -619,7 +619,7 @@ describe('useQueueStore', () => {
|
||||
await store.update()
|
||||
|
||||
expect(store.historyTasks).toHaveLength(1)
|
||||
expect(store.historyTasks[0].queueIndex).toBe(10)
|
||||
expect(store.historyTasks[0].job.priority).toBe(10)
|
||||
})
|
||||
|
||||
it('should dynamically adjust when maxHistoryItems changes', async () => {
|
||||
|
||||
@@ -312,10 +312,6 @@ export class TaskItemImpl {
|
||||
return this.jobId + this.displayStatus
|
||||
}
|
||||
|
||||
get queueIndex() {
|
||||
return this.job.priority
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id
|
||||
}
|
||||
@@ -500,7 +496,7 @@ export const useQueueStore = defineStore('queue', () => {
|
||||
)
|
||||
|
||||
const lastHistoryQueueIndex = computed<number>(() =>
|
||||
historyTasks.value.length ? historyTasks.value[0].queueIndex : -1
|
||||
historyTasks.value.length ? historyTasks.value[0].job.priority : -1
|
||||
)
|
||||
|
||||
const hasPendingTasks = computed<boolean>(() => pendingTasks.value.length > 0)
|
||||
|
||||
@@ -90,6 +90,8 @@ export type MissingNodeType =
|
||||
// Primarily used by group nodes.
|
||||
| {
|
||||
type: string
|
||||
nodeId?: string | number
|
||||
cnrId?: string
|
||||
hint?: string
|
||||
action?: {
|
||||
text: string
|
||||
|
||||
2
src/types/litegraph-augmentation.d.ts
vendored
2
src/types/litegraph-augmentation.d.ts
vendored
@@ -175,6 +175,8 @@ declare module '@/lib/litegraph/src/litegraph' {
|
||||
videoContainer?: HTMLElement
|
||||
/** Whether the node's preview media is loading */
|
||||
isLoading?: boolean
|
||||
/** Whether a file is being uploaded to this node */
|
||||
isUploading?: boolean
|
||||
/** The content type of the node's preview media */
|
||||
previewMediaType?: 'image' | 'video' | 'audio' | 'model'
|
||||
/** If true, output images are stored but not rendered below the node */
|
||||
|
||||
@@ -126,7 +126,6 @@ export function createNodeExecutionId(nodeIds: NodeId[]): NodeExecutionId {
|
||||
* Returns all ancestor execution IDs for a given execution ID, including itself.
|
||||
*
|
||||
* Example: "65:70:63" → ["65", "65:70", "65:70:63"]
|
||||
* @knipIgnoreUsedByStackedPR
|
||||
*/
|
||||
export function getAncestorExecutionIds(
|
||||
executionId: string | NodeExecutionId
|
||||
@@ -141,7 +140,6 @@ export function getAncestorExecutionIds(
|
||||
* Returns all ancestor execution IDs for a given execution ID, excluding itself.
|
||||
*
|
||||
* Example: "65:70:63" → ["65", "65:70"]
|
||||
* @knipIgnoreUsedByStackedPR
|
||||
*/
|
||||
export function getParentExecutionIds(
|
||||
executionId: string | NodeExecutionId
|
||||
|
||||
@@ -44,7 +44,7 @@ export const iconForJobState = (state: JobState): string => {
|
||||
const buildTitle = (task: TaskItemImpl, t: (k: string) => string): string => {
|
||||
const prefix = t('g.job')
|
||||
const shortId = String(task.jobId ?? '').split('-')[0]
|
||||
const idx = task.queueIndex
|
||||
const idx = task.job.priority
|
||||
if (typeof idx === 'number') return `${prefix} #${idx}`
|
||||
if (shortId) return `${prefix} ${shortId}`
|
||||
return prefix
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/**
|
||||
* Extra info returned by the backend for missing_node_type errors
|
||||
* from the /prompt endpoint validation.
|
||||
*/
|
||||
export interface MissingNodeTypeExtraInfo {
|
||||
class_type?: string | null
|
||||
node_title?: string | null
|
||||
node_id?: string
|
||||
}
|
||||
@@ -1,90 +1,70 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
|
||||
import {
|
||||
buildMissingNodeHint,
|
||||
createMissingNodeTypeFromError
|
||||
getCnrIdFromProperties,
|
||||
getCnrIdFromNode
|
||||
} from './missingNodeErrorUtil'
|
||||
|
||||
describe('buildMissingNodeHint', () => {
|
||||
it('returns hint with title and node ID when both available', () => {
|
||||
expect(buildMissingNodeHint('My Node', 'MyNodeClass', '42')).toBe(
|
||||
'"My Node" (Node ID #42)'
|
||||
describe('getCnrIdFromProperties', () => {
|
||||
it('returns cnr_id when present', () => {
|
||||
expect(getCnrIdFromProperties({ cnr_id: 'my-pack' })).toBe('my-pack')
|
||||
})
|
||||
|
||||
it('returns aux_id when cnr_id is absent', () => {
|
||||
expect(getCnrIdFromProperties({ aux_id: 'my-aux-pack' })).toBe(
|
||||
'my-aux-pack'
|
||||
)
|
||||
})
|
||||
|
||||
it('returns hint with title only when no node ID', () => {
|
||||
expect(buildMissingNodeHint('My Node', 'MyNodeClass', undefined)).toBe(
|
||||
'"My Node"'
|
||||
)
|
||||
})
|
||||
|
||||
it('returns hint with node ID only when title matches class type', () => {
|
||||
expect(buildMissingNodeHint('MyNodeClass', 'MyNodeClass', '42')).toBe(
|
||||
'Node ID #42'
|
||||
)
|
||||
})
|
||||
|
||||
it('returns undefined when title matches class type and no node ID', () => {
|
||||
it('prefers cnr_id over aux_id', () => {
|
||||
expect(
|
||||
buildMissingNodeHint('MyNodeClass', 'MyNodeClass', undefined)
|
||||
).toBeUndefined()
|
||||
getCnrIdFromProperties({ cnr_id: 'primary', aux_id: 'secondary' })
|
||||
).toBe('primary')
|
||||
})
|
||||
|
||||
it('returns undefined when title is null and no node ID', () => {
|
||||
expect(buildMissingNodeHint(null, 'MyNodeClass', undefined)).toBeUndefined()
|
||||
it('returns undefined when neither is present', () => {
|
||||
expect(getCnrIdFromProperties({})).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns node ID hint when title is null but node ID exists', () => {
|
||||
expect(buildMissingNodeHint(null, 'MyNodeClass', '42')).toBe('Node ID #42')
|
||||
it('returns undefined for null properties', () => {
|
||||
expect(getCnrIdFromProperties(null)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns undefined for undefined properties', () => {
|
||||
expect(getCnrIdFromProperties(undefined)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns undefined when cnr_id is not a string', () => {
|
||||
expect(getCnrIdFromProperties({ cnr_id: 123 })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('createMissingNodeTypeFromError', () => {
|
||||
it('returns string type when no hint is generated', () => {
|
||||
const result = createMissingNodeTypeFromError({
|
||||
class_type: 'MyNodeClass',
|
||||
node_title: 'MyNodeClass'
|
||||
})
|
||||
expect(result).toBe('MyNodeClass')
|
||||
describe('getCnrIdFromNode', () => {
|
||||
it('returns cnr_id from node properties', () => {
|
||||
const node = {
|
||||
properties: { cnr_id: 'node-pack' }
|
||||
} as unknown as LGraphNode
|
||||
expect(getCnrIdFromNode(node)).toBe('node-pack')
|
||||
})
|
||||
|
||||
it('returns object with hint when title differs from class type', () => {
|
||||
const result = createMissingNodeTypeFromError({
|
||||
class_type: 'MyNodeClass',
|
||||
node_title: 'My Custom Title',
|
||||
node_id: '42'
|
||||
})
|
||||
expect(result).toEqual({
|
||||
type: 'MyNodeClass',
|
||||
hint: '"My Custom Title" (Node ID #42)'
|
||||
})
|
||||
it('returns aux_id when cnr_id is absent', () => {
|
||||
const node = {
|
||||
properties: { aux_id: 'node-aux-pack' }
|
||||
} as unknown as LGraphNode
|
||||
expect(getCnrIdFromNode(node)).toBe('node-aux-pack')
|
||||
})
|
||||
|
||||
it('handles null class_type by defaulting to Unknown', () => {
|
||||
const result = createMissingNodeTypeFromError({
|
||||
class_type: null,
|
||||
node_title: 'Some Title',
|
||||
node_id: '42'
|
||||
})
|
||||
expect(result).toEqual({
|
||||
type: 'Unknown',
|
||||
hint: '"Some Title" (Node ID #42)'
|
||||
})
|
||||
it('prefers cnr_id over aux_id in node properties', () => {
|
||||
const node = {
|
||||
properties: { cnr_id: 'primary', aux_id: 'secondary' }
|
||||
} as unknown as LGraphNode
|
||||
expect(getCnrIdFromNode(node)).toBe('primary')
|
||||
})
|
||||
|
||||
it('handles empty extra_info', () => {
|
||||
const result = createMissingNodeTypeFromError({})
|
||||
expect(result).toBe('Unknown')
|
||||
})
|
||||
|
||||
it('returns object with node ID hint when only node_id is available', () => {
|
||||
const result = createMissingNodeTypeFromError({
|
||||
class_type: 'MyNodeClass',
|
||||
node_id: '123'
|
||||
})
|
||||
expect(result).toEqual({
|
||||
type: 'MyNodeClass',
|
||||
hint: 'Node ID #123'
|
||||
})
|
||||
it('returns undefined when node has no cnr_id or aux_id', () => {
|
||||
const node = { properties: {} } as unknown as LGraphNode
|
||||
expect(getCnrIdFromNode(node)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,37 +1,27 @@
|
||||
import type { MissingNodeType } from '@/types/comfy'
|
||||
|
||||
import type { MissingNodeTypeExtraInfo } from '../types/missingNodeErrorTypes'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
|
||||
/**
|
||||
* Builds a hint string from missing node metadata.
|
||||
* Provides context about which node is missing (title, ID) when available.
|
||||
* Extracts the custom node registry ID (cnr_id or aux_id) from a raw
|
||||
* properties bag.
|
||||
*
|
||||
* @param properties - The properties object to inspect
|
||||
* @returns The cnrId string, or undefined if not found
|
||||
*/
|
||||
export function buildMissingNodeHint(
|
||||
nodeTitle: string | null | undefined,
|
||||
classType: string,
|
||||
nodeId: string | undefined
|
||||
export function getCnrIdFromProperties(
|
||||
properties: Record<string, unknown> | undefined | null
|
||||
): string | undefined {
|
||||
const hasTitle = nodeTitle && nodeTitle !== classType
|
||||
if (hasTitle && nodeId) {
|
||||
return `"${nodeTitle}" (Node ID #${nodeId})`
|
||||
} else if (hasTitle) {
|
||||
return `"${nodeTitle}"`
|
||||
} else if (nodeId) {
|
||||
return `Node ID #${nodeId}`
|
||||
}
|
||||
if (typeof properties?.cnr_id === 'string') return properties.cnr_id
|
||||
if (typeof properties?.aux_id === 'string') return properties.aux_id
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a MissingNodeType from backend error extra_info.
|
||||
* Used when the /prompt endpoint returns a missing_node_type error.
|
||||
* Extracts the custom node registry ID (cnr_id or aux_id) from a node's properties.
|
||||
* Returns undefined if neither property is present.
|
||||
*
|
||||
* @param node - The graph node to inspect
|
||||
* @returns The cnrId string, or undefined if not found
|
||||
*/
|
||||
export function createMissingNodeTypeFromError(
|
||||
extraInfo: MissingNodeTypeExtraInfo
|
||||
): MissingNodeType {
|
||||
const classType = extraInfo.class_type ?? 'Unknown'
|
||||
const nodeTitle = extraInfo.node_title ?? classType
|
||||
const hint = buildMissingNodeHint(nodeTitle, classType, extraInfo.node_id)
|
||||
|
||||
return hint ? { type: classType, hint } : classType
|
||||
export function getCnrIdFromNode(node: LGraphNode): string | undefined {
|
||||
return getCnrIdFromProperties(node.properties as Record<string, unknown>)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user