import type { ComfyDownloadProgress } from '@comfyorg/comfyui-desktop-bridge-types' import { reportError } from '@comfyorg/telemetry/reportError' import { defineStore } from 'pinia' import { ref, shallowReactive, watch } from 'vue' import { getModelFileKey } from '@/platform/workflow/core/utils/modelRequirements' import { dispatchModelDownload, downloadModel, hostReportsModelDownloadProgress } from '@/platform/workflowErrors/missingModel/missingModelDownload' import type { ModelWithUrl } from '@/platform/workflowErrors/missingModel/missingModelDownload' import { useMissingModelStore } from '@/platform/workflowErrors/missingModel/missingModelStore' import type { MissingModelCandidate } from '@/platform/workflowErrors/missingModel/types' export type MissingModelDownloadState = | { status: 'idle' } | { status: 'requested' } | { status: 'pending' } | { status: 'downloading' paused: boolean receivedBytes: number | null totalBytes: number | null fraction: number | null } | { status: 'done' } | { status: 'failed' } interface HostDownload { name: string url: string state: MissingModelDownloadState jobId?: string jobEnded: boolean request?: number endedJobs: ReadonlySet } const IDLE: MissingModelDownloadState = { status: 'idle' } function validCount(value: number | undefined): number | null { return value !== undefined && Number.isFinite(value) && value >= 0 ? value : null } function progressFraction(progress: ComfyDownloadProgress): number | null { const received = validCount(progress.receivedBytes) const total = validCount(progress.totalBytes) if (received !== null && total !== null && total > 0 && received <= total) { return received / total } return Number.isFinite(progress.progress) && progress.progress >= 0 && progress.progress <= 1 ? progress.progress : null } function toDownloadState( progress: ComfyDownloadProgress ): MissingModelDownloadState | undefined { switch (progress.status) { case 'pending': return { status: 'pending' } case 'downloading': case 'paused': return { status: 'downloading', paused: progress.status === 'paused', receivedBytes: validCount(progress.receivedBytes), totalBytes: validCount(progress.totalBytes), fraction: progressFraction(progress) } case 'completed': return { status: 'done' } case 'error': return { status: 'failed' } case 'cancelled': return IDLE default: return undefined } } function isActive(state: MissingModelDownloadState): boolean { return ( state.status === 'requested' || state.status === 'pending' || state.status === 'downloading' ) } function isHostTerminal(status: ComfyDownloadProgress['status']): boolean { return status === 'completed' || status === 'error' || status === 'cancelled' } function acceptsEvent( current: HostDownload | undefined, progress: ComfyDownloadProgress ): boolean { if (!current) return true if (progress.id === undefined) { if (current.jobEnded && progress.status !== 'pending') return false } else if (current.endedJobs.has(progress.id)) { return false } return ( !isActive(current.state) || current.state.status === 'requested' || current.url === progress.url ) } function isBusy(download: HostDownload | undefined): boolean { return ( !!download && (isActive(download.state) || download.state.status === 'done') ) } function isMissingCandidate( candidates: readonly MissingModelCandidate[] | null, progress: Pick ): boolean { return !!candidates?.some( (candidate) => candidate.name === progress.filename && (progress.directory === undefined || candidate.directory === progress.directory) ) } function endedJobsAfter( current: HostDownload | undefined, progress: ComfyDownloadProgress ): ReadonlySet { const ended = current?.endedJobs ?? new Set() return isHostTerminal(progress.status) && progress.id !== undefined ? new Set([...ended, progress.id]) : ended } function nextHostDownload( current: HostDownload | undefined, progress: ComfyDownloadProgress, state: MissingModelDownloadState ): HostDownload { return { name: progress.filename, url: progress.url, state, jobId: isHostTerminal(progress.status) && progress.id === undefined ? undefined : (progress.id ?? current?.jobId), jobEnded: isHostTerminal(progress.status), endedJobs: endedJobsAfter(current, progress) } } type DownloadControl = 'pauseDownload' | 'resumeDownload' | 'cancelDownload' /** Desktop 2 model downloads, mirrored by destination wherever they started. */ export const useMissingModelDownloadStore = defineStore( 'missingModelDownload', () => { const missingModelStore = useMissingModelStore() const downloads = shallowReactive(new Map()) let refreshPending = false const tracking = ref(false) let trackingGeneration = 0 let nextRequest = 0 function stateFor(model: ModelWithUrl): MissingModelDownloadState { return downloads.get(getModelFileKey(model))?.state ?? IDLE } function resetWhere(matches: (download: HostDownload) => boolean) { for (const [key, download] of downloads) { if (matches(download)) downloads.set(key, { ...download, state: IDLE }) } } function flushRefresh() { if (!refreshPending || missingModelStore.isRefreshingMissingModels) return refreshPending = false void missingModelStore.refreshMissingModels() } function reopenFinished( models: readonly { name: string; directory?: string }[], only: (download: HostDownload) => boolean = () => true ) { const missing = new Set( models.flatMap(({ name, directory }) => directory ? [getModelFileKey({ name, directory })] : [] ) ) for (const [key, download] of downloads) { if ( download.state.status === 'done' && missing.has(key) && only(download) ) { downloads.set(key, { ...download, state: IDLE }) } } } function reopenStillMissing( candidates: readonly MissingModelCandidate[] | null ) { if (refreshPending || missingModelStore.isRefreshingMissingModels) return reopenFinished(candidates ?? []) } watch(() => missingModelStore.missingModelCandidates, reopenStillMissing) let finishedBeforeRefresh = new Set() watch( () => missingModelStore.isRefreshingMissingModels, (refreshing) => { if (refreshing) { finishedBeforeRefresh = new Set( [...downloads.values()].filter( (download) => download.state.status === 'done' ) ) return } const finished = finishedBeforeRefresh finishedBeforeRefresh = new Set() reopenFinished( missingModelStore.missingModelCandidates ?? [], (download) => finished.has(download) ) flushRefresh() } ) function keyFor(progress: ComfyDownloadProgress): string | undefined { if (progress.directory !== undefined) { return getModelFileKey({ name: progress.filename, directory: progress.directory }) } const matches = [...downloads].filter( ([, download]) => download.url === progress.url && download.name === progress.filename ) return matches.length === 1 ? matches[0][0] : undefined } function applyHostProgress(progress: ComfyDownloadProgress) { const state = toDownloadState(progress) const key = keyFor(progress) if (!state || key === undefined) return const current = downloads.get(key) if (!acceptsEvent(current, progress)) return const isMissing = isMissingCandidate( missingModelStore.missingModelCandidates, progress ) downloads.set(key, nextHostDownload(current, progress, state)) if (state.status === 'done' && current?.state.status !== 'done') { requestRefresh(isMissing) } } function requestRefresh(isMissing: boolean) { if (!isMissing) return refreshPending = true flushRefresh() } function startTracking(): () => void { if (!hostReportsModelDownloadProgress()) return () => undefined const subscription = ++trackingGeneration const stop = window.__comfyDesktop2?.onDownloadProgress?.((progress) => { if (subscription === trackingGeneration) applyHostProgress(progress) }) if (typeof stop !== 'function') { trackingGeneration++ return () => undefined } tracking.value = true return () => { tracking.value = false trackingGeneration++ try { stop() } catch (error) { reportError(error, { surface: 'platform', errorType: 'error_stopping_model_download_tracking' }) } finally { resetWhere(() => true) } } } function unreportedRequest(model: ModelWithUrl, request: number) { const current = downloads.get(getModelFileKey(model)) return current?.request === request && current.state.status === 'requested' ? current : undefined } function failRequest(model: ModelWithUrl, request: number) { const current = unreportedRequest(model, request) if (!current) return downloads.set(getModelFileKey(model), { ...current, state: { status: 'failed' } }) } function finishUnreportedRequest(model: ModelWithUrl, request: number) { const current = unreportedRequest(model, request) if (!current) return const isMissing = isMissingCandidate( missingModelStore.missingModelCandidates, { filename: model.name, directory: model.directory } ) downloads.set(getModelFileKey(model), { ...current, state: isMissing ? { status: 'done' } : IDLE, jobEnded: true }) requestRefresh(isMissing) } function reportStartFailure(error: unknown) { reportError(error, { surface: 'platform', errorType: 'error_starting_model_download', tags: { host: 'desktop2' } }) } function download(model: ModelWithUrl): void { if (!tracking.value || !hostReportsModelDownloadProgress()) { downloadModel(model, missingModelStore.folderPaths) return } const key = getModelFileKey(model) const current = downloads.get(key) if (isBusy(current)) return const request = ++nextRequest downloads.set(key, { name: model.name, url: model.url, state: { status: 'requested' }, jobEnded: false, request, endedJobs: current?.endedJobs ?? new Set() }) dispatchRequest(model, request) } function dispatchRequest(model: ModelWithUrl, request: number) { const outcome = dispatchModelDownload(model, {}) if (outcome.status === 'dispatch-failed') { reportStartFailure(outcome.error) } if (outcome.status !== 'host-requested') { failRequest(model, request) return } void outcome.hostResult.then( (accepted) => { if (accepted) finishUnreportedRequest(model, request) else failRequest(model, request) }, (error: unknown) => { reportStartFailure(error) failRequest(model, request) } ) } function controlRef(model: ModelWithUrl): string | undefined { const download = downloads.get(getModelFileKey(model)) if (!download || !isActive(download.state)) return undefined if ( download.jobId !== undefined && !download.endedJobs.has(download.jobId) ) return download.jobId const sharingUrl = [...downloads.values()].filter( (other) => other.url === download.url && isActive(other.state) ) return sharingUrl.length === 1 ? download.url : undefined } function canControl(model: ModelWithUrl, action: DownloadControl): boolean { return ( tracking.value && typeof window.__comfyDesktop2?.[action] === 'function' && controlRef(model) !== undefined ) } function reportControlFailure(error: unknown, action: DownloadControl) { reportError(error, { surface: 'platform', errorType: 'error_controlling_model_download', tags: { action } }) } function withdrawUnreportedRequest( model: ModelWithUrl, request: number | undefined ) { const current = request === undefined ? undefined : unreportedRequest(model, request) if (!current) return downloads.set(getModelFileKey(model), { ...current, state: IDLE }) } function control(model: ModelWithUrl, action: DownloadControl) { const target = controlRef(model) if (target === undefined) return const request = downloads.get(getModelFileKey(model))?.request try { void Promise.resolve(window.__comfyDesktop2?.[action]?.(target)).then( (accepted) => { if (accepted === false) { reportControlFailure(new Error(`Host refused ${action}`), action) } else if (action === 'cancelDownload') { withdrawUnreportedRequest(model, request) } }, (error: unknown) => reportControlFailure(error, action) ) } catch (error) { reportControlFailure(error, action) } } return { stateFor, download, startTracking, tracksHostProgress: () => tracking.value, reopenFinished, canControl, pause: (model: ModelWithUrl) => control(model, 'pauseDownload'), resume: (model: ModelWithUrl) => control(model, 'resumeDownload'), cancel: (model: ModelWithUrl) => control(model, 'cancelDownload') } } )