Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions browser_tests/tests/dialogs/modelImportProgressDialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => {
await expect(
toast.getByText('Cancelled', { exact: true }).first()
).toBeVisible()
await expect(toast.getByRole('button', { name: 'Close' })).toBeHidden()
await expect(toast.getByRole('button', { name: 'Close' })).toBeVisible()
})

await test.step('keep the terminal backend state rendered', async () => {
Expand Down Expand Up @@ -238,7 +238,7 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => {
await expect(
toast.getByText('Cancelled', { exact: true }).first()
).toBeVisible()
await expect(toast.getByRole('button', { name: 'Close' })).toBeHidden()
await expect(toast.getByRole('button', { name: 'Close' })).toBeVisible()
})

await test.step('settle the cancellation once the task lookup 404s', async () => {
Expand Down
11 changes: 7 additions & 4 deletions src/platform/assets/components/ModelImportProgressDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,22 +75,25 @@ describe('ModelImportProgressDialog cancellation', () => {
})
})

it('keeps provisional cancellations open for authoritative reconciliation', async () => {
it('allows a provisional cancellation to be dismissed', async () => {
const user = userEvent.setup()
const store = renderDialog()

store.downloadList[0].status = 'cancellation_pending'
await nextTick()

expect(screen.queryByRole('button', { name: 'Close' })).toBeNull()
expect(screen.getAllByText('Cancelled')).not.toHaveLength(0)
await user.click(screen.getByRole('button', { name: 'Close' }))

await waitFor(() => expect(store.hasDownloads).toBe(false))
expect(screen.queryByRole('status')).toBeNull()
})

it('restores the close control once a cancellation settles', async () => {
const store = renderDialog()

store.downloadList[0].status = 'cancellation_pending'
await nextTick()
expect(screen.queryByRole('button', { name: 'Close' })).toBeNull()
expect(screen.getByRole('button', { name: 'Close' })).toBeVisible()

// The store bounds how long a cancellation stays provisional, so the
// dialog cannot be pinned open without a close control until a reload.
Expand Down
4 changes: 2 additions & 2 deletions src/platform/assets/components/ModelImportProgressDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const activeFilterLabel = computed(() => {
})

function closeDialog() {
assetDownloadStore.clearFinishedDownloads()
assetDownloadStore.clearDismissibleDownloads()
isExpanded.value = false
}

Expand Down Expand Up @@ -279,7 +279,7 @@ async function cancelDownload(taskId: TaskId) {
</Button>

<Button
v-if="!isInProgress && !assetDownloadStore.hasPendingCancellation"
v-if="!isInProgress"
variant="muted-textonly"
size="icon"
:aria-label="t('g.close')"
Expand Down
142 changes: 115 additions & 27 deletions src/platform/assets/composables/useUploadModelWizard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,39 @@ import { useModelToNodeStore } from '@/stores/modelToNodeStore'

import { useUploadModelWizard } from './useUploadModelWizard'

vi.mock('@/platform/assets/services/assetService', () => ({
vi.mock<unknown>(import('@/platform/assets/services/assetService'), () => ({
assetService: {
getAssetMetadata: vi.fn(),
uploadAssetAsync: vi.fn(),
uploadAssetPreviewImage: vi.fn()
}
}))

vi.mock('@/platform/assets/importSources/civitaiImportSource', () => ({
civitaiImportSource: {
name: 'Civitai',
hostnames: ['civitai.com', 'civitai.red'],
fetchMetadata: vi.fn()
}
}))
vi.mock<unknown>(
import('@/platform/assets/importSources/civitaiImportSource'),
() => ({
civitaiImportSource: {
name: 'Civitai',
hostnames: ['civitai.com', 'civitai.red'],
fetchMetadata: vi.fn()
}
})
)

vi.mock<unknown>(
import('@/platform/assets/importSources/huggingfaceImportSource'),
() => ({
huggingfaceImportSource: {
name: 'HuggingFace',
hostnames: ['huggingface.co'],
fetchMetadata: vi.fn()
}
})
)

vi.mock('@/platform/assets/importSources/huggingfaceImportSource', () => ({
huggingfaceImportSource: {
name: 'HuggingFace',
hostnames: ['huggingface.co'],
fetchMetadata: vi.fn()
}
}))
vi.mock(import('@/scripts/api'))

vi.mock('@/scripts/api', () => ({
api: {
fetchApi: vi.fn(),
addEventListener: vi.fn(),
apiURL: vi.fn((path: string) => path),
getServerFeature: vi.fn(
(_name: string, defaultValue?: unknown) => defaultValue
)
}
}))

vi.mock('@/i18n', () => ({
vi.mock<unknown>(import('@/i18n'), () => ({
st: (_key: string, fallback: string) => fallback,
t: (key: string) => key,
te: () => false,
Expand All @@ -61,6 +58,12 @@ describe('useUploadModelWizard', () => {
const modelTypes = ref([{ name: 'Checkpoint', value: 'checkpoints' }])
const mountedApps: App<Element>[] = []

beforeEach(() => {
vi.mocked(api.getServerFeature).mockImplementation(
(_name, defaultValue) => defaultValue
)
})

function setupWithI18n<T>(factory: () => T): T {
let result: T | undefined
const host = document.createElement('div')
Expand Down Expand Up @@ -198,6 +201,91 @@ describe('useUploadModelWizard', () => {
expect(wizard.uploadError.value).toBe('Network error')
})

it('keeps watching a new upload while the previous completion refreshes', async () => {
const { assetService } =
await import('@/platform/assets/services/assetService')
vi.mocked(assetService.uploadAssetAsync)
.mockResolvedValueOnce({
type: 'async',
task: {
task_id: 'task-first',
status: 'created',
message: 'Download queued'
}
})
.mockResolvedValueOnce({
type: 'async',
task: {
task_id: 'task-second',
status: 'created',
message: 'Download queued'
}
})

let finishRefresh: (() => void) | undefined
const refreshPending = new Promise<void>((resolve) => {
finishRefresh = resolve
})
const assetsStore = useAssetsStore()
const modelToNodeStore = useModelToNodeStore()
vi.spyOn(modelToNodeStore, 'getAllNodeProviders').mockReturnValue([
fromPartial({ nodeDef: { name: 'CheckpointLoaderSimple' } })
])
vi.spyOn(assetsStore, 'updateModelsForNodeType').mockReturnValueOnce(
refreshPending
)

const wizard = setupUploadModelWizard(modelTypes)
wizard.wizardData.value.url = 'https://civitai.com/models/first'
wizard.selectedModelType.value = 'checkpoints'
await wizard.uploadModel()

const handler = vi
.mocked(api.addEventListener)
.mock.calls.findLast((call) => call[0] === 'asset_download')?.[1]
assert.exists(handler)
handler(
new CustomEvent('asset_download', {
detail: {
task_id: 'task-first',
asset_id: 'asset-first',
asset_name: 'first.safetensors',
bytes_total: 1000,
bytes_downloaded: 1000,
progress: 100,
status: 'completed'
}
})
)
await nextTick()

wizard.wizardData.value.url = 'https://civitai.com/models/second'
await wizard.uploadModel()
expect(wizard.uploadStatus.value).toBe('processing')

finishRefresh?.()
await refreshPending
await nextTick()

handler(
new CustomEvent('asset_download', {
detail: {
task_id: 'task-second',
asset_id: 'asset-second',
asset_name: 'second.safetensors',
bytes_total: 1000,
bytes_downloaded: 1000,
progress: 100,
status: 'completed'
}
})
)

await vi.waitFor(() => {
expect(wizard.uploadStatus.value).toBe('success')
})
})

it('recovers a provisionally cancelled upload when it completes authoritatively', async () => {
const { assetService } =
await import('@/platform/assets/services/assetService')
Expand Down
37 changes: 28 additions & 9 deletions src/platform/assets/composables/useUploadModelWizard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { computed, onScopeDispose, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import { useFeatureFlags } from '@/composables/useFeatureFlags'
Expand Down Expand Up @@ -85,6 +85,8 @@ export function useUploadModelWizard(
const uploadError = ref('')
const uploadTypeMismatch = ref<UploadModelTypeMismatch | null>(null)
let stopAsyncWatch: (() => void) | undefined
let activeAsyncTaskId: string | undefined
onScopeDispose(() => stopAsyncWatch?.())

const wizardData = ref<WizardData>({
url: '',
Expand Down Expand Up @@ -321,6 +323,9 @@ export function useUploadModelWizard(
}

isUploading.value = true
stopAsyncWatch?.()
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
stopAsyncWatch = undefined
activeAsyncTaskId = undefined
uploadTypeMismatch.value = null
let uploadSuccess: UploadModelSuccess | null = null

Expand Down Expand Up @@ -366,23 +371,35 @@ export function useUploadModelWizard(
status: 'processing'
}

stopAsyncWatch?.()
const watchState = { resolved: false }
const taskId = result.task.task_id
activeAsyncTaskId = taskId
const watchState: {
resolved: boolean
stop?: () => void
} = { resolved: false }
const stop = watch(
() =>
assetDownloadStore.downloadList.find(
(d) => d.taskId === result.task.task_id
)?.status,
assetDownloadStore.downloadList.find((d) => d.taskId === taskId)
?.status,
async (status) => {
if (activeAsyncTaskId !== taskId) {
watchState.stop?.()
return
}
if (status === 'completed') {
// `completed` is the only status the download store treats as
// immutable, so it is the only one worth stopping on.
watchState.resolved = true
uploadStatus.value = 'success'
uploadError.value = ''
await refreshModelCaches()
stopAsyncWatch?.()
stopAsyncWatch = undefined
watchState.stop?.()
if (stopAsyncWatch === watchState.stop) {
stopAsyncWatch = undefined
}
if (activeAsyncTaskId === taskId) {
activeAsyncTaskId = undefined
}
} else if (
status === 'failed' ||
status === 'cancellation_pending' ||
Expand All @@ -392,7 +409,7 @@ export function useUploadModelWizard(
// and lets an authoritative `completed` replace a confirmed
// `cancelled`, so this error screen can still be recovered from.
const download = assetDownloadStore.downloadList.find(
(d) => d.taskId === result.task.task_id
(d) => d.taskId === taskId
)
uploadStatus.value = 'error'
uploadError.value =
Expand All @@ -406,6 +423,7 @@ export function useUploadModelWizard(
},
{ immediate: true }
)
watchState.stop = stop
if (watchState.resolved) {
stop()
stopAsyncWatch = undefined
Expand Down Expand Up @@ -454,6 +472,7 @@ export function useUploadModelWizard(
function resetWizard() {
stopAsyncWatch?.()
stopAsyncWatch = undefined
activeAsyncTaskId = undefined
currentStep.value = 1
isFetchingMetadata.value = false
isUploading.value = false
Expand Down
11 changes: 5 additions & 6 deletions src/platform/tasks/services/taskService.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest'
import { assert, describe, expect, it, vi } from 'vitest'

import { api } from '@/scripts/api'

Expand Down Expand Up @@ -85,11 +85,10 @@ describe('taskService.getTask', () => {
)
const transient = await taskService.getTask('task-123')

expect(missing.ok).toBe(false)
expect(transient.ok).toBe(false)
if (!missing.ok) expect(missing.error).toBeInstanceOf(TaskNotFoundError)
if (!transient.ok)
expect(transient.error).not.toBeInstanceOf(TaskNotFoundError)
assert(!missing.ok)
assert(!transient.ok)
expect(missing.error).toBeInstanceOf(TaskNotFoundError)
expect(transient.error).not.toBeInstanceOf(TaskNotFoundError)
})

it('returns network failures as data', async () => {
Expand Down
Loading
Loading