Line data Source code
1 : import { DownloadStatus } from '@comfyorg/comfyui-electron-types'
2 : import type { ComfyDownloadProgress } from '@comfyorg/comfyui-desktop-bridge-types'
3 : import { shallowReactive } from 'vue'
4 :
5 : import { dispatchModelDownload } from '@/platform/workflowErrors/missingModel/missingModelDownload'
6 : import type {
7 : ModelDownloadDispatchOutcome,
8 : ModelWithUrl
9 : } from '@/platform/workflowErrors/missingModel/missingModelDownload'
10 : import {
11 : createTemplateModelDownloadState,
12 : getTemplateModelDownloadIdentity,
13 : reduceTemplateModelDownloadState
14 : } from '@/platform/workflow/templates/utils/templateModelDownloadState'
15 : import type {
16 : TemplateModelDownloadEvent,
17 : TemplateModelDownloadHostEvent,
18 : TemplateModelDownloadState
19 : } from '@/platform/workflow/templates/utils/templateModelDownloadState'
20 : import { useElectronDownloadStore } from '@/stores/electronDownloadStore'
21 : import type { ElectronDownload } from '@/stores/electronDownloadStore'
22 :
23 : type FolderPaths = Record<string, string[]>
24 :
25 : type SubscribeDesktopProgress = (
26 : listener: (progress: ComfyDownloadProgress) => void
27 : ) => () => void
28 :
29 : type SubscribeLegacyProgress = (
30 : listener: (download: ElectronDownload) => void
31 : ) => () => void
32 :
33 : type TemplateModelRowDownloadDependencies = {
34 : /**
35 : * Resolved before the owner mounts, so a dispatch never waits on a lookup
36 : * that could finish after the owner is gone. Empty for hosts that resolve
37 : * their own directories.
38 : */
39 : folderPaths: FolderPaths
40 : dispatchDownload?: (
41 : model: ModelWithUrl,
42 : paths: FolderPaths,
43 : options: { revealLegacyDownload: false }
44 : ) => ModelDownloadDispatchOutcome
45 : subscribeDesktopProgress?: SubscribeDesktopProgress
46 : subscribeLegacyProgress?: SubscribeLegacyProgress
47 : }
48 :
49 0 : function modelMatchesProgress(
50 : model: ModelWithUrl,
51 : progress: { url: string; filename: string; directory?: string }
52 : ): boolean {
53 0 : return (
54 : model.url === progress.url &&
55 : model.name === progress.filename &&
56 : (progress.directory === undefined || model.directory === progress.directory)
57 : )
58 : }
59 :
60 0 : function activeAttempt(
61 : state: TemplateModelDownloadState | undefined
62 : ): number | undefined {
63 0 : if (!state) return undefined
64 0 : if (!['queued', 'starting', 'downloading'].includes(state.status)) return
65 0 : return state.attempt
66 : }
67 :
68 0 : function subscribeToDesktopProgress(
69 : listener: (progress: ComfyDownloadProgress) => void
70 : ): () => void {
71 0 : return window.__comfyDesktop2?.onDownloadProgress?.(listener) ?? (() => {})
72 : }
73 :
74 0 : function subscribeToLegacyProgress(
75 : listener: (download: ElectronDownload) => void
76 : ): () => void {
77 0 : return useElectronDownloadStore().subscribeToDownloadProgress(listener)
78 : }
79 :
80 0 : function validByteCount(value: number | undefined): number | null {
81 0 : return value !== undefined && Number.isFinite(value) && value >= 0
82 : ? value
83 : : null
84 : }
85 :
86 : /**
87 : * A progress figure from either host, accepted only as a 0..1 fraction and
88 : * only as a fallback: byte counters are exact where they exist.
89 : * `ComfyDownloadProgress.progress` has no documented scale, so that reading
90 : * comes from the template input store, which renders the same field as a
91 : * percentage.
92 : */
93 0 : function validFraction(value: number | undefined): number | null {
94 0 : return value !== undefined &&
95 : Number.isFinite(value) &&
96 : value >= 0 &&
97 : value <= 1
98 : ? value
99 : : null
100 : }
101 :
102 0 : function downloadFraction(
103 : receivedBytes: number | null,
104 : totalBytes: number | null
105 : ): number | null {
106 0 : if (receivedBytes === null || totalBytes === null) return null
107 0 : if (totalBytes <= 0 || receivedBytes > totalBytes) return null
108 0 : return receivedBytes / totalBytes
109 : }
110 :
111 0 : function desktopProgressEvent(
112 : progress: ComfyDownloadProgress,
113 : attempt: number
114 : ): TemplateModelDownloadHostEvent {
115 0 : switch (progress.status) {
116 : case 'pending':
117 0 : return { type: 'started', attempt }
118 : case 'downloading':
119 : case 'paused': {
120 0 : const receivedBytes = validByteCount(progress.receivedBytes)
121 0 : const totalBytes = validByteCount(progress.totalBytes)
122 0 : return {
123 : type: 'progress',
124 : attempt,
125 : activity: progress.status === 'paused' ? 'paused' : 'active',
126 : receivedBytes,
127 : totalBytes,
128 : fraction:
129 : downloadFraction(receivedBytes, totalBytes) ??
130 : validFraction(progress.progress)
131 : }
132 : }
133 : case 'completed':
134 : case 'error':
135 : case 'cancelled':
136 0 : return { type: progress.status, attempt }
137 : default:
138 0 : return progress.status satisfies never
139 : }
140 : }
141 :
142 0 : function legacyProgressEvent(
143 : download: ElectronDownload,
144 : attempt: number
145 : ): TemplateModelDownloadHostEvent | null {
146 0 : switch (download.status) {
147 : case DownloadStatus.PENDING:
148 0 : return { type: 'started', attempt }
149 : case DownloadStatus.IN_PROGRESS:
150 : case DownloadStatus.PAUSED:
151 0 : return {
152 : type: 'progress',
153 : attempt,
154 : activity:
155 : download.status === DownloadStatus.PAUSED ? 'paused' : 'active',
156 : receivedBytes: validByteCount(download.receivedBytes),
157 : totalBytes: validByteCount(download.totalBytes),
158 : fraction: validFraction(download.progress)
159 : }
160 : case DownloadStatus.COMPLETED:
161 0 : return { type: 'completed', attempt }
162 : case DownloadStatus.ERROR:
163 0 : return { type: 'error', attempt }
164 : case DownloadStatus.CANCELLED:
165 0 : return { type: 'cancelled', attempt }
166 : case undefined:
167 0 : return null
168 : default:
169 0 : return download.status satisfies never
170 : }
171 : }
172 :
173 : /**
174 : * One record per row identity. A URL change replaces the record outright;
175 : * a retry keeps only what outlives an attempt, which is the ended-job set.
176 : */
177 : type TrackedRow = {
178 : model: ModelWithUrl
179 : state: TemplateModelDownloadState
180 : /** Attempt whose stream has reported non-terminal activity. */
181 : activeAttempt?: number
182 : /** Job holding the current attempt, where the host sends an id. */
183 : job?: { attempt: number; jobId: string }
184 : /** Jobs that delivered a terminal event, so they cannot claim again. */
185 : endedJobs?: ReadonlySet<string>
186 : }
187 :
188 0 : export function useTemplateModelRowDownloads({
189 : folderPaths,
190 : dispatchDownload = dispatchModelDownload,
191 : subscribeDesktopProgress = subscribeToDesktopProgress,
192 : subscribeLegacyProgress = subscribeToLegacyProgress
193 : }: TemplateModelRowDownloadDependencies) {
194 0 : let disposed = false
195 0 : const rows = shallowReactive(new Map<string, TrackedRow>())
196 :
197 0 : function initializeState(model: ModelWithUrl): TemplateModelDownloadState {
198 0 : const identity = getTemplateModelDownloadIdentity(model)
199 0 : const existing = rows.get(identity)
200 0 : if (existing && existing.model.url === model.url) return existing.state
201 :
202 0 : const state = createTemplateModelDownloadState()
203 0 : rows.set(identity, { model, state })
204 0 : return state
205 : }
206 :
207 0 : function stateFor(model: ModelWithUrl): Readonly<TemplateModelDownloadState> {
208 0 : const identity = getTemplateModelDownloadIdentity(model)
209 0 : const row = rows.get(identity)
210 0 : if (row?.model.url !== model.url) {
211 0 : return createTemplateModelDownloadState()
212 : }
213 0 : return row.state
214 : }
215 :
216 0 : function applyEvent(
217 : model: ModelWithUrl,
218 : event: TemplateModelDownloadEvent
219 : ): void {
220 0 : const identity = getTemplateModelDownloadIdentity(model)
221 0 : const row = rows.get(identity)
222 : // A host result can settle after the row moved to a different URL, and
223 : // applying it then would fail the replacement row.
224 0 : if (row?.model.url !== model.url) return
225 :
226 0 : let current = row.state
227 0 : if (
228 : current.status === 'queued' &&
229 : event.type !== 'started' &&
230 : event.type !== 'error' &&
231 : event.type !== 'cancelled'
232 : ) {
233 0 : current = reduceTemplateModelDownloadState(current, {
234 : type: 'started',
235 : attempt: current.attempt
236 : })
237 : }
238 0 : rows.set(identity, {
239 : ...row,
240 : state: reduceTemplateModelDownloadState(current, event)
241 : })
242 : }
243 :
244 0 : function applyNativeEvent(
245 : model: ModelWithUrl,
246 : event: TemplateModelDownloadHostEvent,
247 : jobId?: string
248 : ): void {
249 0 : const identity = getTemplateModelDownloadIdentity(model)
250 0 : if (jobId !== undefined && !acceptsJob(identity, event, jobId)) return
251 0 : if (event.type === 'started' || event.type === 'progress') {
252 0 : const row = rows.get(identity)
253 0 : if (row) rows.set(identity, { ...row, activeAttempt: event.attempt })
254 0 : } else if (
255 : // Everything else is terminal. A retry only ends on a stream that was
256 : // seen running; attempt 1 is exempt because a transfer can finish
257 : // without ever reporting progress.
258 : event.attempt > 1 &&
259 : rows.get(identity)?.activeAttempt !== event.attempt
260 : ) {
261 0 : return
262 : }
263 :
264 0 : applyEvent(model, event)
265 : }
266 :
267 0 : function claimantOf(row: TrackedRow, attempt: number): string | undefined {
268 0 : return row.job?.attempt === attempt ? row.job.jobId : undefined
269 : }
270 :
271 0 : function acceptsTerminal(
272 : identity: string,
273 : row: TrackedRow,
274 : attempt: number,
275 : jobId: string
276 : ): boolean {
277 0 : if (claimantOf(row, attempt) !== jobId) return false
278 0 : rows.set(identity, {
279 : ...row,
280 : endedJobs: new Set([...(row.endedJobs ?? []), jobId])
281 : })
282 0 : return true
283 : }
284 :
285 0 : function acceptsActivity(
286 : identity: string,
287 : row: TrackedRow,
288 : attempt: number,
289 : jobId: string
290 : ): boolean {
291 0 : const claimant = claimantOf(row, attempt)
292 0 : if (claimant !== undefined) return claimant === jobId
293 : // A joined retry reuses a running job's id, so only an ended one is out.
294 0 : if (row.endedJobs?.has(jobId)) return false
295 :
296 0 : rows.set(identity, { ...row, job: { attempt, jobId } })
297 0 : return true
298 : }
299 :
300 0 : function acceptsJob(
301 : identity: string,
302 : event: TemplateModelDownloadHostEvent,
303 : jobId: string
304 : ): boolean {
305 0 : const row = rows.get(identity)
306 0 : if (!row) return false
307 0 : return event.type === 'started' || event.type === 'progress'
308 : ? acceptsActivity(identity, row, event.attempt, jobId)
309 : : acceptsTerminal(identity, row, event.attempt, jobId)
310 : }
311 :
312 0 : function forMatchingModels(
313 : progress: { url: string; filename: string; directory?: string },
314 : apply: (model: ModelWithUrl, attempt: number) => void
315 : ): void {
316 0 : const matches: { model: ModelWithUrl; attempt: number }[] = []
317 0 : for (const { model, state } of rows.values()) {
318 0 : if (!modelMatchesProgress(model, progress)) continue
319 0 : const attempt = activeAttempt(state)
320 0 : if (attempt === undefined) continue
321 0 : matches.push({ model, attempt })
322 : }
323 :
324 0 : if (progress.directory === undefined && matches.length !== 1) return
325 0 : for (const { model, attempt } of matches) apply(model, attempt)
326 : }
327 :
328 0 : const stopDesktopProgress = subscribeDesktopProgress((progress) => {
329 0 : forMatchingModels(progress, (model, attempt) => {
330 0 : applyNativeEvent(
331 : model,
332 : desktopProgressEvent(progress, attempt),
333 : progress.id
334 : )
335 : })
336 : })
337 0 : let stopLegacyProgress: (() => void) | undefined
338 :
339 : /**
340 : * Desktop2 never reaches the legacy host, so its store and subscription are
341 : * only constructed once a dispatch actually lands there.
342 : */
343 0 : function ensureLegacyProgress(): void {
344 0 : stopLegacyProgress ??= subscribeLegacyProgress((download) => {
345 0 : forMatchingModels(download, (model, attempt) => {
346 0 : const event = legacyProgressEvent(download, attempt)
347 0 : if (event) applyNativeEvent(model, event)
348 : })
349 : })
350 : }
351 :
352 0 : function fail(model: ModelWithUrl, attempt: number): void {
353 0 : applyEvent(model, { type: 'error', attempt })
354 : }
355 :
356 0 : function handleOutcome(
357 : model: ModelWithUrl,
358 : attempt: number,
359 : outcome: ModelDownloadDispatchOutcome
360 : ): void {
361 0 : switch (outcome.status) {
362 : case 'host-requested':
363 0 : if (outcome.host === 'electron') ensureLegacyProgress()
364 0 : applyEvent(model, { type: 'started', attempt })
365 : // A resolved `false` is a refusal, not an acknowledgement: the sibling
366 : // `openModelAccessPage` documents the same convention on this bridge.
367 0 : void outcome.hostResult.then(
368 : (accepted) => {
369 0 : if (!accepted) fail(model, attempt)
370 : },
371 : () => fail(model, attempt)
372 : )
373 0 : return
374 : case 'browser-requested':
375 : case 'dispatch-failed':
376 0 : fail(model, attempt)
377 0 : return
378 : case 'not-dispatched':
379 0 : fail(model, attempt)
380 0 : return
381 : default:
382 0 : return outcome satisfies never
383 : }
384 : }
385 :
386 0 : function dispatch(model: ModelWithUrl, attempt: number): void {
387 0 : try {
388 0 : handleOutcome(
389 : model,
390 : attempt,
391 : dispatchDownload(model, folderPaths, { revealLegacyDownload: false })
392 : )
393 : } catch {
394 0 : fail(model, attempt)
395 : }
396 : }
397 :
398 0 : function request(model: ModelWithUrl): void {
399 0 : if (disposed) return
400 0 : const identity = getTemplateModelDownloadIdentity(model)
401 0 : const current = initializeState(model)
402 0 : const queued = reduceTemplateModelDownloadState(current, {
403 : type: 'request'
404 : })
405 0 : if (queued === current) return
406 :
407 0 : const row = rows.get(identity)
408 0 : if (row) rows.set(identity, { ...row, state: queued })
409 0 : dispatch(model, queued.attempt)
410 : }
411 :
412 0 : function dispose(): void {
413 0 : if (disposed) return
414 0 : disposed = true
415 0 : stopDesktopProgress()
416 0 : stopLegacyProgress?.()
417 : }
418 :
419 0 : function canResume(_model: ModelWithUrl): boolean {
420 0 : return false
421 : }
422 :
423 0 : return { stateFor, request, canResume, dispose }
424 : }
|