Line data Source code
1 : import { defineStore } from 'pinia'
2 : import { computed, ref, shallowRef, toRaw, toValue } from 'vue'
3 :
4 : import { extractWorkflow } from '@comfyorg/api-client/fetchJobs'
5 : import type {
6 : APITaskType,
7 : JobListItem,
8 : TaskType
9 : } from '@comfyorg/api-client/jobTypes'
10 : import type {
11 : StatusWsMessageStatus,
12 : TaskOutput
13 : } from '@comfyorg/api-client/executionTypes'
14 : import { api } from '@/scripts/api'
15 : import type { AugmentedResultItem } from '@/utils/resultItem'
16 : import { filterPreviewableResults } from '@/utils/resultItem'
17 : import { parseTaskOutput } from '@/stores/resultItemParsing'
18 : import type { ComfyApp } from '@/types/comfy'
19 : import { useExtensionServiceAccess } from '@/platform/extensions/services/extensionServiceAccess'
20 : import { getJobDetail } from '@/services/jobOutputCache'
21 : import { useNodeOutputStore } from '@/stores/nodeOutputStore'
22 : import { useExecutionStore } from '@/stores/executionStore'
23 : import { useJobModelDownloadStore } from '@/stores/jobModelDownloadStore'
24 : import { tryNormalizeNodeExecutionId } from '@comfyorg/graph-model/nodeIdentification'
25 : import { useSettingStore } from '@/platform/settings/settingStore'
26 :
27 : enum TaskItemDisplayStatus {
28 : Running = 'Running',
29 : Pending = 'Pending',
30 : Completed = 'Completed',
31 : Failed = 'Failed',
32 : Cancelled = 'Cancelled'
33 : }
34 :
35 1357 : function toAugmentedPreviewOutput(
36 : previewOutput: NonNullable<JobListItem['preview_output']>
37 : ): AugmentedResultItem {
38 1357 : return {
39 : ...previewOutput,
40 : filename: previewOutput.filename ?? '',
41 : subfolder: previewOutput.subfolder ?? ''
42 : }
43 : }
44 :
45 2356 : export class TaskItemImpl {
46 : readonly job: JobListItem
47 : readonly outputs: TaskOutput
48 : readonly flatOutputs: ReadonlyArray<AugmentedResultItem>
49 :
50 : constructor(
51 : job: JobListItem,
52 : outputs?: TaskOutput,
53 : flatOutputs?: ReadonlyArray<AugmentedResultItem>
54 : ) {
55 5620 : this.job = job
56 : // If no outputs provided but job has preview_output, create synthetic outputs
57 : // using the real nodeId and mediaType from the backend response
58 5620 : const effectiveOutputs =
59 : outputs ??
60 : (job.preview_output
61 : ? {
62 : [job.preview_output.nodeId]: {
63 : [job.preview_output.mediaType]: [job.preview_output]
64 : }
65 : }
66 : : {})
67 5620 : this.outputs = effectiveOutputs
68 5620 : this.flatOutputs =
69 : flatOutputs ??
70 : (!outputs && job.preview_output?.mediaType === 'text'
71 : ? [toAugmentedPreviewOutput(job.preview_output)]
72 : : this.calculateFlatOutputs())
73 : }
74 :
75 : calculateFlatOutputs(): ReadonlyArray<AugmentedResultItem> {
76 4263 : return parseTaskOutput(this.outputs)
77 : }
78 :
79 : /** All outputs that support preview (images, videos, audio, 3D, text) */
80 : get previewableOutputs(): readonly AugmentedResultItem[] {
81 11432 : return filterPreviewableResults(this.flatOutputs)
82 : }
83 :
84 : get previewOutput(): AugmentedResultItem | undefined {
85 7707 : const previewable = this.previewableOutputs
86 : // Prefer the last saved media file (most recent result) over temp previews
87 7707 : return (
88 : previewable.findLast((output) => output.type === 'output') ??
89 : previewable.at(-1)
90 : )
91 : }
92 :
93 : // Derive taskType from job status
94 : get taskType(): TaskType {
95 0 : switch (this.job.status) {
96 : case 'in_progress':
97 0 : return 'Running'
98 : case 'pending':
99 0 : return 'Pending'
100 : default:
101 0 : return 'History'
102 : }
103 : }
104 :
105 : get apiTaskType(): APITaskType {
106 0 : switch (this.taskType) {
107 : case 'Running':
108 : case 'Pending':
109 0 : return 'queue'
110 : case 'History':
111 0 : return 'history'
112 : }
113 : }
114 :
115 : get key() {
116 0 : return this.jobId + this.displayStatus
117 : }
118 :
119 : get jobId() {
120 10607 : return this.job.id
121 : }
122 :
123 : get outputsCount(): number | undefined {
124 1500 : return this.job.outputs_count ?? undefined
125 : }
126 :
127 : /** Absent on backends or jobs that predate this field. */
128 : get previewableOutputsCount(): number | undefined {
129 4162 : return this.job.previewable_outputs_count ?? undefined
130 : }
131 :
132 : get status() {
133 0 : return this.job.status
134 : }
135 :
136 : get errorMessage(): string | undefined {
137 1 : return this.job.execution_error?.exception_message ?? undefined
138 : }
139 :
140 : get executionError() {
141 0 : return this.job.execution_error ?? undefined
142 : }
143 :
144 : get workflowId(): string | undefined {
145 67 : return this.job.workflow_id ?? undefined
146 : }
147 :
148 : get createTime(): number {
149 6953 : return this.job.create_time
150 : }
151 :
152 : get interrupted(): boolean {
153 0 : return (
154 : this.job.status === 'failed' &&
155 : this.job.execution_error?.exception_type ===
156 : 'InterruptProcessingException'
157 : )
158 : }
159 :
160 : get isHistory() {
161 0 : return this.taskType === 'History'
162 : }
163 :
164 : get isRunning() {
165 0 : return this.taskType === 'Running'
166 : }
167 :
168 : get displayStatus(): TaskItemDisplayStatus {
169 2145 : switch (this.job.status) {
170 : case 'in_progress':
171 57 : return TaskItemDisplayStatus.Running
172 : case 'pending':
173 8 : return TaskItemDisplayStatus.Pending
174 : case 'completed':
175 1609 : return TaskItemDisplayStatus.Completed
176 : case 'failed':
177 462 : return TaskItemDisplayStatus.Failed
178 : case 'cancelled':
179 9 : return TaskItemDisplayStatus.Cancelled
180 : }
181 : }
182 :
183 : get executionStartTimestamp() {
184 22884 : return this.job.execution_start_time ?? undefined
185 : }
186 :
187 : get executionEndTimestamp() {
188 15727 : return this.job.execution_end_time ?? undefined
189 : }
190 :
191 : get executionTime() {
192 7736 : if (!this.executionStartTimestamp || !this.executionEndTimestamp) {
193 36 : return undefined
194 : }
195 7700 : return this.executionEndTimestamp - this.executionStartTimestamp
196 : }
197 :
198 : get executionTimeInSeconds() {
199 3755 : return this.executionTime !== undefined
200 : ? this.executionTime / 1000
201 : : undefined
202 : }
203 :
204 : /**
205 : * Loads full outputs for tasks that only have preview data
206 : * Returns a new TaskItemImpl with full outputs and execution status
207 : */
208 : public async loadFullOutputs(): Promise<TaskItemImpl> {
209 : // Only load for history tasks (caller checks outputsCount > 1)
210 0 : if (!this.isHistory) {
211 0 : return this
212 : }
213 0 : const jobDetail = await getJobDetail(this.jobId)
214 :
215 0 : if (!jobDetail?.outputs) {
216 0 : return this
217 : }
218 :
219 : // Create new TaskItemImpl with full outputs
220 0 : return new TaskItemImpl(this.job, jobDetail.outputs)
221 : }
222 :
223 : public async loadWorkflow(app: ComfyApp) {
224 0 : if (!this.isHistory) {
225 0 : return
226 : }
227 :
228 : // Single fetch for both workflow and outputs (with caching)
229 0 : const jobDetail = await getJobDetail(this.jobId)
230 :
231 0 : const workflowData = await extractWorkflow(jobDetail)
232 0 : if (!workflowData) {
233 0 : return
234 : }
235 :
236 0 : await app.loadGraphData(toRaw(workflowData))
237 :
238 : // Use full outputs from job detail, or fall back to existing outputs
239 0 : const outputsToLoad = jobDetail?.outputs ?? this.outputs
240 0 : const nodeOutputsStore = useNodeOutputStore()
241 0 : const rawOutputs = toRaw(outputsToLoad)
242 0 : for (const rawNodeExecutionId in rawOutputs) {
243 0 : const nodeExecutionId = tryNormalizeNodeExecutionId(rawNodeExecutionId)
244 0 : if (!nodeExecutionId) continue
245 0 : nodeOutputsStore.setNodeOutputsByExecutionId(
246 : nodeExecutionId,
247 : rawOutputs[rawNodeExecutionId]
248 : )
249 : }
250 0 : useExtensionServiceAccess().invokeExtensions(
251 : 'onNodeOutputsUpdated',
252 : app.nodeOutputs
253 : )
254 : }
255 :
256 : public flatten(): TaskItemImpl[] {
257 0 : if (this.displayStatus !== TaskItemDisplayStatus.Completed) {
258 0 : return [this]
259 : }
260 :
261 0 : return this.flatOutputs.map(
262 : (output: AugmentedResultItem, i: number) =>
263 : new TaskItemImpl(
264 : {
265 : ...this.job,
266 : id: `${this.jobId}-${i}`
267 : },
268 : {
269 : [output.nodeId]: {
270 : [output.mediaType]: [output]
271 : }
272 : },
273 : [output]
274 : )
275 : )
276 : }
277 : }
278 :
279 2356 : export const useQueueStore = defineStore('queue', () => {
280 : // Use shallowRef because TaskItemImpl instances are immutable and arrays are
281 : // replaced entirely (not mutated), so deep reactivity would waste performance
282 2355 : const runningTasks = shallowRef<TaskItemImpl[]>([])
283 2355 : const pendingTasks = shallowRef<TaskItemImpl[]>([])
284 2355 : const historyTasks = shallowRef<TaskItemImpl[]>([])
285 2355 : const hasFetchedHistorySnapshot = ref(false)
286 2355 : const maxHistoryItems = ref(64)
287 2355 : const isLoading = ref(false)
288 :
289 : // Single-flight coalescing: at most one fetch in flight at a time.
290 : // If update() is called while a fetch is running, the call is coalesced
291 : // and a single re-fetch fires after the current one completes.
292 : // This prevents both request spam and UI starvation (where a rapid stream
293 : // of calls causes every response to be discarded by a stale-request guard).
294 2355 : const updateState = { inFlight: false, dirty: false }
295 2355 : const hasDirtyUpdate = () => updateState.dirty
296 :
297 2355 : const tasks = computed<TaskItemImpl[]>(
298 : () =>
299 : [
300 : ...pendingTasks.value,
301 : ...runningTasks.value,
302 : ...historyTasks.value
303 : ] as TaskItemImpl[]
304 : )
305 :
306 2355 : const flatTasks = computed<TaskItemImpl[]>(() =>
307 : tasks.value.flatMap((task: TaskItemImpl) => task.flatten())
308 : )
309 :
310 2355 : const lastJobHistoryPriority = computed<number>(() =>
311 : historyTasks.value.length ? historyTasks.value[0].job.priority : -1
312 : )
313 :
314 2355 : const hasPendingTasks = computed<boolean>(() => pendingTasks.value.length > 0)
315 2355 : const activeJobsCount = computed(
316 : () => pendingTasks.value.length + runningTasks.value.length
317 : )
318 :
319 2355 : let currentUpdate: Promise<void> = Promise.resolve()
320 :
321 2355 : const update = async () => {
322 2851 : if (updateState.inFlight) {
323 233 : updateState.dirty = true
324 233 : return
325 : }
326 2618 : currentUpdate = fetchQueueAndHistory()
327 2618 : await currentUpdate
328 : }
329 :
330 : /** Like `update()`, but a coalesced call also waits for the trailing re-fetch. */
331 8 : async function updateFresh() {
332 8 : if (!updateState.inFlight) return update()
333 0 : updateState.dirty = true
334 0 : await currentUpdate
335 0 : await currentUpdate
336 : }
337 :
338 2618 : async function fetchQueueAndHistory() {
339 2618 : updateState.inFlight = true
340 2618 : updateState.dirty = false
341 2618 : isLoading.value = true
342 2618 : try {
343 2618 : const [queueResult, historyResult] = await Promise.allSettled([
344 : api.getQueue({ throwOnError: true }),
345 : api.getHistory(maxHistoryItems.value)
346 : ])
347 :
348 2601 : if (queueResult.status === 'fulfilled') {
349 2580 : const queue = queueResult.value
350 : // API returns pre-sorted data (sort_by=create_time&order=desc)
351 2580 : runningTasks.value = queue.Running.map((job) => new TaskItemImpl(job))
352 2580 : pendingTasks.value = queue.Pending.map((job) => new TaskItemImpl(job))
353 :
354 2580 : const appearedTasks = [...pendingTasks.value, ...runningTasks.value]
355 2580 : const executionStore = useExecutionStore()
356 2580 : appearedTasks.forEach((task) => {
357 65 : const jobIdString = task.jobId
358 65 : const workflowId = task.workflowId
359 65 : if (workflowId && jobIdString) {
360 32 : executionStore.registerJobWorkflowIdMapping(jobIdString, workflowId)
361 : }
362 : })
363 :
364 2580 : const activeJobIds = new Set([
365 : ...queue.Running.map((j) => j.id),
366 : ...queue.Pending.map((j) => j.id)
367 : ])
368 2580 : executionStore.reconcileInitializingJobs(activeJobIds)
369 2580 : useJobModelDownloadStore().reconcileActiveJobs(activeJobIds)
370 : } else {
371 1 : console.error('Failed to fetch queue:', queueResult.reason)
372 : }
373 :
374 2601 : if (historyResult.status === 'fulfilled') {
375 2581 : const history = historyResult.value
376 2581 : const currentHistory = toValue(historyTasks)
377 :
378 : // Sort by create_time descending and limit to maxItems
379 2581 : const sortedHistory = [...history]
380 : .sort((a, b) => b.create_time - a.create_time)
381 : .slice(0, toValue(maxHistoryItems))
382 :
383 : // Reuse existing TaskItemImpl instances or create new
384 : // Must recreate if outputs_count changed (e.g., API started returning it)
385 2581 : const existingByJobId = new Map(
386 : currentHistory.map((impl) => [impl.jobId, impl])
387 : )
388 :
389 2581 : const nextHistoryTasks = sortedHistory.map((job) => {
390 2243 : const existing = existingByJobId.get(job.id)
391 2243 : if (!existing) return new TaskItemImpl(job)
392 : // Recreate if outputs_count changed to ensure lazy loading works
393 2243 : if (
394 : existing.outputsCount !== (job.outputs_count ?? undefined) ||
395 : existing.previewableOutputsCount !==
396 : (job.previewable_outputs_count ?? undefined)
397 : ) {
398 0 : return new TaskItemImpl(job)
399 : }
400 412 : return existing
401 : })
402 :
403 : const isHistoryUnchanged =
404 : nextHistoryTasks.length === currentHistory.length &&
405 : nextHistoryTasks.every(
406 : (task, index) => task === currentHistory[index]
407 : )
408 :
409 2581 : if (!isHistoryUnchanged) {
410 802 : historyTasks.value = nextHistoryTasks
411 : }
412 2581 : hasFetchedHistorySnapshot.value = true
413 : } else {
414 0 : console.error('Failed to fetch history:', historyResult.reason)
415 : }
416 : } finally {
417 2581 : isLoading.value = false
418 2581 : updateState.inFlight = false
419 2581 : if (hasDirtyUpdate()) {
420 122 : void update()
421 : }
422 : }
423 : }
424 :
425 2355 : const clear = async (
426 : targets: ('queue' | 'history')[] = ['queue', 'history']
427 : ) => {
428 3 : if (targets.length === 0) {
429 0 : return
430 : }
431 3 : await Promise.all(targets.map((type) => api.clearItems(type)))
432 3 : await update()
433 : }
434 :
435 2355 : const deleteTask = async (task: TaskItemImpl) => {
436 0 : await api.deleteItem(task.apiTaskType, task.jobId)
437 0 : await update()
438 : }
439 :
440 2355 : return {
441 : runningTasks,
442 : pendingTasks,
443 : historyTasks,
444 : hasFetchedHistorySnapshot,
445 : maxHistoryItems,
446 : isLoading,
447 :
448 : tasks,
449 : flatTasks,
450 : lastJobHistoryPriority,
451 : hasPendingTasks,
452 : activeJobsCount,
453 :
454 : update,
455 : updateFresh,
456 : clear,
457 : delete: deleteTask
458 : }
459 : })
460 :
461 2356 : export const useQueuePendingTaskCountStore = defineStore(
462 : 'queuePendingTaskCount',
463 : {
464 : state: () => ({
465 : count: 0
466 : }),
467 : actions: {
468 : update(e: CustomEvent<StatusWsMessageStatus | null>) {
469 2639 : const queueRemaining = e.detail?.exec_info?.queue_remaining
470 2639 : if (queueRemaining != null) this.count = queueRemaining
471 : }
472 : }
473 : }
474 : )
475 :
476 2356 : export const useQueueUIStore = defineStore('queueUIStore', () => {
477 1975 : const settingStore = useSettingStore()
478 :
479 1975 : const isOverlayExpanded = computed({
480 : get: () => settingStore.get('Comfy.Queue.History.Expanded'),
481 : set: (value) => settingStore.set('Comfy.Queue.History.Expanded', value)
482 : })
483 :
484 22 : function toggleOverlay() {
485 22 : isOverlayExpanded.value = !isOverlayExpanded.value
486 : }
487 :
488 1975 : return { isOverlayExpanded, toggleOverlay }
489 : })
|