diff --git a/browser_tests/fixtures/components/AgentPanel.ts b/browser_tests/fixtures/components/AgentPanel.ts index e980d420232..0e19deaff05 100644 --- a/browser_tests/fixtures/components/AgentPanel.ts +++ b/browser_tests/fixtures/components/AgentPanel.ts @@ -16,6 +16,8 @@ export class AgentPanel { public readonly fileInput: Locator public readonly composerAssetSection: Locator public readonly attachmentChips: Locator + public readonly composer: Locator + public readonly sendButton: Locator constructor(private readonly page: Page) { this.root = page.locator('#agent-panel-root') @@ -41,6 +43,10 @@ export class AgentPanel { this.fileInput = this.root.getByTestId('agent-file-input') this.composerAssetSection = this.root.getByTestId('composer-asset-section') this.attachmentChips = this.root.getByTestId('agent-attachment-chip') + this.composer = this.root.getByRole('textbox', { name: /^Describe ideas/ }) + this.sendButton = this.root.getByRole('button', { + name: enMessages.agent.send + }) } /** @@ -77,6 +83,11 @@ export class AgentPanel { await expect(this.workflowPicker).toHaveText(name) } + async sendMessage(message: string): Promise { + await this.composer.fill(message) + await this.sendButton.click() + } + async turnOffOptionalReportSources(): Promise { await this.serverLogsSwitch.click() await this.settingsSwitch.click() 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 0897a173d6b..ee391aac436 100644 --- a/browser_tests/tests/agent/agentPanel.spec.ts +++ b/browser_tests/tests/agent/agentPanel.spec.ts @@ -178,6 +178,42 @@ test.describe('In-App Agent panel', { tag: '@cloud' }, () => { await expect(panel.getByText('Resize image node')).toBeVisible() }) + test('shows an admission paywall without losing the rejected prompt', async ({ + agentPanel, + comfyPage + }) => { + const page = comfyPage.page + await page.route('**/api/agent/threads/*/messages', (route) => + route.fulfill({ + status: 402, + contentType: 'application/json', + body: JSON.stringify({ + error: { + message: 'Add credits to continue.', + type: 'PAYMENT_REQUIRED', + reason: 'no_funds' + } + }) + }) + ) + + await agentPanel.open() + await agentPanel.selectWorkflow() + const panel = agentPanel.root + + const prompt = 'Build a product photo workflow' + await panel.getByRole('textbox', { name: /^Describe ideas/ }).fill(prompt) + await panel.getByRole('button', { name: 'Send' }).click() + + await expect(panel.getByTestId('user-message-bubble')).toHaveText(prompt) + await expect( + panel.getByRole('textbox', { name: /^Describe ideas/ }) + ).toHaveText(prompt) + const paywall = panel.getByRole('alert') + await expect(paywall).toContainText(enMessages.agent.paywall.title) + await expect(paywall).toContainText('Add credits to continue.') + }) + test.describe('composer sizing', () => { test.use({ viewport: { width: 1920, height: 1080 }, @@ -305,6 +341,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/browser_tests/tests/agent/agentPanelMocks.ts b/browser_tests/tests/agent/agentPanelMocks.ts index 6c762df1f89..c6611788907 100644 --- a/browser_tests/tests/agent/agentPanelMocks.ts +++ b/browser_tests/tests/agent/agentPanelMocks.ts @@ -18,6 +18,7 @@ import type { AgentTurnAccepted, AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' +import { zAgentAdmissionError } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' @@ -37,6 +38,16 @@ const TURN_ACCEPTED: AgentTurnAccepted = { const CANCEL_ACCEPTED: AgentCancelAccepted = { status: 'cancelling' } +export const FUNDS_UNAVAILABLE_MESSAGE = + 'Billing status is temporarily unavailable; please retry.' +const FUNDS_UNAVAILABLE = zAgentAdmissionError.parse({ + error: { + message: FUNDS_UNAVAILABLE_MESSAGE, + reason: 'funds_unavailable', + type: 'SERVICE_UNAVAILABLE' + } +}) + export const THINKING_TEXT = "I'll set the positive prompt to your red fox scene." @@ -152,6 +163,7 @@ async function mockAgentBoot( agentFlagEnabled, agentPanelInitiallyOpen, agentOnboardingCompleted, + agentRetryAfter, crdtDebugEnabled, initialFeatureFlags, initialSettings, @@ -347,6 +359,15 @@ async function mockAgentBoot( const request = route.request() if (request.method() === 'POST') { postedMessages.push(request.postData() ?? '') + if (agentRetryAfter !== undefined) + return route.fulfill({ + status: 503, + headers: { + 'content-type': 'application/json', + 'retry-after': agentRetryAfter + }, + body: JSON.stringify(FUNDS_UNAVAILABLE) + }) const accepted: AgentTurnAccepted = { ...TURN_ACCEPTED, message_id: @@ -388,6 +409,7 @@ type AgentFixtures = { agentPanel: AgentPanel agentPanelInitiallyOpen: boolean agentOnboardingCompleted: boolean + agentRetryAfter: string | undefined crdtDebugEnabled: boolean /** `'server'` loads real node definitions instead of the empty catalog. */ objectInfo: 'server' | undefined @@ -411,6 +433,7 @@ export const agentTest = comfyPageFixture.extend({ }, agentPanelInitiallyOpen: [false, { option: true }], agentOnboardingCompleted: [true, { option: true }], + agentRetryAfter: [undefined, { option: true }], crdtDebugEnabled: [false, { option: true }], objectInfo: [undefined, { option: true }], page: async ( @@ -422,6 +445,7 @@ export const agentTest = comfyPageFixture.extend({ agentFlagEnabled, agentPanelInitiallyOpen, agentOnboardingCompleted, + agentRetryAfter, crdtDebugEnabled, initialFeatureFlags, initialSettings, @@ -439,6 +463,7 @@ export const agentTest = comfyPageFixture.extend({ agentFlagEnabled, agentPanelInitiallyOpen, agentOnboardingCompleted, + agentRetryAfter, crdtDebugEnabled, initialFeatureFlags, initialSettings, diff --git a/browser_tests/tests/agent/agentRetryAfterNotice.spec.ts b/browser_tests/tests/agent/agentRetryAfterNotice.spec.ts new file mode 100644 index 00000000000..8fc73761a14 --- /dev/null +++ b/browser_tests/tests/agent/agentRetryAfterNotice.spec.ts @@ -0,0 +1,49 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { + agentTest, + FUNDS_UNAVAILABLE_MESSAGE +} from '@e2e/tests/agent/agentPanelMocks' + +agentTest.describe( + 'Agent Retry-After notice', + { tag: ['@cloud', '@ui'] }, + () => { + agentTest.describe('with delay-seconds', () => { + agentTest.use({ agentRetryAfter: '30' }) + + agentTest( + 'shows the retry delay the header names', + async ({ agentPanel }) => { + await agentTest.step( + 'open the agent and select the workflow', + async () => { + await agentPanel.open() + await agentPanel.selectWorkflow() + } + ) + + await agentTest.step('submit a prompt', async () => { + await agentPanel.sendMessage('Make a red fox in the snow') + }) + + await agentTest.step( + 'show the admission error and retry delay', + async () => { + await expect( + agentPanel.root.getByText(FUNDS_UNAVAILABLE_MESSAGE) + ).toBeVisible() + await expect( + agentPanel.root.getByText( + enMessages.agent.retryAfterSeconds.replace('{seconds}', '30') + ) + ).toBeVisible() + } + ) + } + ) + }) + } +) diff --git a/browser_tests/tests/agent/agentSelectionWorkflowOwnership.spec.ts b/browser_tests/tests/agent/agentSelectionWorkflowOwnership.spec.ts new file mode 100644 index 00000000000..28f5052a3f8 --- /dev/null +++ b/browser_tests/tests/agent/agentSelectionWorkflowOwnership.spec.ts @@ -0,0 +1,109 @@ +import { expect } from '@playwright/test' +import type { AgentPostMessageRequest } from '@comfyorg/ingest-types' +import { zAgentPostMessageRequest } from '@comfyorg/ingest-types/zod' + +import type { AgentTurnAccepted } from '@/workbench/extensions/agent/schemas/agentApiSchema' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } +import { + inlineReferencesTest as test, + referenceNode, + referenceWorkflow +} from '@e2e/fixtures/agentInlineReferencesFixture' + +test.use({ + connectWebSocketToServer: false, + nodeDefinitions: { ColorBalance: referenceNode } +}) + +// The first workflow saved through the target picker gets this id from +// `agentWorkflowSelectionFixture`; here that is "Portrait study", the tab the +// staged node comes from. +const PORTRAIT_CLOUD_ID = 'a81718a4-02ae-41e6-ae85-000000000001' +const TURN_ACCEPTED: AgentTurnAccepted = { + message_id: '0f7f0e9a-3c9a-4d0e-9a1b-2c6f5f4e8d11', + thread_id: 'b1d6a0b7-8a1d-4a27-8a2f-6c9d1a4b7e03', + workflow_id: PORTRAIT_CLOUD_ID +} + +test( + 'attributes a staged node to the workflow it came from after navigating away', + { tag: ['@cloud', '@ui'] }, + async ({ page, workflowSelection }, testInfo) => { + const turns: AgentPostMessageRequest[] = [] + // Registered after the fixture's broader `**/api/agent/threads**` route so + // this one wins for the send and can answer with a real acceptance. + await page.route('**/api/agent/threads/*/messages', (route) => { + if (route.request().method() !== 'POST') return route.fallback() + turns.push(zAgentPostMessageRequest.parse(route.request().postDataJSON())) + return route.fulfill({ + status: 202, + contentType: 'application/json', + body: JSON.stringify(TURN_ACCEPTED) + }) + }) + + await page.locator('#comfy-file-input').setInputFiles({ + name: 'Portrait study.json', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify(referenceWorkflow)) + }) + await page + .getByRole('button', { name: enMessages.agent.entryButton, exact: true }) + .click() + const panel = page.locator('#agent-panel-root') + const targetPicker = panel.getByRole('button', { + name: enMessages.agent.switchWorkflow + }) + await targetPicker.click() + await page.getByRole('menuitemradio', { name: /Portrait study/ }).click() + await expect.poll(() => workflowSelection.savedPaths.length).toBe(1) + workflowSelection.finishSave(true) + await expect(targetPicker).toHaveText('Portrait study') + + const editor = panel.getByRole('textbox') + await editor.fill('Warm up @') + await panel + .getByRole('menuitem', { name: enMessages.agent.nodes, exact: true }) + .click() + await panel.getByRole('menuitem', { name: /Color balance/ }).click() + await expect(editor).toHaveText('Warm up Color balance #12 ') + + // Navigate away from the target: the node is still Portrait study's, but + // the workflow on screen at send time is a different tab. + await page + .getByRole('button', { + name: enMessages.sideToolbar.newBlankWorkflow, + exact: true + }) + .click() + await expect( + page.locator('.workflow-tabs .p-togglebutton-checked') + ).toHaveText('Unsaved Workflow (2)') + await expect(targetPicker).toHaveText('Portrait study') + await expect(editor).toHaveText('Warm up Color balance #12 ') + await testInfo.attach('staged-node-from-other-tab', { + body: await panel.screenshot({ + animations: 'disabled', + path: testInfo.outputPath('staged-node-from-other-tab.png') + }), + contentType: 'image/png' + }) + + await editor.press('Enter') + await expect(panel.getByTestId('user-message-bubble')).toHaveText( + 'Warm up @[Node: Color balance #12]' + ) + + expect(turns).toHaveLength(1) + // The regression: `node_ids` alone leaves the backend to guess an owner, + // and guessing "the workflow on screen" is wrong here. Replacing the + // captured target with the active workflow in `AgentPanelRoot.vue` drops + // `workflow_id` from this payload, so this assertion discriminates. + expect(turns[0].selection).toEqual({ + node_ids: ['12'], + workflow_id: PORTRAIT_CLOUD_ID + }) + expect(turns[0].workflow_id).toBe(PORTRAIT_CLOUD_ID) + } +) diff --git a/src/platform/workspace/composables/useBillingCapabilities.test.ts b/src/platform/workspace/composables/useBillingCapabilities.test.ts index 70a90dad7a1..142a38c1e70 100644 --- a/src/platform/workspace/composables/useBillingCapabilities.test.ts +++ b/src/platform/workspace/composables/useBillingCapabilities.test.ts @@ -206,11 +206,13 @@ describe('useBillingCapabilities', () => { expect(billingCapabilities.snapshotAuthoritative.value).toBe(false) const initialization = billingCapabilities.initialize() + expect(billingCapabilities.hasResolvedCapabilities.value).toBe(false) expect(billingCapabilities.canTopUp.value).toBe(false) expect(billingCapabilities.canSubscribeSelfServe.value).toBe(false) resolveRequest(capabilitiesResponse(true)) await initialization + expect(billingCapabilities.hasResolvedCapabilities.value).toBe(true) expect(billingCapabilities.canTopUp.value).toBe(true) expect(billingCapabilities.canSubscribeSelfServe.value).toBe(true) expect(billingCapabilities.canCancel.value).toBe(true) @@ -277,6 +279,7 @@ describe('useBillingCapabilities', () => { await billingCapabilities.initialize() + expect(billingCapabilities.hasResolvedCapabilities.value).toBe(false) expect(billingCapabilities.canTopUp.value).toBe(true) expect(billingCapabilities.canSubscribeSelfServe.value).toBe(false) expect(billingCapabilities.canCancel.value).toBe(false) @@ -310,6 +313,7 @@ describe('useBillingCapabilities', () => { await billingCapabilities.initialize() + expect(billingCapabilities.hasResolvedCapabilities.value).toBe(false) expect(billingCapabilities.canTopUp.value).toBe(false) expect(billingCapabilities.canSubscribeSelfServe.value).toBe(false) expect(billingCapabilities.isReady.value).toBe(true) diff --git a/src/platform/workspace/composables/useBillingCapabilities.ts b/src/platform/workspace/composables/useBillingCapabilities.ts index a85f5b86b2b..4109df79aff 100644 --- a/src/platform/workspace/composables/useBillingCapabilities.ts +++ b/src/platform/workspace/composables/useBillingCapabilities.ts @@ -85,6 +85,7 @@ function useBillingCapabilitiesInternal() { return state.response.capabilities }) + const hasResolvedCapabilities = computed(() => capabilities.value !== null) const readUnavailableForCurrentScope = computed(() => { const state = readState.value return ( @@ -426,6 +427,7 @@ function useBillingCapabilitiesInternal() { canInviteMembers, canDowngradeToPersonal, isReady, + hasResolvedCapabilities, snapshotAuthoritative, initialize, refresh diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 664a9fe0fcd..f5b48ce8609 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -257,12 +257,13 @@ vi.mock( ) const paywallWorkspace = vi.hoisted(() => ({ - role: 'owner' as 'owner' | 'member' + role: 'owner' as 'owner' | 'member' | undefined })) const paywallCapabilities = vi.hoisted(() => ({ canTopUp: true, canSubscribeSelfServe: true, - isReady: true + isReady: true, + hasResolvedCapabilities: true })) const paywallBilling = vi.hoisted(() => ({ tier: 'STANDARD' as SubscriptionTier | null @@ -278,7 +279,7 @@ vi.mock(import('@/platform/workspace/composables/useBillingCapabilities'), { }) import type { AgentMessages, TurnId } from './schemas/agentApiSchema' -import { zAgentWsEvent } from './schemas/agentApiSchema' +import { toTurnId, zAgentWsEvent } from './schemas/agentApiSchema' import { MAX_ATTACHMENT_BYTES } from './composables/agent/useAttachment' import type { AgentChatEvent } from './services/agent/agentEventTransport' import { useAgentChatHistoryStore } from './stores/agent/agentChatHistoryStore' @@ -345,7 +346,10 @@ beforeEach(() => { canSubscribeSelfServe: computed( () => paywallCapabilities.canSubscribeSelfServe ), - isReady: computed(() => paywallCapabilities.isReady) + isReady: computed(() => paywallCapabilities.isReady), + hasResolvedCapabilities: computed( + () => paywallCapabilities.hasResolvedCapabilities + ) }) ) workflowStore = useWorkflowStore() @@ -381,9 +385,19 @@ beforeEach(() => { focusNodeInstance.mockReset() socketSend.mockReset() paywallWorkspace.role = 'owner' + vi.spyOn( + useTeamWorkspaceStore(), + 'activeWorkspace', + 'get' + ).mockImplementation(() => + paywallWorkspace.role === undefined + ? null + : fromPartial({ role: paywallWorkspace.role }) + ) paywallCapabilities.canTopUp = true paywallCapabilities.canSubscribeSelfServe = true paywallCapabilities.isReady = true + paywallCapabilities.hasResolvedCapabilities = true paywallBilling.tier = 'STANDARD' paywallHasFunds.value = false }) @@ -713,7 +727,7 @@ describe('AgentPanelRoot paywall actions', () => { it('routes the subscribed owner actions through account preconditions', async () => { render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -723,14 +737,37 @@ describe('AgentPanelRoot paywall actions', () => { await userEvent.click( await screen.findByRole('button', { name: 'Upgrade plan' }) ) - await userEvent.click(screen.getByRole('button', { name: 'Add credits' })) + expect(openAccountPrecondition).toHaveBeenCalledExactlyOnceWith( + 'subscription' + ) + await userEvent.click(screen.getByRole('button', { name: 'Add credits' })) expect(openAccountPrecondition.mock.calls).toEqual([ ['subscription'], ['credits'] ]) }) + it('routes Subscribe through the subscription precondition', async () => { + paywallCapabilities.canTopUp = false + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + useAgentConversationStore().messages.push({ + id: toTurnId('msg-paywall'), + role: 'assistant', + parts: [{ type: 'paywall' }], + streaming: false, + thinking: false + }) + + await userEvent.click( + await screen.findByRole('button', { name: 'Subscribe' }) + ) + + expect(openAccountPrecondition).toHaveBeenCalledExactlyOnceWith( + 'subscription' + ) + }) + it('dismisses the paywall after billing confirms funds are available', async () => { paywallCapabilities.canTopUp = false render(AgentPanelRoot, { global: { plugins: [i18n] } }) @@ -752,9 +789,11 @@ describe('AgentPanelRoot paywall actions', () => { it('hides purchase actions from a Team member without billing permissions', async () => { paywallWorkspace.role = 'member' + paywallCapabilities.canTopUp = false + paywallCapabilities.canSubscribeSelfServe = false render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -778,7 +817,7 @@ describe('AgentPanelRoot paywall actions', () => { paywallBilling.tier = tier render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -798,7 +837,7 @@ describe('AgentPanelRoot paywall actions', () => { paywallCapabilities.canSubscribeSelfServe = false render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -817,7 +856,7 @@ describe('AgentPanelRoot paywall actions', () => { paywallCapabilities.canTopUp = false render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -837,7 +876,7 @@ describe('AgentPanelRoot paywall actions', () => { paywallCapabilities.canSubscribeSelfServe = false render(AgentPanelRoot, { global: { plugins: [i18n] } }) useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, + id: toTurnId('msg-paywall'), role: 'assistant', parts: [{ type: 'paywall' }], streaming: false, @@ -857,29 +896,32 @@ describe('AgentPanelRoot paywall actions', () => { ).not.toBeInTheDocument() }) - it('does not interpret the pending false pair as sales-managed', async () => { - paywallCapabilities.canTopUp = false - paywallCapabilities.canSubscribeSelfServe = false - paywallCapabilities.isReady = false - render(AgentPanelRoot, { global: { plugins: [i18n] } }) - useAgentConversationStore().messages.push({ - id: 'msg-paywall' as TurnId, - role: 'assistant', - parts: [{ type: 'paywall' }], - streaming: false, - thinking: false - }) + it.for(['pending', 'denied', 'unresolved-role'] as const)( + 'withholds purchase actions for %s without inventing a sales-managed plan', + async (state) => { + paywallCapabilities.canTopUp = false + paywallCapabilities.canSubscribeSelfServe = false + paywallCapabilities.isReady = state !== 'pending' + paywallCapabilities.hasResolvedCapabilities = state === 'unresolved-role' + if (state === 'unresolved-role') paywallWorkspace.role = undefined + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + useAgentConversationStore().messages.push({ + id: toTurnId('msg-paywall'), + role: 'assistant', + parts: [{ type: 'paywall' }], + streaming: false, + thinking: false + }) - expect( - await screen.findByRole('button', { name: 'Add credits' }) - ).toBeInTheDocument() - expect( - screen.getByRole('button', { name: 'Upgrade plan' }) - ).toBeInTheDocument() - expect( - screen.queryByText(/billed through your Comfy account team/i) - ).not.toBeInTheDocument() - }) + expect(await screen.findByText('Out of credits')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: /add credits|upgrade|subscribe/i }) + ).not.toBeInTheDocument() + expect( + screen.queryByText(/billed through your Comfy account team/i) + ).not.toBeInTheDocument() + } + ) }) describe('AgentPanelRoot session notices', () => { @@ -1198,6 +1240,40 @@ describe('AgentPanelRoot attach flow', () => { expect(screen.getByRole('button', { name: 'cat.png' })).toBeInTheDocument() }) + it('uses the submitted filename when the upload response omits a name', async () => { + const messageBodies: unknown[] = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith('/api/upload/image')) { + return json(200, { subfolder: '', type: 'input' }) + } + messageBodies.push(JSON.parse(String(init?.body))) + return json(202, { thread_id: 'th-1', message_id: 'm-1' }) + }) + ) + + 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 userEvent.click(screen.getByRole('textbox')) + await userEvent.paste('describe it') + await userEvent.click(screen.getByRole('button', { name: 'Send' })) + + expect(messageBodies).toHaveLength(1) + expect(messageBodies[0]).toMatchObject({ attachments: ['cat.png'] }) + }) + it('uploads a picked video above 20MB when the server permits it', async () => { getServerFeature.mockReturnValue(100 * 1024 * 1024) const uploaded = stubUploadFetch() @@ -1295,13 +1371,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() @@ -1309,15 +1385,13 @@ 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('uploads a dropped video above 20MB when the server permits it', async () => { @@ -1409,13 +1483,142 @@ 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('refreshes the input asset library once for a dropped batch', async () => { + // Overlapping refreshes coalesce into the in-flight query without a + // trailing run, so an asset committing mid-refresh would be dropped. + const uploaded = stubUploadFetch() + renderWithSelectedTarget() + await nextTick() + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .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).toHaveBeenCalled()) + expect(refresh).toHaveBeenCalledOnce() + }) + + 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)) + }) + + it('keeps refreshing later batches after a refresh fails', async () => { + const uploaded = stubUploadFetch() + renderWithSelectedTarget() + await nextTick() + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockRejectedValueOnce(new Error('asset fetch failed')) + .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 vi.waitFor(() => expect(refresh).toHaveBeenCalledTimes(2)) + }) + + it('lets a removed upload finish without reattaching until Undo', async () => { + const signals: AbortSignal[] = [] + let finishUpload: (response: Response) => void = () => {} + const upload = new Promise((resolve) => { + finishUpload = resolve + }) + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (!String(input).includes('/upload/')) + return json(200, agentThreadList()) + if (init?.signal) signals.push(init.signal) + return upload + }) + ) + renderWithSelectedTarget() + await nextTick() + const refresh = vi + .spyOn(useAssetsStore().inputAssets, 'loadNew') + .mockResolvedValue(undefined) - const song = fileOfSize('big.mp3', MAX_ATTACHMENT_BYTES + 1, 'audio/mpeg') + 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 prompt = composer.prompt + + await userEvent.click( + await screen.findByRole('button', { name: i18n.global.t('agent.remove') }) + ) + + expect(signals[0].aborted).toBe(false) + finishUpload( + json(200, { name: 'uploaded-cat.png', subfolder: '', type: 'input' }) + ) + await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce()) + expect(composer.attachments).toEqual([]) + composer.applyEditorPrompt(prompt) + expect(composer.attachments).toEqual([ + expect.objectContaining({ + name: 'cat.png', + ref: 'uploaded-cat.png', + uploading: false + }) + ]) + }) + + 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() @@ -1423,7 +1626,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' }) ) }) @@ -1679,6 +1882,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. @@ -1873,7 +2119,7 @@ describe('AgentPanelRoot attach flow', () => { revoke.mockRestore() }) - it('keeps a dismissed preview available for Undo until the editor unmounts', async () => { + it('keeps a dismissed durable preview available for Undo until the editor unmounts', async () => { const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) vi.stubGlobal( 'fetch', @@ -1902,17 +2148,28 @@ describe('AgentPanelRoot attach flow', () => { screen.getByTestId('agent-file-input'), file ) - expect( - within(await screen.findByTestId('composer-asset-section')).getByText( - 'cat.png' - ) - ).toBeInTheDocument() + const assetSection = await screen.findByTestId('composer-asset-section') + expect(within(assetSection).getByText('cat.png')).toBeInTheDocument() + await waitFor(() => + expect( + within(assetSection).getByRole('img', { name: 'cat.png' }) + ).toHaveAttribute('src', '/api/view?filename=uploaded_cat.png&type=input') + ) + expect(revoke).toHaveBeenCalledExactlyOnceWith('blob:mock-url') await userEvent.click( screen.getByRole('button', { name: i18n.global.t('agent.remove') }) ) expect(screen.queryByText('cat.png')).not.toBeInTheDocument() - expect(revoke).not.toHaveBeenCalled() + screen.getByRole('textbox').focus() + await userEvent.keyboard('{Control>}z{/Control}') + expect( + within(await screen.findByTestId('composer-asset-section')).getByRole( + 'img', + { name: 'cat.png' } + ) + ).toHaveAttribute('src', '/api/view?filename=uploaded_cat.png&type=input') + expect(revoke).toHaveBeenCalledExactlyOnceWith('blob:mock-url') view.unmount() expect(revoke).toHaveBeenCalledTimes(1) revoke.mockRestore() @@ -4564,9 +4821,16 @@ describe('AgentPanelRoot workflow binding', () => { }) ) - await renderAndSend('first message') + await startVueNodeSelection() + await sendFromComposer('first message') - expect(bodies[0]).toMatchObject({ workflow_id: 'wf-cloud-current' }) + expect(bodies[0]).toMatchObject({ + workflow_id: 'wf-cloud-current', + selection: { + node_ids: ['9', '12'], + workflow_id: 'wf-cloud-current' + } + }) }) it('does not resolve two same-named open saved tabs to one cloud id', async () => { @@ -5202,7 +5466,11 @@ describe('AgentPanelRoot workflow binding', () => { expect(bodies[0]).toMatchObject({ content: '@[Node: KSampler #12] Keep this draft', workflow_id: 'wf-cloud-current', - selection: { node_ids: ['12'] }, + // The chip was staged while `wf-cloud-current` was viewed, and the + // user then navigated to `wf-reference` before sending. Ownership must + // follow the workflow the node came from, not the one on screen at + // send time, so this asserts the owner rather than only `node_ids`. + selection: { node_ids: ['12'], workflow_id: 'wf-cloud-current' }, workflow_references: [] }) } @@ -6524,7 +6792,7 @@ describe('AgentPanelRoot workflow binding', () => { await sendFromComposer('edit the selected workflow') expect(bodies[0]).toMatchObject({ workflow_id: 'wf-42', - selection: { node_ids: ['12'] } + selection: { node_ids: ['12'], workflow_id: 'wf-42' } }) }) @@ -6862,7 +7130,7 @@ describe('AgentPanelRoot workflow binding', () => { }) it('resolves picker nodes from the viewed subgraph, not the root graph', async () => { - makeTab() + makeTab('wf-42') const bodies = mockMessagesEndpoint('wf-42') appMock.canvas = { graph: { @@ -6885,7 +7153,9 @@ describe('AgentPanelRoot workflow binding', () => { await userEvent.click(await screen.findByText('KSampler')) await sendFromComposer('explain this') - expect(bodies[0]).toMatchObject({ selection: { node_ids: ['12'] } }) + expect(bodies[0]).toMatchObject({ + selection: { node_ids: ['12'], workflow_id: 'wf-42' } + }) }) it('never subscribes to the retired draft_patch frame', async () => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 7c656311804..6850b2e3f62 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1,6 +1,7 @@ + + diff --git a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.stories.ts b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.stories.ts index 90172131ff0..5587aa072b2 100644 --- a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.stories.ts +++ b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.stories.ts @@ -33,6 +33,22 @@ export const SubscriptionRequired: Story = { render: renderAtMinimumWidth } +export const AdmissionError: Story = { + args: { + presentation: { kind: 'member' }, + message: 'Your workspace spend limit was reached.' + }, + render: renderAtMinimumWidth +} + +export const Unavailable: Story = { + args: { + presentation: { kind: 'member' }, + message: 'The agent is temporarily unavailable. Try again shortly.' + }, + render: renderAtMinimumWidth +} + export const Member: Story = { args: { presentation: { kind: 'member' } }, render: renderAtMinimumWidth diff --git a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.test.ts b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.test.ts index 84c20fbbd40..14f6fef9317 100644 --- a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.test.ts @@ -6,11 +6,12 @@ import { i18n } from '@/i18n' import AgentPaywallCard from './AgentPaywallCard.vue' -describe('AgentPaywallCard', () => { - it('offers Upgrade plan and Add credits for a subscribed owner', async () => { +describe('AgentPaywallCard visual contract', () => { + it('makes Add credits primary for a subscribed owner', async () => { const user = userEvent.setup() const onPaywallAction = vi.fn() render(AgentPaywallCard, { + props: { presentation: { kind: 'subscribed', showUpgrade: true } }, attrs: { 'aria-label': 'Out of credits card', onPaywallAction @@ -26,15 +27,25 @@ describe('AgentPaywallCard', () => { ) ).toBeInTheDocument() - const [upgrade, addCredits] = screen.getAllByRole('button') - expect(upgrade).toHaveAccessibleName('Upgrade plan') - expect(addCredits).toHaveAccessibleName('Add credits') + const upgrade = screen.getByRole('button', { name: 'Upgrade plan' }) + const addCredits = screen.getByRole('button', { name: 'Add credits' }) await user.click(upgrade) await user.click(addCredits) expect(onPaywallAction.mock.calls).toEqual([['upgrade'], ['addCredits']]) }) + it('announces the server denial without purchase actions when capabilities are unknown', () => { + render(AgentPaywallCard, { + props: { message: 'Your workspace spend limit was reached.' }, + global: { plugins: [i18n] } + }) + expect(screen.getByRole('alert')).toHaveTextContent( + 'Your workspace spend limit was reached.' + ) + expect(screen.queryByRole('button')).not.toBeInTheDocument() + }) + it.for([ { presentation: { kind: 'member' as const }, diff --git a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.vue b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.vue index 6f2bd830824..cb346536b40 100644 --- a/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.vue +++ b/src/workbench/extensions/agent/components/agent/message/AgentPaywallCard.vue @@ -9,9 +9,11 @@ import type { AgentPaywallPresentation } from '@/workbench/extensions/agent/services/agent/agentPaywallPresentation' -const { presentation = DEFAULT_AGENT_PAYWALL_PRESENTATION } = defineProps<{ - presentation?: AgentPaywallPresentation -}>() +const { presentation = DEFAULT_AGENT_PAYWALL_PRESENTATION, message } = + defineProps<{ + presentation?: AgentPaywallPresentation + message?: string + }>() const emit = defineEmits<{ paywallAction: [action: AgentPaywallAction] }>() @@ -21,7 +23,8 @@ const bodyKeys: Record = { subscriptionRequired: 'agent.paywall.body.subscriptionRequired', member: 'agent.paywall.body.member', salesManaged: 'agent.paywall.body.salesManaged', - local: 'agent.paywall.body.local' + local: 'agent.paywall.body.local', + unavailable: 'agent.paywall.body.subscriptionRequired' } const bodyKey = computed(() => bodyKeys[presentation.kind]) const showUpgrade = computed( @@ -37,6 +40,7 @@ const showAddCredits = computed(