diff --git a/browser_tests/tests/agent/agentAttachmentUpload.spec.ts b/browser_tests/tests/agent/agentAttachmentUpload.spec.ts new file mode 100644 index 00000000000..e7e3160f701 --- /dev/null +++ b/browser_tests/tests/agent/agentAttachmentUpload.spec.ts @@ -0,0 +1,63 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' + +test.describe('Agent attachment cancellation', { tag: '@cloud' }, () => { + test('closing the panel removes a pending upload and preserves a sendable draft', async ({ + comfyPage, + agentPanel + }) => { + const page = comfyPage.page + let releaseUpload = () => {} + const uploadHeld = new Promise((resolve) => { + releaseUpload = resolve + }) + await page.route('**/api/upload/image', async (route) => { + await uploadHeld + await route.abort() + }) + + try { + const openButton = page.getByRole('button', { + name: enMessages.agent.entryButton, + exact: true + }) + await openButton.click() + await agentPanel.selectWorkflow() + const panel = page.locator('#agent-panel-root') + const composer = panel.getByRole('textbox', { name: /^Describe ideas/ }) + const send = panel.getByRole('button', { name: 'Send', exact: true }) + await composer.fill('Keep this draft') + await expect(send).toBeEnabled() + + const uploadReceived = page.waitForRequest('**/api/upload/image') + await panel.getByTestId('agent-file-input').setInputFiles({ + name: 'pending.mp4', + mimeType: 'video/mp4', + buffer: Buffer.from('pending upload') + }) + await uploadReceived + await expect( + panel.getByTestId('composer-asset-section').getByText('pending.mp4') + ).toBeVisible() + await expect(send).toBeDisabled() + + await panel + .getByRole('button', { name: enMessages.g.close, exact: true }) + .click() + await expect(panel).toHaveCount(0) + await openButton.click() + + await expect(composer).toHaveText('Keep this draft') + await expect(panel.getByText('pending.mp4', { exact: true })).toHaveCount( + 0 + ) + await expect(send).toBeEnabled() + } finally { + releaseUpload() + await page.unrouteAll({ behavior: 'wait' }) + } + }) +}) diff --git a/browser_tests/tests/agent/agentPanel.spec.ts b/browser_tests/tests/agent/agentPanel.spec.ts index f2bf6f9b61b..64f4a3dc89e 100644 --- a/browser_tests/tests/agent/agentPanel.spec.ts +++ b/browser_tests/tests/agent/agentPanel.spec.ts @@ -300,6 +300,62 @@ test.describe('In-App Agent panel', { tag: '@cloud' }, () => { .toBeLessThanOrEqual(1) }) + test('uses the server upload limit for Agent file attachments', async ({ + comfyPage, + agentPanel + }) => { + test.setTimeout(60_000) + const page = comfyPage.page + let uploadCount = 0 + await page.route('**/api/upload/image', async (route) => { + uploadCount += 1 + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + name: 'uploaded_movie.mp4', + subfolder: '', + type: 'input' + }) + }) + }) + await page.evaluate(() => { + window.app!.api.serverFeatureFlags.value = { + ...window.app!.api.serverFeatureFlags.value, + max_upload_size: 24 * 1024 * 1024 + } + }) + + await agentPanel.open() + const panel = page.locator('#agent-panel-root') + const fileInput = panel.getByTestId('agent-file-input') + + const uploadResponse = page.waitForResponse('**/api/upload/image') + await fileInput.setInputFiles({ + name: 'movie.mp4', + mimeType: 'video/mp4', + buffer: Buffer.alloc(21 * 1024 * 1024) + }) + expect((await uploadResponse).ok()).toBe(true) + await expect( + panel.getByTestId('composer-asset-section').getByText('movie.mp4') + ).toBeVisible() + await expect.poll(() => uploadCount).toBe(1) + + await fileInput.setInputFiles({ + name: 'too-large.mp4', + mimeType: 'video/mp4', + buffer: Buffer.alloc(25 * 1024 * 1024) + }) + await expect( + page.getByText('too-large.mp4 is larger than 24 MB') + ).toBeVisible() + await expect(panel.getByText('too-large.mp4', { exact: true })).toHaveCount( + 0 + ) + await expect.poll(() => uploadCount).toBe(1) + }) + test('exits node selection when the active workflow changes', async ({ comfyPage }) => { diff --git a/docs/adr/ASSETS-DRAG-DROP-0035-asset-card-drag-uses-file-url.md b/docs/adr/ASSETS-DRAG-DROP-0035-asset-card-drag-uses-file-url.md index 1948e9e162f..73ffd25049c 100644 --- a/docs/adr/ASSETS-DRAG-DROP-0035-asset-card-drag-uses-file-url.md +++ b/docs/adr/ASSETS-DRAG-DROP-0035-asset-card-drag-uses-file-url.md @@ -70,8 +70,9 @@ after the last URL segment, which for a content URL is the literal `content`. an asset onto the agent prompt did nothing while the panel was in list view and worked in grid view. 5. A non-OK response is not a file, and the user is told. `fetchDroppedAsset` - returns `undefined` on `!response.ok` (status-based, never content-type - sniffing). The canvas drop handler, when a drop that carried the + rejects on `!response.ok` (status-based, never content-type sniffing), and + callers choose whether to surface or gracefully ignore that failure. The + canvas drop handler, when a drop that carried the asset-info flavour yields no file, reports the failure through `reportError` and shows a toast instead of a silent no-op. Drops that never carried asset-info (plain links from elsewhere) stay silent. diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 38eac3d619d..d2c941068d8 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -5244,6 +5244,8 @@ "addFromAssets": "Drag in asset from asset panel", "assetNotAttachable": "Images, video, audio, 3D models, and text files can be attached", "attachmentTooLarge": "{name} is larger than {limit}", + "attachmentBatchLimit": "{count} file was not added because the upload queue limit is {limit}. | {count} files were not added because the upload queue limit is {limit}.", + "attachmentsTooLarge": "{count} file exceeds the upload size limit. | {count} files exceed the upload size limit.", "attachmentUploadFailed": "{name} could not be uploaded", "mention": "Mention a node", "changeWorkflowForChat": "Change the workflow that the agent can edit", diff --git a/src/stores/assetsStore.ts b/src/stores/assetsStore.ts index bc1381b0c05..3e2bbff5f6c 100644 --- a/src/stores/assetsStore.ts +++ b/src/stores/assetsStore.ts @@ -283,6 +283,30 @@ export const useAssetsStore = defineStore('assets', () => { const inputAssets = ref>(undefined!) const outputAssets = ref>(undefined!) + let inputRefreshDirty = false + let inputRefresh: Promise | undefined + + function refreshInputAssets(): Promise { + inputRefreshDirty = true + inputRefresh ??= (async () => { + for (;;) { + inputRefreshDirty = false + try { + await inputAssets.value.loadNew() + } catch { + // A coalesced request still owns a trailing pass even when the + // current refresh fails. + } + // The flag can change while the awaited refresh is in flight. + // oxlint-disable-next-line typescript/no-unnecessary-condition + if (inputRefreshDirty) continue + + inputRefresh = undefined + return + } + })() + return inputRefresh + } let assetsScope: EffectScope | undefined watch( () => flags.assetsEnabled, @@ -913,6 +937,7 @@ export const useAssetsStore = defineStore('assets', () => { return { // States inputAssets, + refreshInputAssets, outputAssets, invalidateAll, diff --git a/src/utils/__tests__/eventUtils.test.ts b/src/utils/__tests__/eventUtils.test.ts index e193701a6fa..49102a3ce7c 100644 --- a/src/utils/__tests__/eventUtils.test.ts +++ b/src/utils/__tests__/eventUtils.test.ts @@ -1,7 +1,96 @@ -import { extractFilesFromDragEvent, getDroppedAsset } from '@/utils/eventUtils' +import { + extractFilesFromDragEvent, + fetchDroppedAsset, + fetchTrustedDroppedAsset, + getDroppedAsset +} from '@/utils/eventUtils' import { beforeEach, describe, expect, it, vi } from 'vitest' describe('eventUtils', () => { + it('rejects a declared oversized dropped asset before buffering its body', async () => { + const blob = vi.fn() + const cancel = vi.fn(async () => undefined) + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ + ok: true, + headers: new Headers({ 'Content-Length': '101' }), + body: { cancel }, + blob + })) + ) + + await expect( + fetchDroppedAsset( + { name: 'large.png', uri: '/api/view?filename=large.png' }, + undefined, + 100 + ) + ).rejects.toThrow('Dropped asset exceeds 100 bytes') + expect(blob).not.toHaveBeenCalled() + expect(cancel).toHaveBeenCalledOnce() + }) + + it('cancels an unsuccessful dropped-asset response', async () => { + const cancel = vi.fn(async () => undefined) + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ + ok: false, + status: 503, + body: { cancel } + })) + ) + + await expect( + fetchDroppedAsset({ + name: 'asset.png', + uri: '/api/view?filename=asset.png' + }) + ).rejects.toThrow('Dropped asset fetch failed with HTTP 503') + expect(cancel).toHaveBeenCalledOnce() + }) + + it.for([ + 'https://example.com/api/view?filename=private.png', + '/api/settings', + 'data:text/plain,private' + ])('rejects an untrusted dropped-asset URI: %s', async (uri) => { + const fetchSpy = vi.fn() + vi.stubGlobal('fetch', fetchSpy) + + await expect( + fetchTrustedDroppedAsset({ name: 'asset.png', uri }) + ).resolves.toBeUndefined() + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('cancels an unknown-length stream once its byte limit is crossed', async () => { + let cancelled = false + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(60)) + controller.enqueue(new Uint8Array(50)) + }, + cancel() { + cancelled = true + } + }) + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(body, { status: 200 })) + ) + + await expect( + fetchDroppedAsset( + { name: 'streamed.png', uri: '/api/view?filename=streamed.png' }, + undefined, + 100 + ) + ).rejects.toThrow('Dropped asset exceeds 100 bytes') + expect(cancelled).toBe(true) + }) + describe('extractFilesFromDragEvent', () => { let fetchSpy: ReturnType @@ -106,7 +195,7 @@ describe('eventUtils', () => { }) it('should fetch URI and return as File when text/uri-list is present', async () => { - const uri = 'https://example.com/api/view?filename=test.png&type=input' + const uri = '/api/view?filename=test.png&type=input' const imageBlob = new Blob([new Uint8Array([0x89, 0x50])], { type: 'image/png' }) @@ -126,7 +215,7 @@ describe('eventUtils', () => { }) it('should handle text/x-moz-url type', async () => { - const uri = 'https://example.com/api/view?filename=test.png&type=input' + const uri = '/api/view?filename=test.png&type=input' const imageBlob = new Blob([new Uint8Array([0x89, 0x50])], { type: 'image/png' }) @@ -188,7 +277,7 @@ describe('eventUtils', () => { ) it('should return empty array when URI fetch fails', async () => { - const uri = 'https://example.com/api/view?filename=test.png&type=input' + const uri = '/api/view?filename=test.png&type=input' fetchSpy.mockRejectedValue(new TypeError('Failed to fetch')) const dataTransfer = new DataTransfer() @@ -219,6 +308,7 @@ describe('eventUtils', () => { expect(getDroppedAsset(dataTransfer)).toEqual({ name: 'My asset', + filename: 'asset.png', uri: 'http://localhost/api/view?x=1', ref: 'stored-asset.png', kind: 'image', @@ -239,6 +329,7 @@ describe('eventUtils', () => { expect(getDroppedAsset(dataTransfer)).toEqual({ name: 'asset.mp4', + filename: 'asset.mp4', uri: undefined, ref: 'stored-asset.mp4', kind: 'video', diff --git a/src/utils/eventUtils.ts b/src/utils/eventUtils.ts index 3dc5be6e58a..41cebaa3ed6 100644 --- a/src/utils/eventUtils.ts +++ b/src/utils/eventUtils.ts @@ -3,12 +3,29 @@ import { parseAssetInfo } from '@/platform/assets/schemas/mediaAssetSchema' export interface DroppedAsset { name: string + filename?: string uri?: string ref?: string kind?: MediaKind previewUrl?: string } +class DroppedAssetFetchError extends Error { + constructor(status: number) { + super(`Dropped asset fetch failed with HTTP ${status}`) + this.name = 'DroppedAssetFetchError' + } +} + +export class DroppedAssetTooLargeError extends RangeError { + constructor(readonly maxBytes: number) { + super(`Dropped asset exceeds ${maxBytes} bytes`) + this.name = 'DroppedAssetTooLargeError' + } +} + +const MAX_DROPPED_ASSET_BYTES = 100 * 1024 * 1024 + export function getDroppedAsset( dataTransfer: DataTransfer ): DroppedAsset | undefined { @@ -24,6 +41,7 @@ export function getDroppedAsset( return uri || ref ? { name: name ?? ref ?? uri!, + filename: asset?.filename, uri, ref, kind: asset?.media_kind, @@ -32,18 +50,93 @@ export function getDroppedAsset( : undefined } -export async function fetchDroppedAsset({ - name, - uri -}: DroppedAsset): Promise { +export async function fetchDroppedAsset( + { name, uri }: DroppedAsset, + signal?: AbortSignal, + maxBytes?: number +): Promise { if (!uri) return undefined - try { - const response = await fetch(uri) - if (!response.ok) return undefined + const response = await fetch(uri, { signal }) + if (!response.ok) { + await cancelResponseBody(response) + throw new DroppedAssetFetchError(response.status) + } + return fileFromResponse(response, name, maxBytes) +} + +export async function fetchTrustedDroppedAsset( + asset: DroppedAsset, + signal?: AbortSignal, + maxBytes?: number +): Promise { + if (!asset.uri) return undefined + const url = new URL(asset.uri, window.location.href) + if ( + !['http:', 'https:'].includes(url.protocol) || + url.origin !== window.location.origin || + !url.pathname.endsWith('/api/view') + ) + return undefined + return fetchDroppedAsset({ ...asset, uri: url.href }, signal, maxBytes) +} + +async function fileFromResponse( + response: Response, + name: string, + maxBytes?: number +): Promise { + const contentLengthHeader = response.headers.get('Content-Length') + const contentLength = + contentLengthHeader === null ? undefined : Number(contentLengthHeader) + if ( + maxBytes !== undefined && + contentLength !== undefined && + Number.isFinite(contentLength) && + contentLength > maxBytes + ) { + await cancelResponseBody(response) + throw new DroppedAssetTooLargeError(maxBytes) + } + + if (maxBytes === undefined || !response.body) { const blob = await response.blob() + if (maxBytes !== undefined && blob.size > maxBytes) + throw new DroppedAssetTooLargeError(maxBytes) return new File([blob], name, { type: blob.type }) + } + + const reader = response.body.getReader() + const chunks: ArrayBuffer[] = [] + let bytesRead = 0 + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + bytesRead += value.byteLength + if (bytesRead > maxBytes) { + try { + await reader.cancel() + } catch { + // The size-policy error remains authoritative when teardown fails. + } + throw new DroppedAssetTooLargeError(maxBytes) + } + chunks.push(value.slice().buffer) + } + } finally { + reader.releaseLock() + } + const blob = new Blob(chunks, { + type: response.headers.get('Content-Type') ?? undefined + }) + return new File([blob], name, { type: blob.type }) +} + +async function cancelResponseBody(response: Response): Promise { + try { + await response.body?.cancel() } catch { - return undefined + // The response is already being rejected, so cancellation is best effort. } } @@ -62,7 +155,11 @@ export async function extractFilesFromDragEvent( const asset = getDroppedAsset(event.dataTransfer) if (!asset) return [] - const file = await fetchDroppedAsset(asset) + const file = await fetchDroppedAsset( + asset, + undefined, + MAX_DROPPED_ASSET_BYTES + ).catch(() => undefined) return file ? [file] : [] } diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 17551d40caf..e21aacb5f52 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -1317,6 +1317,74 @@ describe('AgentPanelRoot attach flow', () => { expect(screen.getByRole('button', { name: 'cat.png' })).toBeInTheDocument() }) + it('rejects an upload response that omits the stored filename', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + if (url.endsWith('/api/upload/image')) { + return json(200, { subfolder: '', type: 'input' }) + } + return json(200, { data: [] }) + }) + ) + + renderWithSelectedTarget() + + await openAddMenu() + await userEvent.click( + await screen.findByRole('menuitem', { + name: i18n.global.t('agent.attachFiles') + }) + ) + await userEvent.upload( + screen.getByTestId('agent-file-input'), + new File(['x'], 'cat.png', { type: 'image/png' }) + ) + + await vi.waitFor(() => + expect(screen.queryByText('cat.png')).not.toBeInTheDocument() + ) + expect(useToastStore().messagesToAdd).toContainEqual( + expect.objectContaining({ detail: 'cat.png could not be uploaded' }) + ) + }) + + it('uses the stored upload location and releases the local preview', async () => { + const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url.endsWith('/api/upload/image') + ? json(200, { + name: 'stored.png', + subfolder: 'nested folder', + type: 'input' + }) + : json(200, { data: [] }) + ) + ) + renderWithSelectedTarget() + + await userEvent.upload( + screen.getByTestId('agent-file-input'), + new File(['x'], 'cat.png', { type: 'image/png' }) + ) + + const preview = await screen.findByAltText('cat.png') + expect(preview.getAttribute('src')).toContain( + '/api/view?filename=stored.png&type=input&subfolder=nested+folder' + ) + expect(useAgentComposerStore().attachments).toEqual([ + expect.objectContaining({ + ref: 'stored.png', + subfolder: 'nested folder', + uploadType: 'input' + }) + ]) + expect(revoke).toHaveBeenCalledWith('blob:mock-url') + revoke.mockRestore() + }) + it('uploads a picked video above 20MB when the server permits it', async () => { getServerFeature.mockReturnValue(100 * 1024 * 1024) const uploaded = stubUploadFetch() @@ -1414,13 +1482,13 @@ describe('AgentPanelRoot attach flow', () => { expect(useToastStore().messagesToAdd).toContainEqual( expect.objectContaining({ severity: 'warn', - detail: 'movie.mp4 is larger than 24MB' + detail: 'movie.mp4 is larger than 24 MB' }) ) expect(screen.queryByText('movie.mp4')).not.toBeInTheDocument() }) - it('keeps the image limit at 20MB when the server permits more', async () => { + it('uses a larger server limit for non-video attachments', async () => { getServerFeature.mockReturnValue(100 * 1024 * 1024) const uploaded = stubUploadFetch() renderWithSelectedTarget() @@ -1428,17 +1496,37 @@ describe('AgentPanelRoot attach flow', () => { const image = fileOfSize('huge.png', MAX_ATTACHMENT_BYTES + 1, 'image/png') dispatchDrag(screen.getByRole('textbox'), 'drop', { files: [image] }) - await nextTick() - expect(uploaded).toEqual([]) - expect(useToastStore().messagesToAdd).toContainEqual( - expect.objectContaining({ - severity: 'warn', - detail: 'huge.png is larger than 20MB' - }) - ) + expect( + within(await screen.findByTestId('composer-asset-section')).getByText( + 'huge.png' + ) + ).toBeInTheDocument() + await vi.waitFor(() => expect(uploaded).toEqual(['huge.png'])) }) + it.for([null, '104857600', Number.NaN, -1, 0])( + 'uses the conservative limit for malformed server value %s', + async (serverLimit) => { + getServerFeature.mockReturnValue(serverLimit) + stubUploadFetch() + renderWithSelectedTarget() + + const image = fileOfSize( + 'huge.png', + MAX_ATTACHMENT_BYTES + 1, + 'image/png' + ) + dispatchDrag(screen.getByRole('textbox'), 'drop', { files: [image] }) + await nextTick() + + expect(screen.queryByText('huge.png')).not.toBeInTheDocument() + expect(useToastStore().messagesToAdd).toContainEqual( + expect.objectContaining({ detail: 'huge.png is larger than 20 MB' }) + ) + } + ) + it('uploads a dropped video above 20MB when the server permits it', async () => { getServerFeature.mockReturnValue(100 * 1024 * 1024) const uploaded = stubUploadFetch() @@ -1528,13 +1616,156 @@ describe('AgentPanelRoot attach flow', () => { await vi.waitFor(() => expect(refresh).toHaveBeenCalled()) }) - it('keeps the 20MB limit for an oversize audio file', async () => { - getServerFeature.mockReturnValue(100 * 1024 * 1024) + it('coalesces concurrent upload refreshes with one trailing pass', async () => { + const uploaded = stubUploadFetch() + renderWithSelectedTarget() + await nextTick() + let releaseFirstRefresh: () => void = () => {} + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFirstRefresh = () => resolve(undefined) + }) + ) + .mockResolvedValue(undefined) + + dispatchDrag(screen.getByRole('textbox'), 'drop', { + files: [ + new File(['x'], 'a.png', { type: 'image/png' }), + new File(['x'], 'b.png', { type: 'image/png' }), + new File(['x'], 'c.png', { type: 'image/png' }) + ] + }) + + await vi.waitFor(() => expect(uploaded).toHaveLength(3)) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce()) + releaseFirstRefresh() + await vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2)) + }) + + it('chains input asset refreshes across overlapping batches', async () => { const uploaded = stubUploadFetch() renderWithSelectedTarget() await nextTick() + let releaseFirstRefresh: () => void = () => {} + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFirstRefresh = () => resolve(undefined) + }) + ) + .mockResolvedValue(undefined) + + const textbox = screen.getByRole('textbox') + dispatchDrag(textbox, 'drop', { + files: [new File(['x'], 'a.png', { type: 'image/png' })] + }) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce()) + + dispatchDrag(textbox, 'drop', { + files: [new File(['x'], 'b.png', { type: 'image/png' })] + }) + await vi.waitFor(() => expect(uploaded).toEqual(['a.png', 'b.png'])) + await expect( + vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2), { + timeout: 250, + interval: 10 + }) + ).rejects.toThrow() + + releaseFirstRefresh() + await vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2)) + }) - const song = fileOfSize('big.mp3', MAX_ATTACHMENT_BYTES + 1, 'audio/mpeg') + it('keeps refreshing later batches after a refresh fails', async () => { + const uploaded = stubUploadFetch() + renderWithSelectedTarget() + await nextTick() + let rejectFirstRefresh!: (error: Error) => void + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectFirstRefresh = reject + }) + ) + .mockResolvedValue(undefined) + + const textbox = screen.getByRole('textbox') + dispatchDrag(textbox, 'drop', { + files: [new File(['x'], 'a.png', { type: 'image/png' })] + }) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce()) + + dispatchDrag(textbox, 'drop', { + files: [new File(['x'], 'b.png', { type: 'image/png' })] + }) + await vi.waitFor(() => expect(uploaded).toEqual(['a.png', 'b.png'])) + expect(refresh).toHaveBeenCalledOnce() + + rejectFirstRefresh(new Error('asset fetch failed')) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2)) + }) + + it('gives Undo a grace period before cancelling a removed upload', async () => { + const signals: AbortSignal[] = [] + vi.stubGlobal( + 'fetch', + vi.fn((input: RequestInfo | URL, init?: RequestInit) => { + if (!String(input).includes('/upload/')) + return Promise.resolve(json(200, agentThreadList())) + if (init?.signal) signals.push(init.signal) + return new Promise((_resolve, reject) => + init?.signal?.addEventListener('abort', () => + reject(init.signal?.reason) + ) + ) + }) + ) + renderWithSelectedTarget() + await nextTick() + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockResolvedValue(undefined) + + dispatchDrag(screen.getByRole('textbox'), 'drop', { + files: [new File(['x'], 'cat.png', { type: 'image/png' })] + }) + await vi.waitFor(() => expect(signals).toHaveLength(1)) + const composer = useAgentComposerStore() + const removeButton = await screen.findByRole('button', { + name: i18n.global.t('agent.remove') + }) + vi.useFakeTimers() + try { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) + await user.click(removeButton) + + expect(signals[0].aborted).toBe(false) + expect(composer.attachments).toEqual([]) + await vi.advanceTimersByTimeAsync(5_000) + expect(signals[0].aborted).toBe(true) + expect(refresh).not.toHaveBeenCalled() + expect(useToastStore().messagesToAdd).not.toContainEqual( + expect.objectContaining({ detail: 'cat.png could not be uploaded' }) + ) + } finally { + vi.useRealTimers() + } + }) + + it('uses the server limit for audio rejection copy', async () => { + getServerFeature.mockReturnValue(24 * 1024 * 1024) + const uploaded = stubUploadFetch() + renderWithSelectedTarget() + await nextTick() + + const song = fileOfSize('big.mp3', 25 * 1024 * 1024, 'audio/mpeg') dispatchDrag(screen.getByRole('textbox'), 'drop', { files: [song] }) await nextTick() @@ -1542,7 +1773,7 @@ describe('AgentPanelRoot attach flow', () => { expect(useToastStore().messagesToAdd).toContainEqual( expect.objectContaining({ severity: 'warn', - detail: 'big.mp3 is larger than 20MB' + detail: 'big.mp3 is larger than 24 MB' }) ) }) @@ -1644,7 +1875,7 @@ describe('AgentPanelRoot attach flow', () => { getData: (type: string) => type === 'application/x-comfy-asset-info' ? JSON.stringify({ filename, type: 'input' }) - : `http://localhost/api/view?filename=${filename}` + : `/api/view?filename=${filename}` } dispatchDrag(target, 'dragenter', dragData) @@ -1744,6 +1975,40 @@ describe('AgentPanelRoot attach flow', () => { } ) + it('stages a renamed non-media asset reference without downloading it', async () => { + const fetchSpy = vi.fn(async (_input?: RequestInfo | URL) => + json(200, agentThreadList()) + ) + vi.stubGlobal('fetch', fetchSpy) + renderWithSelectedTarget() + await nextTick() + const dragData = { + types: ['application/x-comfy-asset-info'], + getData: () => + JSON.stringify({ + filename: 'model.obj', + display_name: 'Renamed model', + attachment_ref: 'stored-model.obj', + media_kind: '3D' + }) + } + + expect(dispatchDrag(screen.getByRole('textbox'), 'drop', dragData)).toBe( + true + ) + + expect( + within(await screen.findByTestId('composer-asset-section')).getByText( + 'model.obj' + ) + ).toBeInTheDocument() + expect( + fetchSpy.mock.calls.some(([url]) => + /\/api\/(view|upload\/image)/.test(String(url)) + ) + ).toBe(false) + }) + it('shows an uploading chip while a Media-card URI is still loading', async () => { let resolveAsset: (response: Response) => void = () => {} vi.stubGlobal( @@ -1798,6 +2063,49 @@ describe('AgentPanelRoot attach flow', () => { ) }) + it('does not warn after closing the panel during a deferred asset fetch', async () => { + vi.stubGlobal( + 'fetch', + vi.fn((input) => { + const url = String(input) + if (url.includes('/api/view')) return new Promise(() => {}) + if (url.includes('/assets')) + return Promise.resolve( + json(200, { assets: [], total: 0, has_more: false }) + ) + if (url.includes('/workflows')) + return Promise.resolve( + json(200, { data: [], total: 0, has_more: false }) + ) + return Promise.resolve(json(200, agentThreadList())) + }) + ) + const { unmount } = renderWithSelectedTarget() + await nextTick() + const toast = useToastStore() + vi.useFakeTimers() + try { + dispatchDrag(screen.getByRole('textbox'), 'drop', { + types: ['application/x-comfy-asset-info', 'text/uri-list'], + getData: (type: string) => + type === 'application/x-comfy-asset-info' + ? JSON.stringify({ filename: 'gen.png', type: 'input' }) + : 'http://localhost/api/view?filename=gen.png' + }) + await nextTick() + expect( + screen.getByLabelText(i18n.global.t('agent.uploading')) + ).toBeInTheDocument() + + unmount() + await vi.advanceTimersByTimeAsync(60_000) + + expect(toast.messagesToAdd).toEqual([]) + } finally { + vi.useRealTimers() + } + }) + it('attaches dropped assets and leaves other files to the graph loader', async () => { // The graph loader only opens a dropped workflow while the drop is // unclaimed, so the panel must not claim files it cannot attach. @@ -1992,21 +2300,14 @@ describe('AgentPanelRoot attach flow', () => { revoke.mockRestore() }) - it('keeps a dismissed preview available for Undo until the editor unmounts', async () => { + it('releases a dismissed in-flight preview when its upload is cancelled', async () => { + vi.useFakeTimers() const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) vi.stubGlobal( 'fetch', vi.fn(async (url: string) => { - if (url.endsWith('/api/upload/image')) { - return new Response( - JSON.stringify({ - name: 'uploaded_cat.png', - subfolder: '', - type: 'input' - }), - { status: 200, headers: { 'Content-Type': 'application/json' } } - ) - } + if (url.endsWith('/api/upload/image')) + return new Promise(() => {}) return new Response('{"threads":[]}', { status: 200, headers: { 'Content-Type': 'application/json' } @@ -2027,14 +2328,18 @@ describe('AgentPanelRoot attach flow', () => { ) ).toBeInTheDocument() - await userEvent.click( + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) + await user.click( screen.getByRole('button', { name: i18n.global.t('agent.remove') }) ) expect(screen.queryByText('cat.png')).not.toBeInTheDocument() expect(revoke).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(5_000) + expect(revoke).toHaveBeenCalledTimes(1) view.unmount() expect(revoke).toHaveBeenCalledTimes(1) revoke.mockRestore() + vi.useRealTimers() }) }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 4f0fb206d1f..f5460efdfa8 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1,6 +1,7 @@