Line data Source code
1 : import type { ComfyTemplateInputDownloadProgress } from '@comfyorg/comfyui-desktop-bridge-types'
2 : import { defineStore } from 'pinia'
3 : import { computed, shallowReactive } from 'vue'
4 :
5 : interface TrackedTemplateInputDownload {
6 : downloadId: string
7 : filename: string
8 : progress: number | null
9 : status: 'pending' | 'downloading' | 'paused' | 'completed'
10 : }
11 :
12 0 : function normalizeProgress(progress: number): number | null {
13 0 : return Number.isFinite(progress) && progress >= 0 && progress <= 1
14 : ? progress
15 : : null
16 : }
17 :
18 2356 : export const useTemplateInputDownloadStore = defineStore(
19 : 'templateInputDownload',
20 : () => {
21 2355 : const downloadsById = shallowReactive(
22 : new Map<string, TrackedTemplateInputDownload>()
23 : )
24 2355 : const previewRevisions = shallowReactive(new Map<string, number>())
25 2355 : const completedIds = new Set<string>()
26 :
27 2355 : const downloads = computed(() => [...downloadsById.values()])
28 2355 : const blockingFilenames = computed(
29 : () => new Set(downloads.value.map(({ filename }) => filename))
30 : )
31 :
32 0 : function updateProgress(progress: ComfyTemplateInputDownloadProgress) {
33 0 : const { downloadId, filename, status } = progress
34 0 : if (status === 'error' || status === 'cancelled') {
35 0 : downloadsById.delete(downloadId)
36 0 : return
37 : }
38 :
39 : // A finished id never goes back to pending or downloading. A late event
40 : // would re-add a record `completeGraphSync` can no longer clear, leaving
41 : // the filename blocked for good.
42 0 : if (completedIds.has(downloadId)) return
43 :
44 0 : if (status === 'completed') {
45 0 : completedIds.add(downloadId)
46 0 : previewRevisions.set(
47 : filename,
48 : (previewRevisions.get(filename) ?? 0) + 1
49 : )
50 : }
51 :
52 0 : downloadsById.set(downloadId, {
53 : downloadId,
54 : filename,
55 : progress: normalizeProgress(progress.progress),
56 : status
57 : })
58 : }
59 :
60 0 : function completeGraphSync(filenames: readonly string[]) {
61 0 : const completed = new Set(filenames)
62 0 : for (const [downloadId, download] of downloadsById) {
63 0 : if (
64 : download.status === 'completed' &&
65 : completed.has(download.filename)
66 : ) {
67 0 : downloadsById.delete(downloadId)
68 : }
69 : }
70 : }
71 :
72 11 : function previewRevision(filename: string): number {
73 11 : return previewRevisions.get(filename) ?? 0
74 : }
75 :
76 0 : function clear() {
77 0 : downloadsById.clear()
78 0 : previewRevisions.clear()
79 0 : completedIds.clear()
80 : }
81 :
82 2355 : return {
83 : downloads,
84 : blockingFilenames,
85 : updateProgress,
86 : completeGraphSync,
87 : previewRevision,
88 : clear
89 : }
90 : }
91 : )
|