File size: 11,930 Bytes
7312c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { act, fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
  SAMPLING_PREVIEW_EVENT,
  SamplingPreviewWidget,
  type SamplingPreviewPayload,
} from '@/components/widgets/SamplingPreviewWidget'

describe('SamplingPreviewWidget', () => {
  const listeners = new Map<string, (event: CustomEvent<unknown>) => void>()
  const api = {
    addCustomEventListener: vi.fn((name: string, listener: (event: CustomEvent<unknown>) => void) => {
      listeners.set(name, listener)
    }),
    removeCustomEventListener: vi.fn((name: string) => listeners.delete(name)),
  }
  const rawApp = {
    api,
    ui: { settings: { settingsValues: { 'Comfy.Locale': 'en' } } },
  }
  const app = rawApp as never

  beforeEach(() => {
    listeners.clear()
    vi.clearAllMocks()
    rawApp.ui.settings.settingsValues['Comfy.Locale'] = 'en'
    vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1))
    vi.stubGlobal('cancelAnimationFrame', vi.fn())
    Object.defineProperty(URL, 'createObjectURL', {
      configurable: true,
      value: vi.fn(() => 'blob:preview'),
    })
    Object.defineProperty(URL, 'revokeObjectURL', {
      configurable: true,
      value: vi.fn(),
    })
  })

  function publish(overrides: Partial<SamplingPreviewPayload> = {}) {
    const payload: SamplingPreviewPayload = {
      node_id: '42',
      prompt_id: 'prompt-1',
      image: btoa('frame-1'),
      mime: 'image/jpeg',
      step: 3,
      total: 8,
      fps: 24,
      frame_count: 60,
      segment_index: 1,
      sampling_pass: 'second',
      ...overrides,
    }
    act(() => listeners.get(SAMPLING_PREVIEW_EVENT)?.(new CustomEvent(
      SAMPLING_PREVIEW_EVENT,
      { detail: payload },
    )))
  }

  it('shows metadata in the playback bar without playback text or percentage', () => {
    const onVisibilityChange = vi.fn()
    render(
      <SamplingPreviewWidget
        app={app}
        nodeId="42"
        onVisibilityChange={onVisibilityChange}
      />,
    )

    publish()

    expect(screen.getByAltText('Sampling preview').getAttribute('src')).toBe('blob:preview')
    expect(screen.getByText('Segment 2 路 Second pass 路 3/8')).not.toBeNull()
    const progress = screen.getByRole('progressbar', {
      name: 'Sampling preview playback progress',
    })
    expect(progress.getAttribute('aria-valuemax')).toBe('100')
    expect(screen.queryByText('Preview playback')).toBeNull()
    expect(screen.queryByText(/%$/)).toBeNull()
    expect(onVisibilityChange).toHaveBeenLastCalledWith(true)
  })

  it('pauses and resumes from either the image or progress bar', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish()

    const pauseControls = screen.getAllByRole('button', { name: 'Pause sampling preview' })
    fireEvent.click(pauseControls[0])
    expect(screen.getAllByRole('button', { name: 'Resume sampling preview' })).toHaveLength(2)

    fireEvent.click(screen.getAllByRole('button', { name: 'Resume sampling preview' })[1])
    expect(screen.getAllByRole('button', { name: 'Pause sampling preview' })).toHaveLength(2)
  })

  it('freezes an animated WebP fallback when browser frame decoding is unavailable', () => {
    const drawImage = vi.fn()
    vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ drawImage } as never)
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish({ mime: 'image/webp' })

    const image = screen.getByAltText('Sampling preview') as HTMLImageElement
    Object.defineProperties(image, {
      complete: { configurable: true, value: true },
      naturalWidth: { configurable: true, value: 320 },
      naturalHeight: { configurable: true, value: 180 },
    })
    fireEvent.click(screen.getAllByRole('button', { name: 'Pause sampling preview' })[0])

    const frozenFrame = screen.getByTestId('sampling-preview-frozen-frame') as HTMLCanvasElement
    expect(drawImage).toHaveBeenCalledWith(image, 0, 0)
    expect(frozenFrame.hidden).toBe(false)
    expect(frozenFrame.width).toBe(320)
    expect(frozenFrame.height).toBe(180)

    publish({ image: btoa('new-preview'), mime: 'image/webp', step: 4 })
    expect(drawImage).toHaveBeenCalledTimes(1)
    expect(frozenFrame.hidden).toBe(false)
    expect(screen.getByText('Segment 2 路 Second pass 路 3/8')).not.toBeNull()

    fireEvent.click(screen.getAllByRole('button', { name: 'Resume sampling preview' })[1])
    expect(frozenFrame.hidden).toBe(true)
    expect(screen.getByText('Segment 2 路 Second pass 路 4/8')).not.toBeNull()
  })

  it('hides the image while keeping its placeholder and show control', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish()

    fireEvent.click(screen.getByRole('button', { name: 'Hide sampling preview' }))
    expect(screen.queryByAltText('Sampling preview')).toBeNull()
    expect(screen.getByTestId('sampling-preview-placeholder')).not.toBeNull()
    expect(screen.getByRole('button', { name: 'Show sampling preview' })).not.toBeNull()
    expect(screen.getByText('Segment 2 路 Second pass 路 3/8')).not.toBeNull()
  })

  it('ignores preview events targeting another node', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)

    publish({ node_id: '99' })

    expect(screen.queryByAltText('Sampling preview')).toBeNull()
  })

  it('renders a display-only preview without controls for pointer-transparent overlays', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" interactive={false} />)
    publish()

    expect(screen.getByAltText('Sampling preview')).not.toBeNull()
    expect(screen.queryByRole('button')).toBeNull()
    expect(screen.getByRole('progressbar')).not.toBeNull()
  })

  it('keeps only the visibility icon interactive in a canvas-transparent overlay', () => {
    render(
      <SamplingPreviewWidget
        app={app}
        nodeId="42"
        interactive={false}
        visibilityControlOnly
      />,
    )
    publish()

    const hideButton = screen.getByRole('button', { name: 'Hide sampling preview' })
    expect(hideButton.className).toContain('pointer-events-auto')
    expect(screen.queryByRole('button', { name: 'Pause sampling preview' })).toBeNull()
    fireEvent.click(hideButton)
    expect(screen.getByRole('button', { name: 'Show sampling preview' })).not.toBeNull()
  })

  it('reads the LiteGraph node id when the event arrives, after node creation', () => {
    let assignedNodeId = -1
    render(<SamplingPreviewWidget app={app} nodeId={() => assignedNodeId} />)
    assignedNodeId = 42

    publish()

    expect(screen.getByAltText('Sampling preview')).not.toBeNull()
  })

  it('accepts the canvas display node id used by expanded graph execution', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)

    publish({ node_id: '42.3.1.87', display_node_id: '42' })

    expect(screen.getByAltText('Sampling preview')).not.toBeNull()
  })

  it('uses the current ComfyUI locale', () => {
    rawApp.ui.settings.settingsValues['Comfy.Locale'] = 'zh'
    render(<SamplingPreviewWidget app={app} nodeId="42" />)

    publish()

    expect(screen.getByText('鐗囨 2 路 浜岄噰 路 3/8')).not.toBeNull()
    expect(screen.getByRole('button', { name: '闅愯棌閲囨牱棰勮' })).not.toBeNull()
  })

  it('clears stale preview when the project starts a new execution', () => {
    const onVisibilityChange = vi.fn()
    const view = render(
      <SamplingPreviewWidget
        app={app}
        nodeId="42"
        executionRevision={0}
        onVisibilityChange={onVisibilityChange}
      />,
    )
    publish()
    expect(screen.getByAltText('Sampling preview')).not.toBeNull()

    view.rerender(
      <SamplingPreviewWidget
        app={app}
        nodeId="42"
        executionRevision={1}
        onVisibilityChange={onVisibilityChange}
      />,
    )

    expect(screen.queryByAltText('Sampling preview')).toBeNull()
    expect(onVisibilityChange).toHaveBeenLastCalledWith(false)
  })

  it('ignores queued preview frames from a previous prompt', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    act(() => listeners.get('execution_start')?.(new CustomEvent(
      'execution_start',
      { detail: { prompt_id: 'prompt-2' } },
    )))

    publish({ prompt_id: 'prompt-1' })
    expect(screen.queryByAltText('Sampling preview')).toBeNull()

    publish({ prompt_id: 'prompt-2' })
    expect(screen.getByAltText('Sampling preview')).not.toBeNull()
  })

  it('keeps the completed preview when an unrelated prompt starts', () => {
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish({ prompt_id: 'prompt-1' })

    act(() => listeners.get('execution_start')?.(new CustomEvent(
      'execution_start',
      { detail: { prompt_id: 'unrelated-prompt' } },
    )))

    expect(screen.getByAltText('Sampling preview')).not.toBeNull()
  })

  it('uses the requested half-frame count and does not restart on every sampling step', () => {
    let nextFrame: FrameRequestCallback | undefined
    vi.mocked(requestAnimationFrame).mockImplementation((callback) => {
      nextFrame = callback
      return 1
    })
    vi.spyOn(performance, 'now').mockReturnValue(0)
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish({ frame_count: 60, fps: 24 })

    act(() => nextFrame?.(1000))
    const progress = screen.getByRole('progressbar', {
      name: 'Sampling preview playback progress',
    })
    expect(progress.getAttribute('aria-valuenow')).toBe('40')

    publish({ image: btoa('new-preview'), step: 4, frame_count: 60, fps: 24 })

    expect(progress.getAttribute('aria-valuenow')).toBe('40')
  })

  it('plays every frame from the legacy backend payload until ComfyUI restarts', () => {
    let nextFrame: FrameRequestCallback | undefined
    let urlIndex = 0
    vi.mocked(requestAnimationFrame).mockImplementation((callback) => {
      nextFrame = callback
      return 1
    })
    vi.mocked(URL.createObjectURL).mockImplementation(() => `blob:preview-${++urlIndex}`)
    vi.spyOn(performance, 'now').mockReturnValue(0)
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish({
      images: [btoa('frame-1'), btoa('frame-2')],
      frame_count: 2,
      fps: 2,
    })

    expect(screen.getByAltText('Sampling preview').getAttribute('src')).toBe('blob:preview-2')
    act(() => nextFrame?.(600))
    expect(screen.getByAltText('Sampling preview').getAttribute('src')).toBe('blob:preview-3')
  })

  it('holds the currently displayed addressable frame while paused', () => {
    let nextFrame: FrameRequestCallback | undefined
    let urlIndex = 0
    vi.mocked(requestAnimationFrame).mockImplementation((callback) => {
      nextFrame = callback
      return 1
    })
    vi.mocked(URL.createObjectURL).mockImplementation(() => `blob:preview-${++urlIndex}`)
    vi.spyOn(performance, 'now').mockReturnValue(0)
    render(<SamplingPreviewWidget app={app} nodeId="42" />)
    publish({
      images: [btoa('frame-1'), btoa('frame-2')],
      frame_count: 2,
      fps: 2,
    })
    act(() => nextFrame?.(600))
    const pausedSource = screen.getByAltText('Sampling preview').getAttribute('src')
    expect(pausedSource).toBe('blob:preview-3')

    fireEvent.click(screen.getAllByRole('button', { name: 'Pause sampling preview' })[0])
    publish({
      image: btoa('new-preview'),
      images: [btoa('new-frame-1'), btoa('new-frame-2')],
      frame_count: 2,
      fps: 2,
      step: 4,
    })

    expect(screen.getByAltText('Sampling preview').getAttribute('src')).toBe(pausedSource)
    expect(screen.getByText('Segment 2 路 Second pass 路 3/8')).not.toBeNull()

    fireEvent.click(screen.getAllByRole('button', { name: 'Resume sampling preview' })[1])
    expect(screen.getByAltText('Sampling preview').getAttribute('src')).not.toBe(pausedSource)
    expect(screen.getByText('Segment 2 路 Second pass 路 4/8')).not.toBeNull()
  })
})