Line data Source code
1 : import type { Ref } from 'vue'
2 : import { computed, onScopeDispose, ref, watch } from 'vue'
3 : import { useI18n } from 'vue-i18n'
4 :
5 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
6 : import { st } from '@/i18n'
7 : import { civitaiImportSource } from '@/platform/assets/importSources/civitaiImportSource'
8 : import { huggingfaceImportSource } from '@/platform/assets/importSources/huggingfaceImportSource'
9 : import type {
10 : AssetItem,
11 : AssetMetadata
12 : } from '@/platform/assets/schemas/assetSchema'
13 : import { assetService } from '@/platform/assets/services/assetService'
14 : import type { ImportSource } from '@/platform/assets/types/importSource'
15 : import {
16 : getAssetFilename,
17 : stripModelTypePrefix,
18 : toModelTypeTag
19 : } from '@/platform/assets/utils/assetMetadataUtils'
20 : import { validateSourceUrl } from '@/platform/assets/utils/importSourceUtil'
21 : import { useAssetDownloadStore } from '@/stores/assetDownloadStore'
22 : import { useAssetsStore } from '@/stores/assetsStore'
23 : import { useModelToNodeStore } from '@/stores/modelToNodeStore'
24 :
25 : interface WizardData {
26 : url: string
27 : metadata?: AssetMetadata
28 : name: string
29 : tags: string[]
30 : previewImage?: string
31 : }
32 :
33 : interface ModelTypeOption {
34 : name: string
35 : value: string
36 : }
37 :
38 2355 : const MODEL_ROOT_TAG = 'models'
39 :
40 : export interface UploadModelSuccess {
41 : filename: string
42 : modelType?: string
43 : taskId?: string
44 : status: 'processing' | 'success'
45 : }
46 :
47 : export interface UploadModelTypeMismatch {
48 : importedModelType?: string
49 : importedModelTypeLabel?: string
50 : requiredModelType: string
51 : requiredModelTypeLabel: string
52 : }
53 :
54 : interface MissingModelUploadContext {
55 : kind: 'missing-model-resolution'
56 : missingModelName: string
57 : requiredModelType: string
58 : replacementTargets: Array<{
59 : nodeId: string
60 : nodeLabel: string
61 : widgetName: string
62 : }>
63 : }
64 :
65 : export type UploadModelDialogContext = MissingModelUploadContext
66 :
67 : interface UploadModelWizardOptions {
68 : requiredModelType?: string
69 : }
70 :
71 0 : export function useUploadModelWizard(
72 : modelTypes: Ref<ModelTypeOption[]>,
73 : options: UploadModelWizardOptions = {}
74 : ) {
75 0 : const { t } = useI18n()
76 0 : const { flags } = useFeatureFlags()
77 0 : const assetsStore = useAssetsStore()
78 0 : const assetDownloadStore = useAssetDownloadStore()
79 0 : const modelToNodeStore = useModelToNodeStore()
80 0 : const requiredModelType = options.requiredModelType
81 0 : const currentStep = ref(1)
82 0 : const isFetchingMetadata = ref(false)
83 0 : const isUploading = ref(false)
84 0 : const uploadStatus = ref<'processing' | 'success' | 'error'>()
85 0 : const uploadError = ref('')
86 0 : const uploadTypeMismatch = ref<UploadModelTypeMismatch | null>(null)
87 0 : let stopAsyncWatch: (() => void) | undefined
88 0 : let activeAsyncTaskId: string | undefined
89 0 : let uploadGeneration = 0
90 0 : let disposed = false
91 0 : const isStaleUpload = (generation: number) =>
92 : disposed || generation !== uploadGeneration
93 0 : onScopeDispose(() => {
94 0 : disposed = true
95 0 : uploadGeneration++
96 0 : stopAsyncWatch?.()
97 : })
98 :
99 0 : const wizardData = ref<WizardData>({
100 : url: '',
101 : name: '',
102 : tags: []
103 : })
104 :
105 0 : const selectedModelType = ref<string | undefined>(requiredModelType)
106 0 : const resolvedModelType = computed(
107 : () => requiredModelType ?? selectedModelType.value
108 : )
109 :
110 0 : const importSources: ImportSource[] = [
111 : civitaiImportSource,
112 : huggingfaceImportSource
113 : ]
114 :
115 : // Detected import source based on URL
116 0 : const detectedSource = computed(() => {
117 0 : const url = wizardData.value.url.trim()
118 0 : if (!url) return null
119 0 : return (
120 : importSources.find((source) => validateSourceUrl(url, source)) ?? null
121 : )
122 : })
123 :
124 : // Clear error when URL changes
125 0 : watch(
126 : () => wizardData.value.url,
127 : () => {
128 0 : uploadError.value = ''
129 0 : uploadTypeMismatch.value = null
130 : }
131 : )
132 :
133 0 : if (requiredModelType) {
134 0 : watch(
135 : selectedModelType,
136 : (value) => {
137 0 : if (value !== requiredModelType) {
138 0 : selectedModelType.value = requiredModelType
139 : }
140 : },
141 : { immediate: true }
142 : )
143 : }
144 :
145 : // Validation - only enable Continue when URL matches a supported source
146 0 : const canFetchMetadata = computed(() => {
147 0 : return detectedSource.value !== null
148 : })
149 :
150 0 : const canUploadModel = computed(() => {
151 0 : return !!resolvedModelType.value
152 : })
153 :
154 0 : async function fetchMetadata() {
155 0 : if (!canFetchMetadata.value) return
156 :
157 : // Clean and normalize URL
158 0 : let cleanedUrl = wizardData.value.url.trim()
159 0 : try {
160 0 : cleanedUrl = new URL(encodeURI(cleanedUrl)).toString()
161 : } catch {
162 : // If URL parsing fails, just use the trimmed input
163 : }
164 0 : wizardData.value.url = cleanedUrl
165 :
166 : // Validate URL belongs to a supported import source
167 : const source = detectedSource.value
168 0 : if (!source) {
169 0 : const supportedSources = importSources.map((s) => s.name).join(', ')
170 0 : uploadError.value = t('assetBrowser.unsupportedUrlSource', {
171 : sources: supportedSources
172 : })
173 0 : return
174 : }
175 :
176 0 : isFetchingMetadata.value = true
177 0 : try {
178 0 : const metadata = await assetService.getAssetMetadata(wizardData.value.url)
179 :
180 : // Decode URL-encoded filenames (e.g., Chinese characters)
181 0 : if (metadata.filename) {
182 0 : try {
183 0 : metadata.filename = decodeURIComponent(metadata.filename)
184 : } catch {
185 : // Keep original if decoding fails
186 : }
187 : }
188 0 : if (metadata.name) {
189 0 : try {
190 0 : metadata.name = decodeURIComponent(metadata.name)
191 : } catch {
192 : // Keep original if decoding fails
193 : }
194 : }
195 :
196 0 : wizardData.value.metadata = metadata
197 :
198 : // Pre-fill name from metadata
199 0 : wizardData.value.name = metadata.filename || metadata.name || ''
200 :
201 : // Store preview image if available
202 0 : wizardData.value.previewImage = metadata.preview_image
203 :
204 : // Pre-fill model type from metadata tags if available
205 0 : if (requiredModelType) {
206 0 : selectedModelType.value = requiredModelType
207 0 : } else if (metadata.tags && metadata.tags.length > 0) {
208 0 : wizardData.value.tags = metadata.tags
209 : // Try to detect model type from tags
210 0 : const typeTag = metadata.tags.find((tag) =>
211 : modelTypes.value.some((type) => type.value === tag)
212 : )
213 0 : if (typeTag) {
214 0 : selectedModelType.value = typeTag
215 : }
216 : }
217 :
218 0 : currentStep.value = 2
219 : } catch (error) {
220 0 : console.error('Failed to retrieve metadata:', error)
221 0 : uploadError.value =
222 : error instanceof Error
223 : ? error.message
224 : : st(
225 : 'assetBrowser.uploadModelFailedToRetrieveMetadata',
226 : 'Failed to retrieve metadata. Please check the link and try again.'
227 : )
228 0 : currentStep.value = 1
229 : } finally {
230 0 : isFetchingMetadata.value = false
231 : }
232 : }
233 :
234 0 : async function uploadPreviewImage(
235 : filename: string
236 : ): Promise<{ id: string; createdNew: boolean } | undefined> {
237 0 : if (!wizardData.value.previewImage) return undefined
238 :
239 0 : try {
240 0 : const baseFilename = filename.split('.')[0]
241 0 : let extension = 'png'
242 0 : const mimeMatch = wizardData.value.previewImage.match(
243 : /^data:image\/([^;]+);/
244 : )
245 0 : if (mimeMatch) {
246 0 : extension = mimeMatch[1] === 'jpeg' ? 'jpg' : mimeMatch[1]
247 : }
248 :
249 0 : const previewAsset = await assetService.uploadAssetFromBase64({
250 : data: wizardData.value.previewImage,
251 : name: `${baseFilename}_preview.${extension}`,
252 : tags: ['preview']
253 : })
254 0 : return {
255 : id: previewAsset.id,
256 : createdNew: previewAsset.created_new
257 : }
258 : } catch (error) {
259 0 : console.error('Failed to upload preview image:', error)
260 0 : return undefined
261 : }
262 : }
263 :
264 0 : async function refreshModelCaches(modelType = resolvedModelType.value) {
265 0 : if (!modelType) return
266 :
267 0 : const providers = modelToNodeStore.getAllNodeProviders(modelType)
268 : const results = await Promise.allSettled(
269 : providers.map((provider) =>
270 : assetsStore.updateModelsForNodeType(provider.nodeDef.name)
271 : )
272 : )
273 0 : results.forEach((result, index) => {
274 0 : if (result.status === 'rejected') {
275 0 : console.error(
276 : `Failed to refresh ${providers[index].nodeDef.name}:`,
277 : result.reason
278 : )
279 : }
280 : })
281 : }
282 :
283 0 : function getModelTypeLabel(modelType: string): string {
284 0 : return (
285 : modelTypes.value.find((type) => type.value === modelType)?.name ??
286 : modelType
287 : )
288 : }
289 :
290 0 : function getImportedModelType(asset: AssetItem): string | undefined {
291 0 : const subtypeTags = asset.tags
292 : .filter((tag) => tag !== MODEL_ROOT_TAG)
293 : .map(stripModelTypePrefix)
294 0 : return (
295 : subtypeTags.find((tag) =>
296 : modelTypes.value.some((type) => type.value === tag)
297 : ) ?? subtypeTags[0]
298 : )
299 : }
300 :
301 0 : function blockMismatchedImportedModel(
302 : asset: AssetItem,
303 : requiredType: string
304 : ): boolean {
305 0 : if (asset.tags.map(stripModelTypePrefix).includes(requiredType))
306 0 : return false
307 :
308 0 : const importedType = getImportedModelType(asset)
309 0 : uploadStatus.value = 'error'
310 0 : uploadError.value = ''
311 0 : uploadTypeMismatch.value = {
312 : importedModelType: importedType,
313 : importedModelTypeLabel: importedType
314 : ? getModelTypeLabel(importedType)
315 : : undefined,
316 : requiredModelType: requiredType,
317 : requiredModelTypeLabel: getModelTypeLabel(requiredType)
318 : }
319 0 : return true
320 : }
321 :
322 0 : function watchAsyncUpload(
323 : taskId: string,
324 : filename: string,
325 : modelType: string | undefined
326 : ): UploadModelSuccess {
327 0 : uploadStatus.value = 'processing'
328 0 : const uploadSuccess: UploadModelSuccess = {
329 : filename,
330 : modelType,
331 : taskId,
332 : status: 'processing'
333 : }
334 :
335 0 : activeAsyncTaskId = taskId
336 0 : const watchState: { resolved: boolean; stop?: () => void } = {
337 : resolved: false
338 : }
339 0 : const stop = watch(
340 : () =>
341 : assetDownloadStore.downloadList.find((d) => d.taskId === taskId)
342 : ?.status,
343 : async (status) => {
344 0 : if (activeAsyncTaskId !== taskId) {
345 0 : watchState.stop?.()
346 0 : return
347 : }
348 0 : if (status === 'completed') {
349 0 : watchState.resolved = true
350 0 : uploadStatus.value = 'success'
351 0 : uploadError.value = ''
352 0 : await refreshModelCaches()
353 0 : watchState.stop?.()
354 0 : if (stopAsyncWatch === watchState.stop) stopAsyncWatch = undefined
355 0 : if (activeAsyncTaskId === taskId) activeAsyncTaskId = undefined
356 0 : return
357 : }
358 0 : if (
359 : status === 'failed' ||
360 : status === 'cancellation_pending' ||
361 : status === 'cancelled'
362 : ) {
363 : // Keep watching because an authoritative completion can replace
364 : // provisional failure and cancellation states.
365 0 : const download = assetDownloadStore.downloadList.find(
366 : (d) => d.taskId === taskId
367 : )
368 0 : uploadStatus.value = 'error'
369 0 : uploadError.value =
370 : status === 'cancelled' || status === 'cancellation_pending'
371 : ? t('electronFileDownload.cancelled')
372 : : download?.error ||
373 : t('assetBrowser.downloadFailed', {
374 : name: download?.assetName || ''
375 : })
376 : }
377 : },
378 : { immediate: true }
379 : )
380 0 : watchState.stop = stop
381 0 : if (watchState.resolved) {
382 0 : stop()
383 0 : stopAsyncWatch = undefined
384 : } else {
385 0 : stopAsyncWatch = stop
386 : }
387 0 : return uploadSuccess
388 : }
389 :
390 0 : async function uploadModel(): Promise<UploadModelSuccess | null> {
391 0 : if (isUploading.value) return null
392 0 : if (!canUploadModel.value) {
393 0 : return null
394 : }
395 :
396 0 : const source = detectedSource.value
397 0 : if (!source) {
398 0 : uploadError.value = t('assetBrowser.noValidSourceDetected')
399 0 : return null
400 : }
401 :
402 0 : isUploading.value = true
403 0 : const generation = ++uploadGeneration
404 0 : stopAsyncWatch?.()
405 0 : stopAsyncWatch = undefined
406 0 : activeAsyncTaskId = undefined
407 0 : uploadTypeMismatch.value = null
408 0 : let uploadSuccess: UploadModelSuccess | null = null
409 :
410 0 : try {
411 0 : const modelType = resolvedModelType.value
412 0 : const subtypeTag =
413 : modelType && flags.supportsModelTypeTags
414 : ? toModelTypeTag(modelType)
415 : : modelType
416 0 : const tags = subtypeTag ? [MODEL_ROOT_TAG, subtypeTag] : [MODEL_ROOT_TAG]
417 0 : const filename =
418 : wizardData.value.metadata?.filename ||
419 : wizardData.value.metadata?.name ||
420 : 'model'
421 :
422 0 : const preview = await uploadPreviewImage(filename)
423 0 : if (isStaleUpload(generation)) {
424 0 : if (preview?.createdNew) {
425 0 : try {
426 0 : await assetService.deleteAsset(preview.id)
427 : } catch (error) {
428 0 : console.error('Failed to clean up stale preview image:', error)
429 : }
430 : }
431 0 : return null
432 : }
433 :
434 0 : const userMetadata = {
435 : source: source.type,
436 : source_url: wizardData.value.url,
437 : model_type: modelType
438 : }
439 :
440 0 : const result = await assetService.uploadAssetAsync({
441 : source_url: wizardData.value.url,
442 : tags,
443 : user_metadata: userMetadata,
444 : preview_id: preview?.id
445 : })
446 :
447 0 : if (result.type === 'async' && result.task.status !== 'completed') {
448 0 : if (modelType) {
449 0 : assetDownloadStore.trackDownload(
450 : result.task.task_id,
451 : modelType,
452 : filename
453 : )
454 : }
455 : }
456 :
457 0 : if (isStaleUpload(generation)) {
458 0 : if (result.type === 'sync' || result.task.status === 'completed') {
459 0 : await refreshModelCaches(modelType)
460 : }
461 0 : return null
462 : }
463 :
464 0 : if (result.type === 'async' && result.task.status !== 'completed') {
465 0 : uploadSuccess = watchAsyncUpload(
466 : result.task.task_id,
467 : filename,
468 : modelType
469 : )
470 : } else {
471 0 : if (
472 : requiredModelType &&
473 : result.type === 'sync' &&
474 : modelType &&
475 : blockMismatchedImportedModel(result.asset, modelType)
476 : ) {
477 0 : currentStep.value = 3
478 0 : return null
479 : }
480 :
481 0 : uploadStatus.value = 'success'
482 0 : await refreshModelCaches()
483 0 : if (isStaleUpload(generation)) return null
484 0 : uploadSuccess = {
485 : filename:
486 : result.type === 'sync' ? getAssetFilename(result.asset) : filename,
487 : modelType,
488 : status: 'success'
489 : }
490 : }
491 0 : currentStep.value = 3
492 : } catch (error) {
493 0 : if (isStaleUpload(generation)) return null
494 0 : console.error('Failed to upload asset:', error)
495 0 : uploadStatus.value = 'error'
496 0 : uploadError.value =
497 : error instanceof Error ? error.message : 'Failed to upload model'
498 0 : currentStep.value = 3
499 : } finally {
500 0 : if (!isStaleUpload(generation)) {
501 0 : isUploading.value = false
502 : }
503 : }
504 0 : return uploadSuccess
505 : }
506 :
507 0 : function goToPreviousStep() {
508 0 : if (currentStep.value > 1) {
509 0 : currentStep.value = currentStep.value - 1
510 : }
511 : }
512 :
513 0 : function resetWizard() {
514 0 : uploadGeneration++
515 0 : stopAsyncWatch?.()
516 0 : stopAsyncWatch = undefined
517 0 : activeAsyncTaskId = undefined
518 0 : currentStep.value = 1
519 0 : isFetchingMetadata.value = false
520 0 : isUploading.value = false
521 0 : uploadStatus.value = undefined
522 0 : uploadError.value = ''
523 0 : uploadTypeMismatch.value = null
524 0 : wizardData.value = {
525 : url: '',
526 : name: '',
527 : tags: []
528 : }
529 0 : selectedModelType.value = requiredModelType
530 : }
531 :
532 0 : return {
533 : // State
534 : currentStep,
535 : isFetchingMetadata,
536 : isUploading,
537 : uploadStatus,
538 : uploadError,
539 : uploadTypeMismatch,
540 : wizardData,
541 : selectedModelType,
542 :
543 : // Computed
544 : canFetchMetadata,
545 : canUploadModel,
546 : detectedSource,
547 :
548 : // Actions
549 : fetchMetadata,
550 : uploadModel,
551 : goToPreviousStep,
552 : resetWizard
553 : }
554 : }
|