diff --git a/.agents/checks/error-handling.md b/.agents/checks/error-handling.md index 8babfacef16..dac52ebd8a6 100644 --- a/.agents/checks/error-handling.md +++ b/.agents/checks/error-handling.md @@ -30,9 +30,9 @@ Rules: - User-facing error messages must be actionable and friendly (per AGENTS.md) - Use the shared `useErrorHandling` composable (`src/composables/useErrorHandling.ts`) for centralized error handling: - - `wrapWithErrorHandling` / `wrapWithErrorHandlingAsync` automatically catch errors and surface them as toast notifications via `useToastStore` + - `wrapWithErrorHandling` / `wrapWithErrorHandlingAsync` automatically catch errors and surface them as toast notifications via `useToast` - `toastErrorHandler` can be used directly for custom error handling flows - Supports `ErrorRecoveryStrategy` for retry/fallback patterns (e.g., reauthentication, network reconnect) -- API errors from `api.get()`/`api.post()` should be caught and surfaced to the user via `useToastStore` (`src/platform/updates/common/toastStore.ts`) +- API errors from `api.get()`/`api.post()` should be caught and surfaced to the user via `useToast` (`src/components/ui/toast/toastStore.ts`) - Electron/desktop code paths: IPC errors should be caught and not crash the renderer process - Workflow execution errors should be displayed in the UI status bar, not silently swallowed diff --git a/.agents/checks/playwright-e2e.md b/.agents/checks/playwright-e2e.md index aa6eb612116..eed8a44d630 100644 --- a/.agents/checks/playwright-e2e.md +++ b/.agents/checks/playwright-e2e.md @@ -48,6 +48,7 @@ Reference docs (read if you need full context): - `comfyPage.canvasOps.resetView()` for view reset - `test.use({ initialSettings })` for starting settings; `comfyPage.settings.setSetting()` for runtime changes under test - Component page objects in `browser_tests/fixtures/components/` + - `comfyPage.toast` (`ToastHelper`) for toasts. Flag any `getByText` or `getByRole('alert' | 'status').filter({ hasText })` on a toast's copy: `Toaster` repeats it in a live region, so strict mode resolves two elements. Use `comfyPage.toast.withText()` or a kind locator such as `toastErrors`. Also flag raw `getByTestId('toast')` or `[data-toast-kind]` locators in specs. Tests without `comfyPage` destructure the `toast` fixture 9. **Building workflows programmatically when a JSON asset would work** — Complex `page.evaluate` chains to construct a graph should use a premade JSON workflow in `browser_tests/assets/` loaded via `comfyPage.workflow.loadWorkflow()`. diff --git a/.agents/checks/vue-patterns.md b/.agents/checks/vue-patterns.md index 052e2adaaa7..8e178c5b1c6 100644 --- a/.agents/checks/vue-patterns.md +++ b/.agents/checks/vue-patterns.md @@ -31,6 +31,7 @@ Available shadcn-vue replacements in `src/components/ui/`: - `stepper/` — Stepper - `tags-input/` — TagsInput - `search-input/` — SearchInput +- `toast/` — `useToast()` store (`success/error/info/warning/loading`), Toaster, ToastDock, ToastPanel - `Popover.vue` — Popover For Reka UI primitives not yet wrapped, create a new component in `src/components/ui/` following the pattern in existing components (see `src/components/ui/AGENTS.md`): use `useForwardProps`, `cn()`, design tokens. diff --git a/.claude/skills/reviewing-unit-tests/SKILL.md b/.claude/skills/reviewing-unit-tests/SKILL.md index f35c67e08e7..a602b3176a7 100644 --- a/.claude/skills/reviewing-unit-tests/SKILL.md +++ b/.claude/skills/reviewing-unit-tests/SKILL.md @@ -131,7 +131,7 @@ If the wrapper only renames or relays a mocked value, fail it. Inline the lookup ### Third-Party Seams - Distinguish trivial hooks from behavior-rich APIs. -- Mocking single-method third-party hooks like `primevue/usetoast` is usually acceptable. +- Mocking single-method third-party hooks like `@vueuse/core`'s `useClipboard` is usually acceptable. - That exception does not justify mocking behavior-rich third-party modules. ### `vue-i18n` diff --git a/.claude/skills/verify/SKILL.md b/.claude/skills/verify/SKILL.md index 4dc69c60a79..b86e0c3a510 100644 --- a/.claude/skills/verify/SKILL.md +++ b/.claude/skills/verify/SKILL.md @@ -70,7 +70,7 @@ await new Promise((resolve) => { }) ``` -At 0 frames, Vue transitions never finish. A removed PrimeVue toast keeps its DOM node with `p-toast-message-leave-active` at opacity 0, and a new one sticks at `p-toast-message-enter-from`, so DOM queries report toasts a real user never sees. In that case assert on component state instead. Walk `el.__vueParentComponent` up to the component whose `type.name` is `Toast` and read `proxy.messages`. A 2026-09-21 run filed a false "verify toast stays after the top-up settles" finding this way. +At 0 frames, Vue transitions never finish, so DOM queries can report elements a real user never sees, such as a dialog stuck mid-leave. For toasts, assert on the store instead: `document.querySelector('#vue-app').__vue_app__.config.globalProperties.$pinia._s.get('toast').toasts` is the list the Toaster renders. A 2026-09-21 run filed a false "verify toast stays after the top-up settles" finding from DOM queries in a hidden tab. ## Drive diff --git a/.oxlintrc.json b/.oxlintrc.json index 396300def4b..051e19d742f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -799,6 +799,12 @@ "name": "@playwright/test", "importNames": ["test"], "message": "Use `comfyPageFixture as test` from the ComfyPage fixture module instead of raw `test` from '@playwright/test'." + }, + { + "name": "@e2e/fixtures/helpers/ToastHelper", + "importNames": ["ToastHelper"], + "allowTypeImports": true, + "message": "Use `comfyPage.toast`, or the `toast` fixture in tests without `comfyPage`, instead of constructing a ToastHelper." } ], "patterns": [ diff --git a/.storybook/preview.ts b/.storybook/preview.ts index 0c38b3954dc..d0e7e651170 100644 --- a/.storybook/preview.ts +++ b/.storybook/preview.ts @@ -6,7 +6,6 @@ import type { Preview, StoryContext, StoryFn } from '@storybook/vue3-vite' import { createPinia } from 'pinia' import 'primeicons/primeicons.css' import PrimeVue from 'primevue/config' -import ToastService from 'primevue/toastservice' import Tooltip from 'primevue/tooltip' import { i18n } from '@/i18n' @@ -43,7 +42,6 @@ setup((app) => { } } }) - app.use(ToastService) }) // Theme and dialog decorator diff --git a/README.md b/README.md index 26baaeac81e..160ad9a4525 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,49 @@ https://github.com/user-attachments/assets/5696a89d-4a47-4fcc-9e8c-71e1264943f2 ### Developer APIs +
+ v1.58: Kind-based toast API + +`app.extensionManager.toast` has `success`, `error`, `info`, `warning`, and +`loading`. Each takes `(title, { description, duration, closable, action })` +and returns an id for `dismiss(id)`. `dismissAll()` removes every toast. + +```js +const toast = app.extensionManager.toast + +toast.info('Loaded!', { description: 'Extension loaded!', duration: 3000 }) + +const toastId = toast.warning('Model missing', { + action: { + label: 'Download', + onClick: () => { + startDownload() + toast.dismiss(toastId) + } + } +}) +``` + +A toast stays open until dismissed unless `duration` (ms) is set. Clicking an +`action` button does not dismiss the toast. + +`add()` and `addAlert()` still work but are deprecated. `addAlert(message)` now +shows `message` as the warning title, like `warning(message)`. `remove()` and +`removeAll()` were removed; use `dismiss(id)` or `dismissAll()`. + +`add()` maps the PrimeVue message fields onto the new API and ignores every +other field: + +| `add()` field | New API | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `severity` | kind: `warn` → `warning` (`warning` also works but is deprecated); `success`, `error` unchanged; `info`, `secondary`, `contrast` → `info`; any other value logs an error and shows nothing | +| `summary` | `title` (`detail` becomes the title when `summary` is missing) | +| `detail` | `description` | +| `life` | `duration` in ms; `0` or unset keeps the toast open | +| `closable` | `closable` | + +
+
v1.6.13: prompt/confirm/alert replacements for ComfyUI desktop @@ -472,7 +515,9 @@ app.extensionManager.toast.add({ }) ``` -Documentation of all supported options can be found here: +Only `severity`, `summary`, `detail`, `life` and `closable` are honoured; see the field mapping under the [kind-based toast API](#extension-api-toast-kinds). + +Deprecated in v1.58 by the [kind-based toast API](#extension-api-toast-kinds). ![image](https://github.com/user-attachments/assets/de02cd7e-cd81-43d1-a0b0-bccef92ff487) diff --git a/apps/website/e2e/README.md b/apps/website/e2e/README.md index 9c9bcb17f8e..fc490a777ab 100644 --- a/apps/website/e2e/README.md +++ b/apps/website/e2e/README.md @@ -4,6 +4,10 @@ Use `test` from `./fixtures/blockExternalMedia`, not `@playwright/test`. Use its `page` and `context`. Set user-agent variants with scoped `test.use` options instead of creating browser contexts. +Find an auth toast with `new AuthToasts(page).withText(...)` from +`./fixtures/authToasts`, never `page.getByText` on its copy: a screen-reader +live region repeats that copy. + ## No external requests Register test-specific `context.route` responses before navigation. They override diff --git a/apps/website/e2e/auth-live-errors.spec.ts b/apps/website/e2e/auth-live-errors.spec.ts index e92dac5adf6..e5b14d271d6 100644 --- a/apps/website/e2e/auth-live-errors.spec.ts +++ b/apps/website/e2e/auth-live-errors.spec.ts @@ -2,6 +2,7 @@ import { expect } from '@playwright/test' import type { Page, Route } from '@playwright/test' import { t } from '@/i18n/translations' +import { AuthToasts } from './fixtures/authToasts' import { test } from './fixtures/blockExternalMedia' import { WORKSHOP_EMAIL, @@ -61,7 +62,7 @@ test.describe('Live sign-in error codes', () => { await page.getByRole('button', { name: 'Sign in', exact: true }).click() await expect( - page.getByText('Invalid login credentials'), + new AuthToasts(page).withText('Invalid login credentials'), 'the same copy as a wrong password keeps sign-in from revealing whether an email has an account' ).toBeVisible() }) @@ -78,7 +79,9 @@ test.describe('Live sign-in error codes', () => { await page.getByRole('button', { name: 'Sign in', exact: true }).click() await expect( - page.getByText('This account has been disabled. Please contact support.') + new AuthToasts(page).withText( + 'This account has been disabled. Please contact support.' + ) ).toBeVisible() }) @@ -94,7 +97,7 @@ test.describe('Live sign-in error codes', () => { await page.getByRole('button', { name: 'Sign in', exact: true }).click() await expect( - page.getByText( + new AuthToasts(page).withText( 'Too many login attempts. Please wait a moment and try again.' ) ).toBeVisible() @@ -123,7 +126,7 @@ test.describe('Live sign-in error codes', () => { await page.getByRole('button', { name: 'Sign in', exact: true }).click() await expect( - page.getByText( + new AuthToasts(page).withText( 'Network error. Please check your connection and try again.' ) ).toBeVisible() @@ -148,7 +151,7 @@ test.describe('Live sign-up error codes and password checklist', () => { await page.getByRole('button', { name: 'Sign up', exact: true }).click() await expect( - page.getByText( + new AuthToasts(page).withText( t('auth.errors.auth/email-already-in-use', {}, { locale: 'en' }) ) ).toBeVisible() @@ -234,12 +237,12 @@ test.describe('Live forgot-password transport failure', () => { await page.getByRole('button', { name: 'Send reset link' }).click() await expect( - page.getByText( + new AuthToasts(page).withText( 'Too many login attempts. Please wait a moment and try again.' ) ).toBeVisible() await expect( - page.getByText('Password reset email sent'), + new AuthToasts(page).withText('Password reset email sent'), 'a rejected send is a real failure, not the neutral unregistered-email success' ).toBeHidden() await expect( diff --git a/apps/website/e2e/auth-live.spec.ts b/apps/website/e2e/auth-live.spec.ts index 6b0460e644a..d3ddf845ae3 100644 --- a/apps/website/e2e/auth-live.spec.ts +++ b/apps/website/e2e/auth-live.spec.ts @@ -1,6 +1,7 @@ import { expect } from '@playwright/test' import type { Page, Route } from '@playwright/test' +import { AuthToasts } from './fixtures/authToasts' import { test } from './fixtures/blockExternalMedia' import { WORKSHOP_EMAIL, @@ -76,7 +77,9 @@ test.describe('Live email sign-in', () => { await page.getByLabel('Password', { exact: true }).fill('wrong-password') await page.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect(page.getByText('Invalid login credentials')).toBeVisible() + await expect( + new AuthToasts(page).withText('Invalid login credentials') + ).toBeVisible() await expect(page).toHaveURL(/\/login\/(?:[?#].*)?$/) }) @@ -155,7 +158,9 @@ test.describe('Live forgot-password', () => { await page.getByLabel('Email').fill(WORKSHOP_EMAIL) await page.getByRole('button', { name: 'Send reset link' }).click() - await expect(page.getByText('Password reset email sent')).toBeVisible() + await expect( + new AuthToasts(page).withText('Password reset email sent') + ).toBeVisible() await expect(page).toHaveURL('/login/', { timeout: 10_000 }) }) @@ -187,7 +192,7 @@ test.describe('Live forgot-password', () => { await page.getByRole('button', { name: 'Send reset link' }).click() await expect( - page.getByText('Password reset email sent'), + new AuthToasts(page).withText('Password reset email sent'), 'the cloud app shows success even on this failure to avoid confirming account existence' ).toBeVisible() }) diff --git a/apps/website/e2e/fixtures/authToasts.ts b/apps/website/e2e/fixtures/authToasts.ts new file mode 100644 index 00000000000..0007c22d09b --- /dev/null +++ b/apps/website/e2e/fixtures/authToasts.ts @@ -0,0 +1,13 @@ +import type { Locator, Page } from '@playwright/test' + +export class AuthToasts { + public readonly list: Locator + + constructor(page: Page) { + this.list = page.getByRole('region', { name: /^Notifications/ }) + } + + withText(text: string): Locator { + return this.list.getByRole('alert').filter({ hasText: text }) + } +} diff --git a/apps/website/src/components/auth/AuthForgotPassword.test.ts b/apps/website/src/components/auth/AuthForgotPassword.test.ts index b71159400ef..5c63098e7aa 100644 --- a/apps/website/src/components/auth/AuthForgotPassword.test.ts +++ b/apps/website/src/components/auth/AuthForgotPassword.test.ts @@ -3,7 +3,7 @@ import { render, screen, waitFor } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick, readonly, ref } from 'vue' -import { removeAllToasts, useAuthToasts } from '@/config/auth-toast-state' +import { dismissAllAuthToasts, useAuthToasts } from '@/config/auth-toast-state' import { sendWorkshopPasswordReset } from '@/config/workshop-firebase' import { captureAuthFailed, useWorkshopAuthFlag } from '@/scripts/posthog' import AuthForgotPassword from './AuthForgotPassword.vue' @@ -12,7 +12,7 @@ vi.mock(import('@/scripts/posthog')) vi.mock(import('@/config/workshop-firebase')) const flag = ref(true) -const { messages: toasts } = useAuthToasts() +const { toasts } = useAuthToasts() const assign = vi.fn<(url: string | URL) => void>() async function typeEmail(value: string) { @@ -35,7 +35,7 @@ const flushMicrotasks = async () => { beforeEach(() => { flag.value = true vi.mocked(useWorkshopAuthFlag).mockReturnValue(readonly(flag)) - removeAllToasts() + dismissAllAuthToasts() window.history.replaceState({}, '', '/') vi.spyOn(window.location, 'assign').mockImplementation(assign) }) @@ -71,9 +71,9 @@ describe('AuthForgotPassword', () => { ) expect(toasts.value).toEqual([ expect.objectContaining({ - severity: 'success', - summary: 'Password reset email sent', - life: 5000 + kind: 'success', + title: 'Password reset email sent', + duration: 5000 }) ]) @@ -107,7 +107,7 @@ describe('AuthForgotPassword', () => { ['auth/network-request-failed', 'Network error'] ] as const)( 'keeps %s an error: no confirmation, no redirect, and the send can be retried', - async ([code, detail]) => { + async ([code, description]) => { vi.mocked(sendWorkshopPasswordReset).mockRejectedValue({ code, message: 'x' @@ -118,9 +118,9 @@ describe('AuthForgotPassword', () => { await waitFor(() => expect(toasts.value[0]).toMatchObject({ - severity: 'error', - summary: 'Error', - detail: expect.stringContaining(detail) + kind: 'error', + title: 'Error', + description: expect.stringContaining(description) }) ) expect( @@ -150,8 +150,8 @@ describe('AuthForgotPassword', () => { await waitFor(() => expect(toasts.value[0]).toMatchObject({ - severity: 'warn', - summary: 'Warning' + kind: 'warning', + title: 'Warning' }) ) }) diff --git a/apps/website/src/components/auth/AuthForgotPassword.vue b/apps/website/src/components/auth/AuthForgotPassword.vue index 1ed0ad30c86..e26632662a4 100644 --- a/apps/website/src/components/auth/AuthForgotPassword.vue +++ b/apps/website/src/components/auth/AuthForgotPassword.vue @@ -11,7 +11,7 @@ import { onBeforeUnmount, onMounted, ref, watch } from 'vue' import { authSchemasFor } from '@/config/auth-schemas' import { signInErrorMessage } from '@/config/auth-sign-in-state' -import { addToast } from '@/config/auth-toast-state' +import { authToast } from '@/config/auth-toast-state' import { requestedReturnPath } from '@/config/workshop-return' import type { Locale } from '@/i18n/translations' import { translationsFor } from '@/i18n/translations' @@ -154,21 +154,17 @@ function reportSendFailure(error: unknown) { auth_action: 'password_reset' }) const classification = classifyAuthError(error) - const severity = severityForAuthError(classification) - addToast({ - severity, - summary: t(severity === 'warn' ? 'g.warning' : 'g.error'), - detail: signInErrorMessage(classification, locale, hostname) + const kind = severityForAuthError(classification) + authToast[kind](t(`g.${kind}`), { + description: signInErrorMessage(classification, locale, hostname) }) } function reportSent() { state.value = 'sent' - addToast({ - severity: 'success', - summary: t('auth.forgot.toastSummary'), - detail: t('auth.forgot.toastDetail'), - life: TOAST_LIFE_MS + authToast.success(t('auth.forgot.toastSummary'), { + description: t('auth.forgot.toastDetail'), + duration: TOAST_LIFE_MS }) returnTimer = setTimeout(() => { window.location.assign(signInDestination()) diff --git a/apps/website/src/components/auth/AuthSignIn.import-failure.test.ts b/apps/website/src/components/auth/AuthSignIn.import-failure.test.ts index df44629dabd..55e728113e7 100644 --- a/apps/website/src/components/auth/AuthSignIn.import-failure.test.ts +++ b/apps/website/src/components/auth/AuthSignIn.import-failure.test.ts @@ -13,13 +13,13 @@ vi.mock(import('@/config/workshop-firebase'), () => { }) it('leaves the buttons usable when the Firebase chunk fails to load on a click', async () => { - const { messages } = useAuthToasts() + const { toasts } = useAuthToasts() render(AuthSignIn) const button = screen.getByRole('button', { name: /^sign in with google$/i }) await userEvent.setup().click(button) - await waitFor(() => expect(messages.value).toHaveLength(1)) - expect(messages.value[0].detail).toBe( + await waitFor(() => expect(toasts.value).toHaveLength(1)) + expect(toasts.value[0].description).toBe( t('auth.errors.generic', {}, { locale: 'en' }) ) expect( diff --git a/apps/website/src/components/auth/AuthSignIn.test.ts b/apps/website/src/components/auth/AuthSignIn.test.ts index 53280489e18..99f76707ea8 100644 --- a/apps/website/src/components/auth/AuthSignIn.test.ts +++ b/apps/website/src/components/auth/AuthSignIn.test.ts @@ -16,7 +16,7 @@ import type { TurnstileRenderOptions } from '@comfyorg/account-core/turnstileScript' -import { removeAllToasts, useAuthToasts } from '@/config/auth-toast-state' +import { dismissAllAuthToasts, useAuthToasts } from '@/config/auth-toast-state' import { testCredential, testFirebaseUser @@ -108,7 +108,7 @@ vi.mock(import('@comfyorg/account-ui/auth/regionProbe'), () => ({ isInChina })) -const { messages: toasts } = useAuthToasts() +const { toasts } = useAuthToasts() const replace = vi.fn<(url: string | URL) => void>() const assign = vi.fn<(url: string | URL) => void>() @@ -138,7 +138,7 @@ beforeEach(() => { isInChina .mockReset() .mockImplementation(() => inChina.pending ?? Promise.resolve(inChina.value)) - removeAllToasts() + dismissAllAuthToasts() window.history.replaceState({}, '', '/') replace.mockReset() assign.mockReset() @@ -336,7 +336,7 @@ describe('AuthSignIn', () => { .click(screen.getByRole('button', { name: /^sign in with github$/i })) const alert = await screen.findByRole('alert') - expect(alert.getAttribute('data-severity')).toBe('warn') + expect(toasts.value[0].kind).toBe('warning') expect(alert.textContent).toContain('Warning') expect(alert.textContent).toContain( t('auth.errors.auth/popup-closed-by-user', {}, { locale: 'en' }) @@ -964,12 +964,12 @@ describe('AuthSignIn', () => { await user.click(screen.getByRole('button', { name: /^sign in$/i })) const alert = await screen.findByRole('alert') - expect(alert.getAttribute('data-severity')).toBe('error') + expect(toasts.value[0].kind).toBe('error') expect( alert.textContent, 'user-not-found collapses to the neutral invalid-credential line so the toast never confirms whether the email has an account' ).toContain(t('auth.errors.auth/invalid-credential', {}, { locale: 'en' })) - expect(toasts.value[0].life).toBeUndefined() + expect(toasts.value[0].duration).toBe(Number.POSITIVE_INFINITY) expect(replace).not.toHaveBeenCalled() }) @@ -1651,7 +1651,7 @@ describe('AuthSignIn controller lifecycle', () => { toasts.value, 'a hung email request recovers with a message rather than silently re-enabling' ).toHaveLength(1) - expect(toasts.value[0].detail).toBe( + expect(toasts.value[0].description).toBe( t('auth.errors.generic', {}, { locale: 'en' }) ) expect( diff --git a/apps/website/src/components/auth/AuthToast.test.ts b/apps/website/src/components/auth/AuthToast.test.ts index f41ea9ec50c..eb47555f960 100644 --- a/apps/website/src/components/auth/AuthToast.test.ts +++ b/apps/website/src/components/auth/AuthToast.test.ts @@ -2,82 +2,96 @@ import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { addToast, removeAllToasts } from '@/config/auth-toast-state' +import { authToast, dismissAllAuthToasts } from '@/config/auth-toast-state' import AuthToast from './AuthToast.vue' -beforeEach(removeAllToasts) +beforeEach(dismissAllAuthToasts) + +function shownToasts() { + return screen.queryAllByRole('alert') +} describe('AuthToast', () => { - it('shows a message raised before the host mounted', () => { - addToast({ severity: 'error', summary: 'Error', detail: 'Too early' }) + it('shows a toast raised before the host mounted', async () => { + authToast.error('Error', { description: 'Too early' }) render(AuthToast) - expect(screen.getByRole('alert').textContent).toContain('Too early') + await vi.waitFor(() => + expect(shownToasts()[0]).toHaveTextContent('Too early') + ) }) - it('dismisses a message with a life only once that many milliseconds pass', async () => { + it('dismisses a toast with a duration once that many milliseconds pass', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }) + authToast.success('Signed out', { duration: 5000 }) render(AuthToast) - addToast({ - severity: 'success', - summary: 'Signed out', - detail: 'Bye', - life: 5000 - }) - await screen.findByRole('alert') await vi.advanceTimersByTimeAsync(4999) - expect(screen.getByRole('alert')).toBeTruthy() + expect(shownToasts()).toHaveLength(1) await vi.advanceTimersByTimeAsync(1) - expect(screen.queryByRole('alert')).toBeNull() + expect(shownToasts()).toHaveLength(0) }) - it('keeps a message without a life until it is closed', async () => { + it('keeps a toast without a duration until it is closed', async () => { render(AuthToast) - addToast({ severity: 'error', summary: 'Error', detail: 'Sticky' }) - await screen.findByRole('alert') + authToast.error('Error', { description: 'Sticky' }) + await vi.waitFor(() => expect(shownToasts()).toHaveLength(1)) await vi.advanceTimersByTimeAsync(60_000) - expect(screen.getByRole('alert')).toBeTruthy() + expect(shownToasts()).toHaveLength(1) await userEvent.setup().click(screen.getByRole('button', { name: 'Close' })) - expect(screen.queryByRole('alert')).toBeNull() + expect(shownToasts()).toHaveLength(0) }) - it('closing early cancels the pending auto-dismiss', async () => { + it('keeps toasts open when Escape is pressed', async () => { render(AuthToast) - addToast({ severity: 'success', summary: 'Ok', detail: 'a', life: 5000 }) - await screen.findByRole('alert') + authToast.error('Error', { description: 'Sticky' }) + await vi.waitFor(() => expect(shownToasts()).toHaveLength(1)) - await userEvent.setup().click(screen.getByRole('button', { name: 'Close' })) - addToast({ severity: 'success', summary: 'Ok', detail: 'b' }) - await screen.findByRole('alert') - await vi.advanceTimersByTimeAsync(5000) + await userEvent.setup().keyboard('{Escape}') - expect( - screen.getByRole('alert').textContent, - 'the first message timer must not remove whatever is showing later' - ).toContain('b') + expect(shownToasts()).toHaveLength(1) }) - it.for(['success', 'warn', 'error', 'info'] as const)( - 'announces the %s severity so styling and assistive tech can tell them apart', - async (severity) => { - render(AuthToast) - addToast({ severity, summary: 'S', detail: 'D' }) - const alert = await screen.findByRole('alert') + it('keeps toast text selectable', async () => { + render(AuthToast) + authToast.error('Error', { description: 'Copy me' }) + await vi.waitFor(() => expect(shownToasts()).toHaveLength(1)) - expect(alert.getAttribute('data-severity')).toBe(severity) - } - ) + expect(shownToasts()[0].style.userSelect).not.toBe('none') + }) - it('announces assertively and atomically like PrimeVue', async () => { + it('times out a later toast after the user closed the last one', async () => { + vi.useFakeTimers({ shouldAdvanceTime: false }) + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) render(AuthToast) - addToast({ severity: 'error', summary: 'S', detail: 'D' }) - const alert = await screen.findByRole('alert') + authToast.error('Error', { description: 'Sticky' }) + await vi.waitFor(() => expect(shownToasts()).toHaveLength(1)) + + await user.hover(shownToasts()[0]) + await user.click(screen.getByRole('button', { name: 'Close' })) + authToast.success('Signed out', { duration: 1000 }) + await vi.waitFor(() => expect(shownToasts()).toHaveLength(1)) + await vi.advanceTimersByTimeAsync(1000) - expect(alert.getAttribute('aria-live')).toBe('assertive') - expect(alert.getAttribute('aria-atomic')).toBe('true') + expect(shownToasts()).toHaveLength(0) + }) + + it.for([ + ['error', 'assertive'], + ['warning', 'assertive'], + ['success', 'polite'] + ] as const)('announces a %s toast %sly', async ([kind, politeness]) => { + render(AuthToast) + authToast[kind]('Title', { description: 'Description' }) + + expect( + await screen.findByText('Title. Description', { + selector: `[aria-live="${politeness}"] > p` + }) + ).toBeInTheDocument() }) }) diff --git a/apps/website/src/components/auth/AuthToast.vue b/apps/website/src/components/auth/AuthToast.vue index 6684ed82d49..5cda4e3b856 100644 --- a/apps/website/src/components/auth/AuthToast.vue +++ b/apps/website/src/components/auth/AuthToast.vue @@ -1,36 +1,111 @@ diff --git a/apps/website/src/components/auth/AuthToastMessage.vue b/apps/website/src/components/auth/AuthToastMessage.vue deleted file mode 100644 index f582f349606..00000000000 --- a/apps/website/src/components/auth/AuthToastMessage.vue +++ /dev/null @@ -1,137 +0,0 @@ - - - diff --git a/apps/website/src/components/auth/useAuthSignInController.ts b/apps/website/src/components/auth/useAuthSignInController.ts index fc25e4f689a..d8014daf0b4 100644 --- a/apps/website/src/components/auth/useAuthSignInController.ts +++ b/apps/website/src/components/auth/useAuthSignInController.ts @@ -29,7 +29,7 @@ import { isAttemptInFlight, signInErrorMessage } from '@/config/auth-sign-in-state' -import { addToast } from '@/config/auth-toast-state' +import { authToast } from '@/config/auth-toast-state' import { isSwitchingAccount, requestedReturnPath @@ -211,11 +211,9 @@ export function useAuthSignInController(options: AuthSignInControllerOptions) { }) function toastSignInFailure(classification: AuthErrorClassification) { - const severity = severityForAuthError(classification) - addToast({ - severity, - summary: t(severity === 'warn' ? 'g.warning' : 'g.error'), - detail: signInErrorMessage(classification, locale, hostname) + const kind = severityForAuthError(classification) + authToast[kind](t(`g.${kind}`), { + description: signInErrorMessage(classification, locale, hostname) }) } diff --git a/apps/website/src/config/auth-toast-state.test.ts b/apps/website/src/config/auth-toast-state.test.ts index 7c41505745b..73bc9b69c8e 100644 --- a/apps/website/src/config/auth-toast-state.test.ts +++ b/apps/website/src/config/auth-toast-state.test.ts @@ -1,39 +1,32 @@ import { beforeEach, describe, expect, it } from 'vitest' import { - addToast, - removeAllToasts, - removeToast, + authToast, + dismissAllAuthToasts, + dismissAuthToast, useAuthToasts } from './auth-toast-state' -const { messages } = useAuthToasts() +const { toasts } = useAuthToasts() -beforeEach(removeAllToasts) +beforeEach(dismissAllAuthToasts) describe('auth toast list', () => { - it('gives each message its own id and keeps duplicates', () => { - const first = addToast({ severity: 'error', summary: 'Error', detail: 'x' }) - const second = addToast({ - severity: 'error', - summary: 'Error', - detail: 'x' - }) - - expect(second.id).not.toBe(first.id) - expect( - messages.value.map((message) => message.id), - 'PrimeVue does not de-duplicate identical toasts, so neither does this list' - ).toEqual([first.id, second.id]) + it('gives each toast its own id and keeps duplicates', () => { + const first = authToast.error('Error', { description: 'x' }) + const second = authToast.error('Error', { description: 'x' }) + + expect(second).not.toBe(first) + expect(toasts.value.map((toast) => toast.id)).toEqual([first, second]) }) - it('removes exactly the message asked for and ignores unknown ids', () => { - const kept = addToast({ severity: 'success', summary: 'Ok', detail: 'y' }) - const gone = addToast({ severity: 'warn', summary: 'Warn', detail: 'z' }) + it('dismisses exactly the toast asked for and ignores unknown ids', () => { + const kept = authToast.success('Ok') + const gone = authToast.warning('Warning') - removeToast(gone.id) - removeToast(999_999) + dismissAuthToast(gone) + dismissAuthToast(999_999) - expect(messages.value).toEqual([kept]) + expect(toasts.value.map((toast) => toast.id)).toEqual([kept]) }) }) diff --git a/apps/website/src/config/auth-toast-state.ts b/apps/website/src/config/auth-toast-state.ts index d59b238e5ab..5e5ddbed6b3 100644 --- a/apps/website/src/config/auth-toast-state.ts +++ b/apps/website/src/config/auth-toast-state.ts @@ -2,42 +2,55 @@ * The auth pages' toast list, shared between the host island in AuthLayout * and whichever island raises a message. It owns the rendered list rather * than handing messages over, so one raised before the host hydrates still - * shows. Ids and the add/remove shape mirror PrimeVue's ToastService, which - * the cloud app's GlobalToast sits on. + * shows. */ import { readonly, ref } from 'vue' -export type ToastSeverity = 'success' | 'info' | 'warn' | 'error' +export type AuthToastKind = 'error' | 'success' | 'warning' -export interface ToastMessageInput { - readonly severity: ToastSeverity - readonly summary: string - readonly detail: string - /** Milliseconds until auto-dismiss; absent means sticky until closed. */ - readonly life?: number +interface AuthToastOptions { + readonly description?: string + readonly duration?: number } -export interface ToastMessage extends ToastMessageInput { +export interface AuthToast { + readonly duration: number readonly id: number + readonly kind: AuthToastKind + readonly title: string + readonly description?: string } -const messages = ref([]) +const toasts = ref([]) let nextId = 0 -export function addToast(message: ToastMessageInput): ToastMessage { - const entry: ToastMessage = { ...message, id: nextId++ } - messages.value = [...messages.value, entry] - return entry +function add( + kind: AuthToastKind, + title: string, + { description, duration = Number.POSITIVE_INFINITY }: AuthToastOptions = {} +): number { + const id = nextId++ + toasts.value = [...toasts.value, { description, duration, id, kind, title }] + return id } -export function removeToast(id: number): void { - messages.value = messages.value.filter((message) => message.id !== id) +export const authToast: Record< + AuthToastKind, + (title: string, options?: AuthToastOptions) => number +> = { + error: (title, options) => add('error', title, options), + success: (title, options) => add('success', title, options), + warning: (title, options) => add('warning', title, options) } -export function removeAllToasts(): void { - messages.value = [] +export function dismissAuthToast(id: number): void { + toasts.value = toasts.value.filter((toast) => toast.id !== id) +} + +export function dismissAllAuthToasts(): void { + toasts.value = [] } export function useAuthToasts() { - return { messages: readonly(messages) } + return { toasts: readonly(toasts) } } diff --git a/apps/website/src/locales/en/main.json b/apps/website/src/locales/en/main.json index 07d438e6f00..df22f965db8 100644 --- a/apps/website/src/locales/en/main.json +++ b/apps/website/src/locales/en/main.json @@ -726,7 +726,8 @@ "needHelp": "Need Help?" }, "toast": { - "close": "Close" + "close": "Close", + "viewportLabel": "Notifications ({hotkey})" }, "hero": { "carouselLabel": "Featured models", diff --git a/apps/website/src/locales/ja/main.json b/apps/website/src/locales/ja/main.json index 36df9236ff9..bf9c0b37a75 100644 --- a/apps/website/src/locales/ja/main.json +++ b/apps/website/src/locales/ja/main.json @@ -94,7 +94,8 @@ "troubleshooting": "一般的な原因:" }, "toast": { - "close": "閉じる" + "close": "閉じる", + "viewportLabel": "通知 ({hotkey})" }, "turnstile": { "expired": "認証の有効期限が切れました。再度チャレンジを完了してください。", diff --git a/apps/website/src/locales/zh-CN/main.json b/apps/website/src/locales/zh-CN/main.json index 43510d0ea72..ab145814c29 100644 --- a/apps/website/src/locales/zh-CN/main.json +++ b/apps/website/src/locales/zh-CN/main.json @@ -300,7 +300,8 @@ "troubleshooting": "常见原因:" }, "toast": { - "close": "关闭" + "close": "关闭", + "viewportLabel": "通知 ({hotkey})" }, "turnstile": { "expired": "验证已过期。请重新完成验证。", diff --git a/browser_tests/README.md b/browser_tests/README.md index 136d03fc840..4e21fdecf66 100644 --- a/browser_tests/README.md +++ b/browser_tests/README.md @@ -472,6 +472,13 @@ properties in methods rather than rebuilding locators. - When multiple nodes share a title, disambiguate: `vueNodes.getNodeByTitle(name).nth(n)` — strict mode fails on ambiguous locators. +- Never locate a toast by its copy with `getByText` or + `getByRole('alert' | 'status').filter({ hasText })`: `Toaster` repeats every + toast's text in live regions with those roles. Use + `comfyPage.toast.withText(text)` and its kind locators such as + `toastErrors`. Tests without `comfyPage` (`cloudAppFixture`, `agentTest`, + or a `page`-only test) destructure the `toast` fixture instead. Specs may + not construct a `ToastHelper`; lint allows only type imports. ### Node references over coordinates diff --git a/browser_tests/fixtures/ComfyPage.ts b/browser_tests/fixtures/ComfyPage.ts index c917a346089..352477a986a 100644 --- a/browser_tests/fixtures/ComfyPage.ts +++ b/browser_tests/fixtures/ComfyPage.ts @@ -228,7 +228,6 @@ export class ComfyPage { public readonly assets: AssetsHelper public readonly modelLibrary: ModelLibraryHelper public readonly cloudAuth: CloudAuthHelper - public readonly visibleToasts: Locator /** Worker index to test user ID */ public readonly userIds: string[] = [] @@ -277,7 +276,6 @@ export class ComfyPage { this.contextMenu = new ContextMenu(page) this.currentUserPopover = new CurrentUserPopover(page) this.toast = new ToastHelper(page) - this.visibleToasts = this.toast.visibleToasts this.dragDrop = new DragDropHelper(page) this.featureFlags = new FeatureFlagHelper(page) this.command = new CommandHelper(page) diff --git a/browser_tests/fixtures/components/AgentPanel.ts b/browser_tests/fixtures/components/AgentPanel.ts index d03d2a83579..7c5d1834ebe 100644 --- a/browser_tests/fixtures/components/AgentPanel.ts +++ b/browser_tests/fixtures/components/AgentPanel.ts @@ -8,37 +8,37 @@ import frMessages from '@/locales/fr/main.json' with { type: 'json' } import { TestIds } from '@e2e/fixtures/selectors' export class AgentPanel { - public readonly root: Locator - public readonly dockedPanel: Locator - public readonly openButton: Locator + public readonly activityRows: Locator + public readonly attachmentChips: Locator public readonly closeButton: Locator - public readonly debugHeading: Locator - public readonly serverLogsSwitch: Locator - public readonly settingsSwitch: Locator - public readonly workflowSwitch: Locator - public readonly copyReportButton: Locator + public readonly composer: Locator + public readonly composerAssetSection: Locator + public readonly composerPromptArea: Locator public readonly copiedButton: Locator - public readonly workflowPicker: Locator + public readonly copyReportButton: Locator + public readonly creditsExhaustedPaywall: Locator + public readonly debugHeading: Locator + public readonly dockedPanel: Locator + public readonly dockedPanelShell: Locator public readonly fileInput: Locator - public readonly composerAssetSection: Locator + public readonly nodeSelectionBanner: Locator + public readonly openButton: Locator + public readonly root: Locator public readonly scrollAssetsRight: Locator - public readonly attachmentChips: Locator - public readonly composer: Locator - public readonly composerPromptArea: Locator public readonly sendButton: Locator + public readonly serverLogsSwitch: Locator + public readonly settingsSwitch: Locator public readonly stopButton: Locator - public readonly creditsExhaustedPaywall: Locator + public readonly workflowPicker: Locator + public readonly workflowSwitch: Locator public readonly workSummary: Locator - public readonly nodeSelectionBanner: Locator - public readonly activityRows: Locator constructor(private readonly page: Page) { this.root = page.locator('#agent-panel-root') - this.dockedPanel = page.getByTestId('docked-agent-panel') - this.openButton = page.getByRole('button', { - name: enMessages.agent.entryButton, - exact: true - }) + this.activityRows = this.root + .getByTestId(TestIds.agent.activityTrace) + .getByRole('listitem') + this.attachmentChips = this.root.getByTestId('agent-attachment-chip') this.closeButton = this.root .locator('header') .getByRole('button', { name: enMessages.g.close, exact: true }) @@ -48,46 +48,48 @@ export class AgentPanel { exact: true }) ) - this.debugHeading = this.root.getByText('CRDT debug', { exact: true }) - this.serverLogsSwitch = this.root.getByRole('switch', { - name: 'Server logs' - }) - this.settingsSwitch = this.root.getByRole('switch', { name: 'Settings' }) - this.workflowSwitch = this.root.getByRole('switch', { - name: 'Workflow JSON' - }) + this.composer = this.root.getByRole('textbox', { name: /^Describe ideas/ }) + this.composerAssetSection = this.root.getByTestId('composer-asset-section') + this.composerPromptArea = this.root.getByTestId('composer-inline-input') + this.copiedButton = this.root.getByRole('button', { name: 'Copied' }) this.copyReportButton = this.root.getByRole('button', { name: 'Copy full report' }) - this.copiedButton = this.root.getByRole('button', { name: 'Copied' }) - this.workflowPicker = this.root.getByRole('button', { - name: enMessages.agent.switchWorkflow + this.creditsExhaustedPaywall = this.root.getByRole('alert').filter({ + hasText: enMessages.agent.paywall.title }) + this.debugHeading = this.root.getByText('CRDT debug', { exact: true }) + this.dockedPanel = page.getByTestId('docked-agent-panel') + this.dockedPanelShell = page.getByTestId('docked-agent-panel-shell') this.fileInput = this.root.getByTestId('agent-file-input') - this.composerAssetSection = this.root.getByTestId('composer-asset-section') + this.nodeSelectionBanner = page.getByTestId('node-selection-mode-banner') + this.openButton = page.getByRole('button', { + name: enMessages.agent.entryButton, + exact: true + }) this.scrollAssetsRight = this.root.getByRole('button', { name: enMessages.g.scrollRight }) - this.attachmentChips = this.root.getByTestId('agent-attachment-chip') - this.composer = this.root.getByRole('textbox', { name: /^Describe ideas/ }) - this.composerPromptArea = this.root.getByTestId('composer-inline-input') this.sendButton = this.root.getByRole('button', { name: enMessages.agent.send }) + this.serverLogsSwitch = this.root.getByRole('switch', { + name: 'Server logs' + }) + this.settingsSwitch = this.root.getByRole('switch', { name: 'Settings' }) this.stopButton = this.root.getByRole('button', { name: enMessages.agent.stop, exact: true }) - this.creditsExhaustedPaywall = this.root.getByRole('alert').filter({ - hasText: enMessages.agent.paywall.title + this.workflowPicker = this.root.getByRole('button', { + name: enMessages.agent.switchWorkflow + }) + this.workflowSwitch = this.root.getByRole('switch', { + name: 'Workflow JSON' }) this.workSummary = this.root.getByRole('button', { name: new RegExp(`^${escapeRegExp(enMessages.agent.worked)}`) }) - this.nodeSelectionBanner = page.getByTestId('node-selection-mode-banner') - this.activityRows = this.root - .getByTestId(TestIds.agent.activityTrace) - .getByRole('listitem') } async scrollAssetsToEnd(): Promise { diff --git a/browser_tests/fixtures/components/ModelImportProgressToast.ts b/browser_tests/fixtures/components/ModelImportProgressToast.ts index 058ff65378e..50fb766c0c2 100644 --- a/browser_tests/fixtures/components/ModelImportProgressToast.ts +++ b/browser_tests/fixtures/components/ModelImportProgressToast.ts @@ -1,5 +1,7 @@ import type { Locator, Page } from '@playwright/test' +import { TestIds } from '@e2e/fixtures/selectors' + export class ModelImportProgressToast { public readonly root: Locator public readonly expandButton: Locator @@ -7,7 +9,9 @@ export class ModelImportProgressToast { public readonly filterOptions: Locator constructor(page: Page) { - this.root = page.getByRole('status').filter({ hasText: 'Importing Models' }) + this.root = page + .getByTestId(TestIds.toast.panel) + .filter({ hasText: 'Importing Models' }) this.expandButton = this.root.getByRole('button', { name: 'Expand' }) this.filterButton = this.root.getByRole('button', { name: /^(All|Completed|Failed)$/ diff --git a/browser_tests/fixtures/components/SidebarTab.ts b/browser_tests/fixtures/components/SidebarTab.ts index 5c97d5e3089..08e5b049b5d 100644 --- a/browser_tests/fixtures/components/SidebarTab.ts +++ b/browser_tests/fixtures/components/SidebarTab.ts @@ -4,6 +4,7 @@ import { expect } from '@playwright/test' import type { ComfyMouse } from '@e2e/fixtures/ComfyMouse' import type { WorkspaceStore } from '@e2e/types/globals' import { TestIds } from '@e2e/fixtures/selectors' +import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' export class SidebarTab { public readonly tabButton: Locator @@ -389,6 +390,8 @@ export class AssetsSidebarTab extends SidebarTab { // --- Loading --- public readonly skeletonLoaders: Locator + private readonly toast: ToastHelper + constructor(public override readonly page: Page) { super(page, 'assets') this.generatedTab = page.getByRole('tab', { name: 'Generated' }) @@ -447,6 +450,7 @@ export class AssetsSidebarTab extends SidebarTab { this.skeletonLoaders = page.locator( '.sidebar-content-container .animate-pulse' ) + this.toast = new ToastHelper(page) } emptyStateTitle(title: string) { @@ -485,7 +489,7 @@ export class AssetsSidebarTab extends SidebarTab { override async open({ waitForAssets = true } = {}) { // Remove any toast notifications that may overlay the sidebar button - await this.dismissToasts() + await this.toast.closeToasts() await super.open() await this.generatedTab.waitFor({ state: 'visible' }) if (waitForAssets) { @@ -493,26 +497,14 @@ export class AssetsSidebarTab extends SidebarTab { } } - /** Dismiss all visible toast notifications by clicking their close buttons. */ - async dismissToasts() { - const closeButtons = this.page.locator('.p-toast-close-button') - for (const btn of await closeButtons.all()) { - await btn.click().catch(() => {}) - } - // Wait for all toast elements to fully animate out and detach from DOM - await expect(this.page.locator('.p-toast-message')) - .toHaveCount(0) - .catch(() => {}) - } - async switchToImported() { - await this.dismissToasts() + await this.toast.closeToasts() await this.importedTab.click() await expect(this.importedTab).toHaveAttribute('aria-selected', 'true') } async switchToGenerated() { - await this.dismissToasts() + await this.toast.closeToasts() await this.generatedTab.click() await expect(this.generatedTab).toHaveAttribute('aria-selected', 'true') } @@ -539,7 +531,7 @@ export class AssetsSidebarTab extends SidebarTab { } async openSettingsMenu() { - await this.dismissToasts() + await this.toast.closeToasts() await this.settingsButton.click() await expect( this.listViewOption @@ -562,7 +554,7 @@ export class AssetsSidebarTab extends SidebarTab { } async openFilterMenu() { - await this.dismissToasts() + await this.toast.closeToasts() await this.filterButton.click() await expect(this.mediaTypeFilterMenuItem).toBeVisible() } diff --git a/browser_tests/fixtures/helpers/AssetsHelper.ts b/browser_tests/fixtures/helpers/AssetsHelper.ts index bbef403b0e1..0c055b758be 100644 --- a/browser_tests/fixtures/helpers/AssetsHelper.ts +++ b/browser_tests/fixtures/helpers/AssetsHelper.ts @@ -10,7 +10,10 @@ import type { JobDetail, RawJobListItem } from '@/platform/remote/comfyui/jobs/jobTypes' -import type { AssetDownloadWsMessage } from '@/platform/remote/comfyui/execution/types' +import type { + AssetDownloadWsMessage, + AssetExportWsMessage +} from '@/platform/remote/comfyui/execution/types' const jobsListRoutePattern = '**/api/jobs?*' const assetsListRoutePattern = /\/api\/assets(?:\?.*)?$/ @@ -145,6 +148,12 @@ export class AssetsHelper { }, message) } + async dispatchExport(message: AssetExportWsMessage): Promise { + await this.page.evaluate((assetExport) => { + window.app!.api.dispatchCustomEvent('asset_export', assetExport) + }, message) + } + async mockOutputHistory(jobs: RawJobListItem[]): Promise { this.generatedJobs = [...jobs] diff --git a/browser_tests/fixtures/helpers/ToastHelper.ts b/browser_tests/fixtures/helpers/ToastHelper.ts index cfe7581bc88..f1ef9838809 100644 --- a/browser_tests/fixtures/helpers/ToastHelper.ts +++ b/browser_tests/fixtures/helpers/ToastHelper.ts @@ -1,19 +1,39 @@ import { expect } from '@playwright/test' import type { Locator, Page } from '@playwright/test' +import { TestIds } from '@e2e/fixtures/selectors' + +type ToastKind = 'error' | 'success' | 'warning' | 'loading' + +const TOAST_SELECTOR = '[data-testid="toast"]' + +export function toastSelector(kind: ToastKind): string { + return `${TOAST_SELECTOR}[data-toast-kind="${kind}"]` +} + export class ToastHelper { - public readonly visibleToasts: Locator + public readonly panels: Locator public readonly toastErrors: Locator + public readonly toastLoadings: Locator public readonly toastSuccesses: Locator public readonly toastWarnings: Locator + public readonly visibleToasts: Locator + + constructor(page: Page) { + this.panels = page.getByTestId(TestIds.toast.panel) + this.toastErrors = page.locator(toastSelector('error')) + this.toastLoadings = page.locator(toastSelector('loading')) + this.toastSuccesses = page.locator(toastSelector('success')) + this.toastWarnings = page.locator(toastSelector('warning')) + this.visibleToasts = page.locator(TOAST_SELECTOR).filter({ visible: true }) + } + + withText(text: string | RegExp): Locator { + return this.visibleToasts.filter({ hasText: text }) + } - constructor(private readonly page: Page) { - this.visibleToasts = page.locator('.p-toast-message:visible') - this.toastErrors = page.locator('.p-toast-message.p-toast-message-error') - this.toastSuccesses = page.locator( - '.p-toast-message.p-toast-message-success' - ) - this.toastWarnings = page.locator('.p-toast-message.p-toast-message-warn') + async dismiss(toast: Locator): Promise { + await toast.getByTestId('toast-close').click() } async closeToasts(requireCount = 0): Promise { @@ -23,15 +43,12 @@ export class ToastHelper { .waitFor({ state: 'visible' }) } - // Clear all toasts - const toastCloseButtons = await this.page - .locator('.p-toast-close-button') - .all() - for (const button of toastCloseButtons) { - await button.click() + const closeButtons = this.visibleToasts.getByTestId('toast-close') + for (let open = await closeButtons.count(); open > 0; open--) { + await closeButtons.first().click() + await expect(closeButtons).toHaveCount(open - 1) } - // Assert all toasts are closed await expect(this.visibleToasts).toHaveCount(0) } } diff --git a/browser_tests/fixtures/networkIsolationFixture.ts b/browser_tests/fixtures/networkIsolationFixture.ts index 965f19650bc..00c5a839dad 100644 --- a/browser_tests/fixtures/networkIsolationFixture.ts +++ b/browser_tests/fixtures/networkIsolationFixture.ts @@ -3,6 +3,7 @@ import { expect, test as base } from '@playwright/test' import { config as dotenvConfig } from 'dotenv' import { HERO_SLIDES } from '@/platform/cloud/onboarding/constants/heroSlides' +import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' import type { LiveCloudBillingConfig } from '@e2e/fixtures/utils/liveCloudBillingConfig' import { installLiveCloudBillingRouting } from '@e2e/fixtures/utils/liveCloudBillingContext' import { @@ -56,8 +57,9 @@ function guardApiRequests( } export const networkIsolationFixture = base.extend<{ - networkPolicy: NetworkPolicy liveCloudBillingConfig: LiveCloudBillingConfig | undefined + networkPolicy: NetworkPolicy + toast: ToastHelper }>({ serviceWorkers: 'block', liveCloudBillingConfig: [undefined, { option: true }], @@ -190,5 +192,8 @@ export const networkIsolationFixture = base.extend<{ } await use(context) restore() + }, + toast: async ({ page }, use) => { + await use(new ToastHelper(page)) } }) diff --git a/browser_tests/fixtures/selectors.ts b/browser_tests/fixtures/selectors.ts index e2c8324006d..9d26be208eb 100644 --- a/browser_tests/fixtures/selectors.ts +++ b/browser_tests/fixtures/selectors.ts @@ -150,6 +150,9 @@ export const TestIds = { card: 'asset-card', videoPreview: 'media-asset-video' }, + toast: { + panel: 'toast-panel' + }, subgraphEditor: { hiddenSection: 'subgraph-editor-hidden-section', iconEye: 'icon-eye', diff --git a/browser_tests/fixtures/utils/errorSurfaces.ts b/browser_tests/fixtures/utils/errorSurfaces.ts index 271032a8e24..27fa3101349 100644 --- a/browser_tests/fixtures/utils/errorSurfaces.ts +++ b/browser_tests/fixtures/utils/errorSurfaces.ts @@ -1,6 +1,7 @@ import type { Locator, Page } from '@playwright/test' import { expect } from '@playwright/test' +import { ToastHelper, toastSelector } from '@e2e/fixtures/helpers/ToastHelper' import { TestIds } from '@e2e/fixtures/selectors' interface VisibleError { @@ -25,7 +26,10 @@ const visibleErrorSurfaceSelectors = [ selector: `[data-testid="${TestIds.dialogs.errorDialog}"]` }, { surface: 'nodeRenderErrors', selector: '.node-error' }, - { surface: 'errorToasts', selector: '.p-toast-message-error' } + { + surface: 'errorToasts', + selector: toastSelector('error') + } ] const visibleErrorSampleIntervalMs = 100 @@ -92,7 +96,7 @@ export function errorSurfaces(page: Page): Record { errorOverlay: page.getByTestId(TestIds.dialogs.errorOverlay), errorDialog: page.getByTestId(TestIds.dialogs.errorDialog), nodeRenderErrors: page.locator('.node-error'), - errorToasts: page.locator('.p-toast-message-error') + errorToasts: new ToastHelper(page).toastErrors } } diff --git a/browser_tests/tests/agent/agentDuplicateInsertOpaqueWidgetWrite.spec.ts b/browser_tests/tests/agent/agentDuplicateInsertOpaqueWidgetWrite.spec.ts index 4a7c20d1739..ec6e50c530f 100644 --- a/browser_tests/tests/agent/agentDuplicateInsertOpaqueWidgetWrite.spec.ts +++ b/browser_tests/tests/agent/agentDuplicateInsertOpaqueWidgetWrite.spec.ts @@ -14,7 +14,6 @@ import { } from '@e2e/fixtures/agentPanelFixture' import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' -import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' import { nextFrame } from '@e2e/fixtures/utils/timing' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' import { webSocketFixture } from '@e2e/fixtures/ws' @@ -464,6 +463,7 @@ test.describe( test('a rejected widget edit is reported and rolled back to the value the shared document kept', async ({ page, + toast, getWebSocket }) => { const { host, seedInput, copyBNodeId } = @@ -486,7 +486,7 @@ test.describe( // and `toContainText` passes on any node in the collection, so either // alone would accept a message the user never sees. Filter to the text // and require it on screen. - const rejectionToast = new ToastHelper(page).toastErrors.filter({ + const rejectionToast = toast.toastErrors.filter({ hasText: 'Widget edit was rejected and was not saved' }) await expect(rejectionToast).toBeVisible({ timeout: 3_000 }) diff --git a/browser_tests/tests/agent/agentPanel.spec.ts b/browser_tests/tests/agent/agentPanel.spec.ts index 6afc2231fb0..d34bbc52474 100644 --- a/browser_tests/tests/agent/agentPanel.spec.ts +++ b/browser_tests/tests/agent/agentPanel.spec.ts @@ -633,7 +633,7 @@ test.describe('In-App Agent panel', { tag: '@cloud' }, () => { buffer: Buffer.alloc(25 * 1024 * 1024) }) await expect( - page.getByText('too-large.mp4 is larger than 24 MB') + comfyPage.toast.withText('too-large.mp4 is larger than 24 MB') ).toBeVisible() await expect( panel.getByRole('group', { name: 'too-large.mp4' }) diff --git a/browser_tests/tests/agent/agentPanelAppMode.spec.ts b/browser_tests/tests/agent/agentPanelAppMode.spec.ts index e32c2af432b..b632591c6f6 100644 --- a/browser_tests/tests/agent/agentPanelAppMode.spec.ts +++ b/browser_tests/tests/agent/agentPanelAppMode.spec.ts @@ -1,22 +1,20 @@ import { expect } from '@playwright/test' -import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { WorkspaceStore } from '@e2e/types/globals' import { agentTest as test } from '@e2e/tests/agent/agentPanelMocks' -const OPEN_AGENT_LABEL = enMessages.agent.entryButton const OPEN_STORAGE_KEY = 'Comfy.AgentPanel.open' test.describe('In-App Agent panel across view modes', { tag: '@cloud' }, () => { test('T-16 / PM-653 / FE-1298 keeps a single docked panel root and active workflow in app mode', async ({ + agentPanel, comfyPage }) => { test.setTimeout(30_000) const page = comfyPage.page - const panelRoot = page.locator('#agent-panel-root') const activeWorkflowPath = () => page.evaluate( () => @@ -27,32 +25,41 @@ test.describe('In-App Agent panel across view modes', { tag: '@cloud' }, () => { expect(selectedWorkflowPath).toBeTruthy() - const openButton = page.getByRole('button', { - name: OPEN_AGENT_LABEL, - exact: true - }) - await expect(openButton).toBeVisible() - await new AgentPanel(page).open() + await expect(agentPanel.openButton).toBeVisible() + await agentPanel.open() - await expect(panelRoot).toHaveCount(1) - await expect(panelRoot).toBeVisible() + await expect(agentPanel.root).toHaveCount(1) + await expect(agentPanel.root).toBeVisible() await expect .poll(() => page.evaluate((key) => localStorage.getItem(key), OPEN_STORAGE_KEY) ) .toBe('true') + await expect(agentPanel.dockedPanelShell).toHaveCSS( + 'border-left-width', + '0px' + ) + // Enter app mode: the docked panel re-hosts under LinearView. await comfyPage.appMode.toggleAppMode() - await expect(panelRoot).toHaveCount(1) - await expect(panelRoot).toBeVisible() + await expect(agentPanel.root).toHaveCount(1) + await expect(agentPanel.root).toBeVisible() await expect.poll(activeWorkflowPath).toBe(selectedWorkflowPath) + await expect(agentPanel.dockedPanelShell).toHaveCSS( + 'border-left-width', + '1px' + ) // Return to graph mode: the docked panel re-hosts under GraphCanvas. await comfyPage.appMode.toggleAppMode() - await expect(panelRoot).toHaveCount(1) - await expect(panelRoot).toBeVisible() + await expect(agentPanel.root).toHaveCount(1) + await expect(agentPanel.root).toBeVisible() await expect.poll(activeWorkflowPath).toBe(selectedWorkflowPath) + await expect(agentPanel.dockedPanelShell).toHaveCSS( + 'border-left-width', + '0px' + ) }) test('keeps a user-closed panel hidden when toggling app mode and back', async ({ diff --git a/browser_tests/tests/agent/agentPreviewTextWidgetNotMinted.spec.ts b/browser_tests/tests/agent/agentPreviewTextWidgetNotMinted.spec.ts index 1df4dfeb661..1e69a053b82 100644 --- a/browser_tests/tests/agent/agentPreviewTextWidgetNotMinted.spec.ts +++ b/browser_tests/tests/agent/agentPreviewTextWidgetNotMinted.spec.ts @@ -6,7 +6,6 @@ import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { AgentNonValueWidgetRig } from '@e2e/fixtures/agentNonValueWidgetRig' import type { AgentFollowerHostSocket } from '@e2e/fixtures/agentFollowerHostSocket' import { agentTest as test } from '@e2e/fixtures/agentPanelFixture' -import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' /** * `preview_text` reaches the minter through an `executed` frame, the node's @@ -142,7 +141,8 @@ test.describe( { tag: ['@cloud', '@agent', '@vue-nodes', '@widget'] }, () => { test('execution text output mints nothing and never tells the user an edit was rejected', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const rig = await AgentNonValueWidgetRig.boot(page, rigConfig) @@ -174,7 +174,7 @@ test.describe( }) await test.step('no rejection toast, hand edit still on screen', async () => { - const rejectionToast = new ToastHelper(page).toastErrors.filter({ + const rejectionToast = toast.toastErrors.filter({ hasText: 'Widget edit was rejected and was not saved' }) await expect(rejectionToast).toHaveCount(0) diff --git a/browser_tests/tests/agent/agentProgressTextWidgetNotMinted.spec.ts b/browser_tests/tests/agent/agentProgressTextWidgetNotMinted.spec.ts index 82eb5ee448a..727e6fe9276 100644 --- a/browser_tests/tests/agent/agentProgressTextWidgetNotMinted.spec.ts +++ b/browser_tests/tests/agent/agentProgressTextWidgetNotMinted.spec.ts @@ -8,7 +8,6 @@ import { progressTextFrame } from '@e2e/fixtures/agentNonValueWidgetRig' import { agentTest as test } from '@e2e/fixtures/agentPanelFixture' -import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' /** * `$$node-text-preview` is a `serialize: false` widget written by binary @@ -90,7 +89,8 @@ test.describe( { tag: ['@cloud', '@agent', '@vue-nodes', '@widget'] }, () => { test('streaming execution progress mints nothing and never tells the user an edit was rejected', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const rig = await AgentNonValueWidgetRig.boot(page, rigConfig) @@ -125,7 +125,7 @@ test.describe( }) await test.step('no rejection toast, hand edit still on screen', async () => { - const rejectionToast = new ToastHelper(page).toastErrors.filter({ + const rejectionToast = toast.toastErrors.filter({ hasText: 'Widget edit was rejected and was not saved' }) await expect(rejectionToast).toHaveCount(0) diff --git a/browser_tests/tests/agent/agentRunModePopover.spec.ts b/browser_tests/tests/agent/agentRunModePopover.spec.ts index 8d9ecf73259..54e5b2b08a9 100644 --- a/browser_tests/tests/agent/agentRunModePopover.spec.ts +++ b/browser_tests/tests/agent/agentRunModePopover.spec.ts @@ -187,7 +187,7 @@ test.describe('Agent run permissions popover', { tag: '@cloud' }, () => { await test.step('the rejected pick keeps the menu, focus and old mode', async () => { await expect( - page.getByText(enMessages.agent.runModeSaveFailed) + comfyPage.toast.withText(enMessages.agent.runModeSaveFailed) ).toBeVisible() await expect(autoOption).toBeFocused() await expect(autoOption).not.toBeChecked() diff --git a/browser_tests/tests/agent/agentUndefinedSerializeWidgetNotMinted.spec.ts b/browser_tests/tests/agent/agentUndefinedSerializeWidgetNotMinted.spec.ts index 909b10aef97..67e898f20a6 100644 --- a/browser_tests/tests/agent/agentUndefinedSerializeWidgetNotMinted.spec.ts +++ b/browser_tests/tests/agent/agentUndefinedSerializeWidgetNotMinted.spec.ts @@ -5,7 +5,6 @@ import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { AgentNonValueWidgetRig } from '@e2e/fixtures/agentNonValueWidgetRig' import { agentTest as test } from '@e2e/fixtures/agentPanelFixture' -import { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' /** * The sibling `agentProgressTextWidgetNotMinted` spec covers the ephemeral @@ -103,7 +102,8 @@ test.describe( { tag: ['@cloud', '@agent', '@vue-nodes', '@widget'] }, () => { test('an ephemeral widget that leaves serialize undefined mints nothing and never tells the user an edit was rejected', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const rig = await AgentNonValueWidgetRig.boot(page, rigConfig) @@ -156,7 +156,7 @@ test.describe( }) await test.step('no rejection toast, hand edit still on screen', async () => { - const rejectionToast = new ToastHelper(page).toastErrors.filter({ + const rejectionToast = toast.toastErrors.filter({ hasText: 'Widget edit was rejected and was not saved' }) await expect(rejectionToast).toHaveCount(0) diff --git a/browser_tests/tests/agent/agentWorkflowSelection.spec.ts b/browser_tests/tests/agent/agentWorkflowSelection.spec.ts index b0e852c4926..5032112e7f0 100644 --- a/browser_tests/tests/agent/agentWorkflowSelection.spec.ts +++ b/browser_tests/tests/agent/agentWorkflowSelection.spec.ts @@ -545,6 +545,7 @@ test.describe( test('keeps the failed selection open and allows retry without a naming dialog', async ({ page, + toast, workflowSelection }) => { await new AgentPanel(page).open() @@ -564,7 +565,7 @@ test.describe( await expect(row).toBeEnabled() await expect(row).toBeChecked() await expect( - page.getByText(enMessages.shareWorkflow.saveFailedTitle) + toast.withText(enMessages.shareWorkflow.saveFailedTitle) ).toBeVisible() await expect(composer).toHaveText('Keep this draft') await row.click() diff --git a/browser_tests/tests/authAccountSwitch.spec.ts b/browser_tests/tests/authAccountSwitch.spec.ts index 6aab84d93b0..81866a0595e 100644 --- a/browser_tests/tests/authAccountSwitch.spec.ts +++ b/browser_tests/tests/authAccountSwitch.spec.ts @@ -6,6 +6,7 @@ import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/workspa import type { Page } from '@playwright/test' import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { CurrentUserPopover } from '@e2e/fixtures/components/CurrentUserPopover' import { AssetsSidebarTab } from '@e2e/fixtures/components/SidebarTab' import { CLOUD_REMOTE_CONFIG, @@ -335,14 +336,13 @@ test.describe('Cloud account switch', { tag: '@cloud' }, () => { .fill('password') await page.getByRole('button', { name: 'Sign in' }).click() + const popover = new CurrentUserPopover(page) + await expect(popover.trigger).toBeVisible() + await popover.open() await expect( - page.getByRole('button', { name: 'Current user' }) + popover.root.getByText(ACCOUNT_B.email, { exact: true }) ).toBeVisible() - await page.getByRole('button', { name: 'Current user' }).click() - await expect( - page.getByText(ACCOUNT_B.email, { exact: true }) - ).toBeVisible() - await page.keyboard.press('Escape') + await popover.close() await expect .poll(() => workspaceMintOwners, { timeout: 15_000 }) .toContain(ACCOUNT_B.id) diff --git a/browser_tests/tests/cloudOnboardingAuth.spec.ts b/browser_tests/tests/cloudOnboardingAuth.spec.ts index 11ed16d7a08..4bf04a998ca 100644 --- a/browser_tests/tests/cloudOnboardingAuth.spec.ts +++ b/browser_tests/tests/cloudOnboardingAuth.spec.ts @@ -101,6 +101,7 @@ test.describe('Cloud onboarding — live auth', { tag: '@cloud' }, () => { test('shows an inline error and stays on the login page on a wrong password', async ({ page, + toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignInFailure({ @@ -114,7 +115,7 @@ test.describe('Cloud onboarding — live auth', { tag: '@cloud' }, () => { await page.locator('#cloud-sign-in-password').blur() await page.getByRole('button', { name: 'Sign in' }).click() - await expect(page.getByText('Invalid login credentials')).toBeVisible() + await expect(toast.withText('Invalid login credentials')).toBeVisible() await expect(page).toHaveURL(/\/cloud\/login/) }) diff --git a/browser_tests/tests/cloudOnboardingAuthErrors.spec.ts b/browser_tests/tests/cloudOnboardingAuthErrors.spec.ts index a37b241f1be..9a126066b33 100644 --- a/browser_tests/tests/cloudOnboardingAuthErrors.spec.ts +++ b/browser_tests/tests/cloudOnboardingAuthErrors.spec.ts @@ -65,6 +65,7 @@ async function openSignupEmailForm(page: Page) { test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => { test('shows the same neutral copy for a nonexistent account as a wrong password', async ({ page, + toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignInFailure({ @@ -79,12 +80,12 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => await page.getByRole('button', { name: 'Sign in' }).click() await expect( - page.getByText('Invalid login credentials'), + toast.withText('Invalid login credentials'), 'the same copy as a wrong password keeps sign-in from revealing whether an email has an account' ).toBeVisible() }) - test('reports a disabled account', async ({ page, cloudAuth }) => { + test('reports a disabled account', async ({ page, toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignInFailure({ code: 400, message: 'USER_DISABLED' @@ -99,12 +100,13 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => await page.getByRole('button', { name: 'Sign in' }).click() await expect( - page.getByText('This account has been disabled. Please contact support.') + toast.withText('This account has been disabled. Please contact support.') ).toBeVisible() }) test('reports rate limiting after repeated failed attempts', async ({ page, + toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignInFailure({ @@ -119,7 +121,7 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => await page.getByRole('button', { name: 'Sign in' }).click() await expect( - page.getByText( + toast.withText( 'Too many login attempts. Please wait a moment and try again.' ) ).toBeVisible() @@ -127,6 +129,7 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => test('reports a duplicate email on sign-up instead of creating a second account', async ({ page, + toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignUpFailure({ @@ -143,13 +146,14 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => await page.getByRole('button', { name: 'Sign up', exact: true }).click() await expect( - page.getByText(enMessages.auth.errors['auth/email-already-in-use']) + toast.withText(enMessages.auth.errors['auth/email-already-in-use']) ).toBeVisible() await expect(page).toHaveURL(/\/cloud\/signup/) }) test('reports a dropped connection without claiming invalid credentials', async ({ page, + toast, cloudAuth }) => { await cloudAuth.mockLiveEmailSignInTransportFailure() @@ -163,7 +167,7 @@ test.describe('Cloud onboarding — auth error codes', { tag: '@cloud' }, () => await page.getByRole('button', { name: 'Sign in' }).click() await expect( - page.getByText( + toast.withText( 'Network error. Please check your connection and try again.' ) ).toBeVisible() diff --git a/browser_tests/tests/cloudWorkspaceDeepLink.spec.ts b/browser_tests/tests/cloudWorkspaceDeepLink.spec.ts index cfa4911c0ff..72317bf1248 100644 --- a/browser_tests/tests/cloudWorkspaceDeepLink.spec.ts +++ b/browser_tests/tests/cloudWorkspaceDeepLink.spec.ts @@ -54,7 +54,7 @@ test.describe('Cloud workspace deep link', { tag: '@cloud' }, () => { const page = comfyPage.page await expect( - page.getByText(`You're still in ${PERSONAL_WORKSPACE_NAME}`) + comfyPage.toast.withText(`You're still in ${PERSONAL_WORKSPACE_NAME}`) ).toBeVisible() expect(new URL(page.url()).searchParams.has('workspace')).toBe(false) @@ -82,7 +82,7 @@ test.describe('Cloud workspace deep link', { tag: '@cloud' }, () => { await comfyPage.waitForAppReady() await expect( - page.getByText(`You're still in ${PERSONAL_WORKSPACE_NAME}`) + comfyPage.toast.withText(`You're still in ${PERSONAL_WORKSPACE_NAME}`) ).toBeVisible() expect(new URL(page.url()).searchParams.has('workspace')).toBe(false) }) @@ -90,7 +90,7 @@ test.describe('Cloud workspace deep link', { tag: '@cloud' }, () => { test('is unchanged with no workspace param', async ({ comfyPage }) => { const page = comfyPage.page - await expect(page.locator('.p-toast-message:visible')).toHaveCount(0) + await expect(comfyPage.toast.visibleToasts).toHaveCount(0) await page.getByRole('button', { name: 'Current user' }).click() await expect(page.getByTestId('workspace-switcher-trigger')).toContainText( PERSONAL_WORKSPACE_NAME diff --git a/browser_tests/tests/customNodes/errorSurfaces.spec.ts b/browser_tests/tests/customNodes/errorSurfaces.spec.ts index 74a7d7a914f..c15aa4afa2a 100644 --- a/browser_tests/tests/customNodes/errorSurfaces.spec.ts +++ b/browser_tests/tests/customNodes/errorSurfaces.spec.ts @@ -20,8 +20,8 @@ test('a persistent error toast fails carrying its visible text', async ({ page }) => { await page.setContent( - '
Failed to load workspace: HTTP 502
' + - '
Settings seed rejected
' + '
Failed to load workspace: HTTP 502
' + + '
Settings seed rejected
' ) const failure = await expectNoVisibleErrors(page, 'at startup').then( () => undefined, @@ -54,7 +54,8 @@ test('a visible error toast fails after it clears before the assertion', async ( await page.evaluate(() => { const toast = document.createElement('div') toast.id = 't' - toast.className = 'p-toast-message-error' + toast.dataset.testid = 'toast' + toast.dataset.toastKind = 'error' toast.textContent = 'momentary' document.getElementById('root')!.append(toast) setTimeout(() => toast.remove(), 800) @@ -68,16 +69,20 @@ test('a visible error toast fails after it clears before the assertion', async ( expect(String(failure)).toContain('momentary') }) -test('an error class added after insertion fails after it clears', async ({ +test('error toast attributes added after insertion fail after they clear', async ({ page }) => { await page.setContent('
late error
') await page.evaluate(() => { const toast = document.getElementById('t')! - toast.classList.add('p-toast-message-error') - setTimeout(() => toast.classList.remove('p-toast-message-error'), 800) + toast.dataset.testid = 'toast' + toast.dataset.toastKind = 'error' + setTimeout(() => { + delete toast.dataset.testid + delete toast.dataset.toastKind + }, 800) }) - await expect(page.locator('#t')).not.toHaveClass('p-toast-message-error') + await expect(page.locator('#t')).not.toHaveAttribute('data-toast-kind') const failure = await expectNoVisibleErrors(page, 'class-added').then( () => undefined, (error: unknown) => error @@ -91,7 +96,7 @@ test('a hidden error fails when an ancestor mutation reveals it', async ({ }) => { await page.setContent( '' ) await page.evaluate(() => { diff --git a/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts b/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts index 834f4066bc0..beb98bc8425 100644 --- a/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts +++ b/browser_tests/tests/dialogs/billingPortalOrigin.spec.ts @@ -154,7 +154,8 @@ test.describe('Billing portal origin (#19892)', { tag: '@cloud' }, () => { }) test('opens nothing and reports the refusal for a look-alike portal host', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const portalOpens = await setupRefusedPlanChange(page, LOOK_ALIKE_PORTAL) @@ -163,7 +164,7 @@ test.describe('Billing portal origin (#19892)', { tag: '@cloud' }, () => { // The customer still gets the server's own guidance, which is what tells // them what to do; the rejected host never reaches a tab. - await expect(page.getByText(PAYMENT_REQUIRED.message)).toBeVisible() + await expect(toast.withText(PAYMENT_REQUIRED.message)).toBeVisible() expect(await portalOpens()).toEqual([]) }) }) diff --git a/browser_tests/tests/dialogs/billingProgressToastParity.spec.ts b/browser_tests/tests/dialogs/billingProgressToastParity.spec.ts index c6c52ace60a..6cb65d37586 100644 --- a/browser_tests/tests/dialogs/billingProgressToastParity.spec.ts +++ b/browser_tests/tests/dialogs/billingProgressToastParity.spec.ts @@ -278,23 +278,27 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { for (const { name, rails } of RAIL_MATRIX) { test.describe(`on the ${name} rail`, () => { test('announces a processing subscribe and clears it once it settles', async ({ - page + page, + toast }) => { const server = await setupToastParity(page, { rails }) await confirmCreatorUpgrade(page) - const toast = page.getByText(SUBSCRIPTION_PROCESSING) - await expect(toast).toBeVisible() + const processingToast = toast.toastLoadings.filter({ + hasText: SUBSCRIPTION_PROCESSING + }) + await expect(processingToast).toBeVisible() server.operation = SETTLED_OPERATION await returnToTab(page) await expect(successHeading(page)).toBeVisible() - await expect(toast).toBeHidden() + await expect(processingToast).toBeHidden() }) test('asks for verification while a subscribe waits on the hosted payment page', async ({ - page + page, + toast }) => { await setupToastParity(page, { rails, @@ -308,12 +312,15 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { await confirmCreatorUpgrade(page) - await expect(page.getByText(SUBSCRIPTION_ACTION_REQUIRED)).toBeVisible() - await expect(page.getByText(SUBSCRIPTION_PROCESSING)).toBeHidden() + await expect( + toast.toastWarnings.filter({ hasText: SUBSCRIPTION_ACTION_REQUIRED }) + ).toBeVisible() + await expect(toast.withText(SUBSCRIPTION_PROCESSING)).toBeHidden() }) test('stays quiet after a reload finds the subscribe parked on a payment method', async ({ - page + page, + toast }) => { await setupToastParity(page, { rails, @@ -331,8 +338,8 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { await firstRead await operationRead(page) - await expect(page.getByText(SUBSCRIPTION_PROCESSING)).toHaveCount(0) - await expect(page.getByText(SUBSCRIPTION_ACTION_REQUIRED)).toHaveCount( + await expect(toast.withText(SUBSCRIPTION_PROCESSING)).toHaveCount(0) + await expect(toast.withText(SUBSCRIPTION_ACTION_REQUIRED)).toHaveCount( 0 ) }) @@ -372,7 +379,8 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { } test('asks again for verification after a reload finds the subscribe still waiting', async ({ - page + page, + toast }) => { await setupToastParity(page, { rails, @@ -385,18 +393,20 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { } }) + const actionRequired = toast.withText(SUBSCRIPTION_ACTION_REQUIRED) await page.goto(APP_URL) await waitForCloudApp(page) - await expect(page.getByText(SUBSCRIPTION_ACTION_REQUIRED)).toBeVisible() + await expect(actionRequired).toBeVisible() await page.reload() await waitForCloudApp(page) - await expect(page.getByText(SUBSCRIPTION_ACTION_REQUIRED)).toBeVisible() + await expect(actionRequired).toBeVisible() }) test('announces a processing top-up and clears it once it settles', async ({ - page + page, + toast }) => { const server = await setupToastParity(page, { rails }) await page.goto(APP_URL) @@ -408,16 +418,18 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { .getByRole('button', { name: 'Add credits', exact: true }) .click() await dialog.root.getByRole('button', { name: 'Pay $50.00' }).click() - const toast = page.getByText(TOPUP_PROCESSING) - await expect(toast).toBeVisible() + const processingToast = toast.toastLoadings.filter({ + hasText: TOPUP_PROCESSING + }) + await expect(processingToast).toBeVisible() server.operation = SETTLED_OPERATION await returnToTab(page) - await expect(toast).toBeHidden() + await expect(processingToast).toBeHidden() }) - test('raises no progress toast for a cancel', async ({ page }) => { + test('raises no progress toast for a cancel', async ({ page, toast }) => { await setupToastParity(page, { rails, operation: SETTLED_OPERATION }) await page.goto(APP_URL) await waitForCloudApp(page) @@ -426,8 +438,8 @@ test.describe('Billing progress toast parity', { tag: '@cloud' }, () => { await cancel.open(ACTIVE_STANDARD.renewal_date) await cancel.confirmCancel() - await expect(page.getByText(/Processing payment/)).toHaveCount(0) - await expect(page.getByText(SUBSCRIPTION_ACTION_REQUIRED)).toHaveCount( + await expect(toast.withText(/Processing payment/)).toHaveCount(0) + await expect(toast.withText(SUBSCRIPTION_ACTION_REQUIRED)).toHaveCount( 0 ) }) diff --git a/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts b/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts index 36a750e17e2..92aff971aad 100644 --- a/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts +++ b/browser_tests/tests/dialogs/billingRailParitySdkRail.spec.ts @@ -24,6 +24,7 @@ import { TopUpCreditsDialog } from '@e2e/fixtures/components/TopUpCreditsDialog' import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' import { createPlan } from '@e2e/fixtures/data/billingPlans' import { CLOUD_SELF_EMAIL } from '@e2e/fixtures/helpers/CloudAuthHelper' +import type { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' import { APP_URL, setupCloudApp } from '@e2e/fixtures/utils/cloudAppSetup' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -366,10 +367,8 @@ async function returnToTab(page: Page) { await page.evaluate(() => window.dispatchEvent(new Event('focus'))) } -const successToast = (page: Page) => - page.locator('.p-toast-message-success', { - hasText: 'Credits added successfully!' - }) +const successToast = (toast: ToastHelper) => + toast.toastSuccesses.filter({ hasText: 'Credits added successfully!' }) /** The plan summary on the success step, which names what was bought. */ const successSummary = (page: Page) => @@ -426,10 +425,13 @@ async function expectPortalReturnRefresh( * Buys $50 of credits, then upgrades to Creator from Plan & Credits without * leaving the page, and returns the panel once the success step is closed. */ -async function topUpThenUpgrade(page: Page): Promise { +async function topUpThenUpgrade( + page: Page, + toast: ToastHelper +): Promise { await bootApp(page) const topUp = await buyFiftyDollars(page) - await expect(successToast(page)).toBeVisible() + await expect(successToast(toast)).toBeVisible() await expect(topUp.root).toBeHidden() // A settled purchase lands the customer on Plan & Credits. @@ -460,7 +462,8 @@ async function topUpThenUpgrade(page: Page): Promise { test.describe('Billing rail parity', { tag: '@cloud' }, () => { test.describe('with only the subscription rail on', () => { test('buys credits on the legacy transport and refreshes the balance', async ({ - page + page, + toast }) => { const routes = await setupParity(page, { rails: SUBSCRIPTION_RAIL_ONLY }) await bootApp(page) @@ -468,7 +471,7 @@ test.describe('Billing rail parity', { tag: '@cloud' }, () => { await buyFiftyDollars(page) - await expect(successToast(page)).toBeVisible() + await expect(successToast(toast)).toBeVisible() expect(routes.topupRequests).toHaveLength(1) const [purchase] = routes.topupRequests expect(transport(purchase)).toBe('xhr') @@ -509,10 +512,11 @@ test.describe('Billing rail parity', { tag: '@cloud' }, () => { }) test('completes a top-up and then a subscribe in one session, and totals both', async ({ - page + page, + toast }) => { const routes = await setupParity(page, { rails: SUBSCRIPTION_RAIL_ONLY }) - const panel = await topUpThenUpgrade(page) + const panel = await topUpThenUpgrade(page, toast) expect(routes.topupRequests.map(transport)).toEqual(['xhr']) expect(routes.subscribeRequests.map(transport)).toEqual(['fetch']) diff --git a/browser_tests/tests/dialogs/billingRecoverySdkRail.spec.ts b/browser_tests/tests/dialogs/billingRecoverySdkRail.spec.ts index 67de529f991..10fff87a57e 100644 --- a/browser_tests/tests/dialogs/billingRecoverySdkRail.spec.ts +++ b/browser_tests/tests/dialogs/billingRecoverySdkRail.spec.ts @@ -22,6 +22,7 @@ import { import { createPlan } from '@e2e/fixtures/data/billingPlans' import { makeWorkspaceTokenResponse } from '@e2e/fixtures/data/workspaceAuthFixtures' import { CLOUD_SELF_EMAIL } from '@e2e/fixtures/helpers/CloudAuthHelper' +import type { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' import { APP_URL, setupCloudApp } from '@e2e/fixtures/utils/cloudAppSetup' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -234,10 +235,8 @@ async function payAndOpenVerification(page: Page, routes: TopupRoutes) { const completeVerification = (dialog: TopUpCreditsDialog) => dialog.root.getByRole('button', { name: 'Complete verification' }) -const successToast = (page: Page) => - page - .locator('.p-toast-message.p-toast-message-success') - .getByText('Credits added successfully') +const successToast = (toast: ToastHelper) => + toast.toastSuccesses.filter({ hasText: 'Credits added successfully' }) function transports(requests: Request[]): string[] { return requests.map((request) => request.resourceType()) @@ -565,7 +564,8 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { test.describe('hosted bank verification', () => { test('offers the verification again after the customer abandons the hosted page', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupTopUp(page) @@ -581,11 +581,12 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { await expect(completeVerification(dialog)).not.toHaveAttribute( 'aria-busy' ) - await expect(successToast(page)).toHaveCount(0) + await expect(successToast(toast)).toHaveCount(0) }) test('settles the same purchase when the customer retries the verification', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupTopUp(page) @@ -599,7 +600,7 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { routes.setOperation(SUCCEEDED) await returnToTab(page) - await expect(successToast(page)).toBeVisible() + await expect(successToast(toast)).toBeVisible() await expect(dialog.root).toBeHidden() expect(routes.purchaseRequests).toHaveLength(1) expect(operationIdsPolled(routes.pollRequests)).toEqual( @@ -609,7 +610,8 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { }) test('does not offer the verification again once the bank has accepted it', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupTopUp(page) @@ -630,9 +632,7 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { } await expect( - page - .locator('.p-toast-message') - .getByText('Verify your payment to add your credits') + toast.withText('Verify your payment to add your credits') ).toHaveCount(0) // Shown as work in progress, not as a step the customer still owes. await expect(completeVerification(dialog)).toBeDisabled() @@ -645,7 +645,8 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { }) test('reports the outcome of a verified purchase after a reload', async ({ - page + page, + toast }) => { test.setTimeout(120_000) const routes = await setupTopUp(page) @@ -660,7 +661,7 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { routes.setOperation(SUCCEEDED) await returnToTab(page) - await expect(successToast(page)).toBeVisible({ timeout: 45_000 }) + await expect(successToast(toast)).toBeVisible({ timeout: 45_000 }) expect(routes.purchaseRequests).toHaveLength(1) expect(transports(routes.pollRequests)).not.toContain('xhr') // The step was already done, so the reload has nothing to reopen. @@ -704,7 +705,8 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { test.describe('a plan change over an operation parked by an earlier attempt', () => { test('says the earlier payment has to finish, and issues no second subscribe', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupSubscription(page) @@ -725,7 +727,7 @@ test.describe('Billing recovery on the SDK rails', { tag: '@cloud' }, () => { await confirmUpgrade(page) await expect( - page.getByText( + toast.withText( 'A payment you started earlier is still going through. It has to finish before you can choose a different plan.' ) ).toBeVisible() diff --git a/browser_tests/tests/dialogs/embeddedCheckoutSdkRail.spec.ts b/browser_tests/tests/dialogs/embeddedCheckoutSdkRail.spec.ts index 1491b419c0d..d42f4316e9c 100644 --- a/browser_tests/tests/dialogs/embeddedCheckoutSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/embeddedCheckoutSdkRail.spec.ts @@ -662,7 +662,8 @@ test.describe( test.describe('Embedded top-up bank step', { tag: '@cloud' }, () => { test('offers the in-page bank step again after a decline, and settles when it completes', async ({ - page + page, + toast }) => { const fake = await installFakeStripe(page) fake.bankSteps.push('fail') @@ -701,9 +702,7 @@ test.describe('Embedded top-up bank step', { tag: '@cloud' }, () => { .click() await expect( - page - .locator('.p-toast-message-success') - .getByText('Credits added successfully') + toast.toastSuccesses.filter({ hasText: 'Credits added successfully' }) ).toBeVisible() expect(bankSteps(fake)).toEqual([ { method: 'handleNextAction', clientSecret: BANK_STEP_SECRET }, diff --git a/browser_tests/tests/dialogs/enterpriseTierCloud.spec.ts b/browser_tests/tests/dialogs/enterpriseTierCloud.spec.ts index 293af9da36d..2a5b35265f3 100644 --- a/browser_tests/tests/dialogs/enterpriseTierCloud.spec.ts +++ b/browser_tests/tests/dialogs/enterpriseTierCloud.spec.ts @@ -242,7 +242,8 @@ test.describe('Enterprise workspace billing', { tag: '@cloud' }, () => { }) test('keeps an ended Enterprise workspace out of self-service recovery', async ({ - page + page, + toast }) => { const workspace = await setupSalesManagedWorkspace( page, @@ -283,10 +284,9 @@ test.describe('Enterprise workspace billing', { tag: '@cloud' }, () => { await expect( page.getByRole('heading', { name: 'Choose a Plan' }) ).toHaveCount(0) - await expect(page.locator('.p-toast-message-warn')).toContainText( - 'Plan inactive' - ) - await expect(page.locator('.p-toast-message-warn')).toContainText( + const warning = toast.toastWarnings + await expect(warning).toContainText('Plan inactive') + await expect(warning).toContainText( 'Contact your Comfy account manager to restore access.' ) }) diff --git a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts index b0f4a721b0a..ca4444b4198 100644 --- a/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts +++ b/browser_tests/tests/dialogs/hostedBillingDestination.spec.ts @@ -324,7 +324,8 @@ test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { }) test('tells the customer and mints no portal session when the hosted payment-methods tab is blocked', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const { portalRequests } = await mockCloudBoot(page) @@ -337,7 +338,7 @@ test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { await content.getByRole('button', { name: 'Billing & invoices' }).click() await expect( - page.getByText( + toast.withText( "Couldn't open the billing page. Allow pop-ups for this site and try again." ) ).toBeVisible() @@ -345,7 +346,8 @@ test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { }) test('tells the customer and mints no portal session when the provider portal tab is blocked', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const { portalRequests } = await mockCloudBoot(page) @@ -355,7 +357,7 @@ test.describe('Hosted billing destination (FE-2218)', { tag: '@cloud' }, () => { await content.getByRole('button', { name: 'Billing & invoices' }).click() await expect( - page.getByText( + toast.withText( "Couldn't open the billing page. Allow pop-ups for this site and try again." ) ).toBeVisible() diff --git a/browser_tests/tests/dialogs/managerDialog.spec.ts b/browser_tests/tests/dialogs/managerDialog.spec.ts index db4d581df11..1a86bd3dfdd 100644 --- a/browser_tests/tests/dialogs/managerDialog.spec.ts +++ b/browser_tests/tests/dialogs/managerDialog.spec.ts @@ -467,10 +467,10 @@ test.describe('ManagerDialog', { tag: '@ui' }, () => { ) await expect( - comfyPage.page.getByRole('alert').filter({ hasText: result.result }) + comfyPage.toast.toastErrors.filter({ hasText: result.result }) ).toBeVisible() await expect( - comfyPage.page.getByText('Failed', { exact: true }) + comfyPage.toast.panels.getByText('Failed', { exact: true }) ).toBeVisible() await expect( info.getByRole('button', { name: 'Install', exact: true }) diff --git a/browser_tests/tests/dialogs/memberRoleChange.spec.ts b/browser_tests/tests/dialogs/memberRoleChange.spec.ts index 3cd215ca93c..affc9ff3aeb 100644 --- a/browser_tests/tests/dialogs/memberRoleChange.spec.ts +++ b/browser_tests/tests/dialogs/memberRoleChange.spec.ts @@ -168,7 +168,8 @@ test.describe('Member role change (Members tab)', { tag: '@cloud' }, () => { }) test('promoting a member re-sorts the row under the creator and stays demotable', async ({ - page + page, + toast }) => { const state = await new CloudWorkspaceMockHelper(page).setup() const members = new MembersSettingsPanel(page) @@ -191,7 +192,7 @@ test.describe('Member role change (Members tab)', { tag: '@cloud' }, () => { .click() await page.getByRole('button', { name: 'Make owner' }).click() - await expect(page.getByText('Role updated')).toBeVisible() + await expect(toast.withText('Role updated')).toBeVisible() await expect(janeRow.getByText('Owner', { exact: true })).toBeVisible() await expect(emails).toHaveText([ CREATOR.email, @@ -245,7 +246,8 @@ test.describe('Member role change (Members tab)', { tag: '@cloud' }, () => { }) test('failed role change keeps the dialog open with an error toast', async ({ - page + page, + toast }) => { await new CloudWorkspaceMockHelper(page).setup() // Override the member route so PATCH fails after boot succeeds. @@ -266,7 +268,11 @@ test.describe('Member role change (Members tab)', { tag: '@cloud' }, () => { await page.getByRole('button', { name: 'Make owner' }).click() // US10 — error toast, dialog stays open, role unchanged. - await expect(page.getByText('Failed to update role')).toBeVisible() + await expect( + toast.toastErrors.filter({ + hasText: 'Failed to update role' + }) + ).toBeVisible() await expect( page.getByRole('heading', { name: 'Make Jane an owner?' }) ).toBeVisible() diff --git a/browser_tests/tests/dialogs/modelImportProgressDialog.spec.ts b/browser_tests/tests/dialogs/modelImportProgressDialog.spec.ts index 48efa216361..b7833296d1b 100644 --- a/browser_tests/tests/dialogs/modelImportProgressDialog.spec.ts +++ b/browser_tests/tests/dialogs/modelImportProgressDialog.spec.ts @@ -6,6 +6,7 @@ import { comfyExpect as expect } from '@e2e/fixtures/ComfyPage' import { modelImportProgressFixture } from '@e2e/fixtures/modelImportProgressFixture' +import { TestIds } from '@e2e/fixtures/selectors' const test = mergeTests(comfyPageFixture, modelImportProgressFixture) @@ -31,6 +32,45 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { ).toBeVisible() }) + test('keeps a panel reachable when expanded panels outgrow a short viewport', async ({ + comfyPage, + modelImportProgress + }) => { + await comfyPage.page.setViewportSize({ width: 1280, height: 360 }) + await comfyPage.assets.dispatchExport({ + task_id: 'stacked-export', + export_name: 'outputs.zip', + assets_total: 4, + assets_attempted: 1, + assets_failed: 0, + bytes_total: 1000, + bytes_processed: 250, + progress: 0.25, + status: 'running' + }) + const exportPanel = comfyPage.page + .getByTestId(TestIds.toast.panel) + .filter({ hasText: 'Exporting Assets' }) + + await modelImportProgress.expand() + await exportPanel.getByRole('button', { name: 'Expand' }).click() + await modelImportProgress.filterBy('Failed') + await expect( + modelImportProgress.job('completed-model.safetensors') + ).toBeHidden() + + const panelBounds = await modelImportProgress.root.boundingBox() + const collapseBounds = await modelImportProgress.root + .getByRole('button', { name: 'Collapse' }) + .boundingBox() + expect(panelBounds).not.toBeNull() + expect(collapseBounds).not.toBeNull() + expect( + collapseBounds!.y + collapseBounds!.height, + 'the footer must not be clipped by a squashed panel' + ).toBeLessThanOrEqual(panelBounds!.y + panelBounds!.height) + }) + test('recovers from a premature failed status once the backend silently retries and completes it (PM-1302)', async ({ comfyPage }) => { @@ -49,13 +89,14 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { }) await expect( - page.getByText('Importing Models', { exact: true }) + comfyPage.toast.panels.getByText('Importing Models', { exact: true }) ).toBeVisible() }) - const failedFooterText = page.getByText('1 download failed', { - exact: true - }) + const failedFooterText = comfyPage.toast.panels.getByText( + '1 download failed', + { exact: true } + ) await test.step('show the retryable failure reported by the backend', async () => { await comfyPage.assets.dispatchDownload({ @@ -85,12 +126,14 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { await expect(failedFooterText).toBeHidden() await expect( - page.getByText('All downloads completed', { exact: true }) + comfyPage.toast.panels.getByText('All downloads completed', { + exact: true + }) ).toBeVisible() }) const toast = page - .getByRole('status') + .getByTestId(TestIds.toast.panel) .filter({ hasText: 'All downloads completed' }) await expect(toast).toHaveScreenshot( @@ -127,11 +170,11 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { }) const toast = page - .getByRole('status') + .getByTestId(TestIds.toast.panel) .filter({ hasText: '1 download failed' }) await expect(toast).toBeVisible() await expect( - page.getByText('1 download failed', { exact: true }) + comfyPage.toast.panels.getByText('1 download failed', { exact: true }) ).toBeVisible() await test.step('dismiss the failed model import', async () => { @@ -181,7 +224,9 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { }) }) - const toast = page.getByRole('status').filter({ hasText: assetName }) + const toast = page + .getByTestId(TestIds.toast.panel) + .filter({ hasText: assetName }) await expect(toast).toBeVisible() await test.step('cancel through user-visible controls', async () => { @@ -244,7 +289,9 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { await route.fulfill({ status: 404, json: { detail: 'Task not found' } }) }) - const toast = page.getByRole('status').filter({ hasText: assetName }) + const toast = page + .getByTestId(TestIds.toast.panel) + .filter({ hasText: assetName }) await test.step('cancel a running download', async () => { await comfyPage.assets.dispatchDownload({ @@ -317,7 +364,9 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { status: 'running' }) - const toast = page.getByRole('status').filter({ hasText: assetName }) + const toast = page + .getByTestId(TestIds.toast.panel) + .filter({ hasText: assetName }) await expect(toast).toBeVisible() await toast.getByRole('button', { name: 'Expand' }).click() const cancellation = page.waitForResponse( @@ -399,7 +448,7 @@ test.describe('Model import progress toast', { tag: ['@screenshot'] }, () => { }) const toast = page - .getByRole('status') + .getByTestId(TestIds.toast.panel) .filter({ hasText: '1 download failed' }) await test.step('dismiss the model import during reconciliation', async () => { diff --git a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts index fbd917b43ee..a2b2f62e6a5 100644 --- a/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts +++ b/browser_tests/tests/dialogs/pricingTableDeepLink.spec.ts @@ -575,30 +575,27 @@ test.describe('Pricing table deep link', { tag: '@cloud' }, () => { }) test('keeps an error toast dismissable over the open dialog', async ({ - page + page, + toast }) => { await setupCloudApp(page, workspace('personal', 'owner'), []) await page.goto(`${APP_URL}/?pricing=1`) await cloudAppExpect(pricingHeading(page)).toBeVisible() await page.evaluate((detail) => { - window.app!.extensionManager.toast.add({ - severity: 'error', - summary: 'Error', - detail, - life: 30_000 + window.app!.extensionManager.toast.error('Error', { + description: detail, + duration: 30_000 }) }, SUBSCRIPTION_IN_PROGRESS_DETAIL) - const toast = page - .locator('.p-toast-message') - .filter({ hasText: SUBSCRIPTION_IN_PROGRESS_DETAIL }) - await expect(toast).toBeVisible() - // Not getByRole: an open Reka modal marks the toast container aria-hidden, - // so the close button is absent from the accessibility tree. - await toast.locator('.p-toast-close-button').click() + const errorToast = toast.toastErrors.filter({ + hasText: SUBSCRIPTION_IN_PROGRESS_DETAIL + }) + await expect(errorToast).toBeVisible() + await toast.dismiss(errorToast) - await expect(toast).toHaveCount(0) + await expect(errorToast).toHaveCount(0) await expect(pricingHeading(page)).toBeVisible() }) @@ -692,7 +689,8 @@ test.describe('Pricing table deep link', { tag: '@cloud' }, () => { }) test('restores pending checkout when retrying a timed-out operation', async ({ - page + page, + toast }) => { const subscribeRequests: Request[] = [] const operationPollRequests: Request[] = [] @@ -749,7 +747,7 @@ test.describe('Pricing table deep link', { tag: '@cloud' }, () => { await expect(backButton).toBeEnabled() await expect( - page.getByText('Subscription verification timed out', { exact: true }) + toast.withText('Subscription verification timed out') ).toBeVisible() const pollCountAfterTimeout = operationPollRequests.length @@ -1123,7 +1121,8 @@ test.describe( }) test('reconciles status and balance without polling', async ({ - page + page, + toast }) => { await page.goto(`${APP_URL}/?pricing=personal`) @@ -1139,9 +1138,9 @@ test.describe( expect((await subscribeResponse).status()).toBe(200) expect(subscribeRequests).toHaveLength(1) - const blockedPopupToast = page - .locator('.p-toast-message.p-toast-message-error') - .filter({ hasText: 'Failed to change plan' }) + const blockedPopupToast = toast.toastErrors.filter({ + hasText: 'Failed to change plan' + }) await expect(blockedPopupToast).toContainText( "Couldn't open the payment page — please try again" ) diff --git a/browser_tests/tests/dialogs/publishDialog.spec.ts-snapshots/publish-dialog-lg-chromium-linux.png b/browser_tests/tests/dialogs/publishDialog.spec.ts-snapshots/publish-dialog-lg-chromium-linux.png index ff641f442f8..bf3b57193a0 100644 Binary files a/browser_tests/tests/dialogs/publishDialog.spec.ts-snapshots/publish-dialog-lg-chromium-linux.png and b/browser_tests/tests/dialogs/publishDialog.spec.ts-snapshots/publish-dialog-lg-chromium-linux.png differ diff --git a/browser_tests/tests/dialogs/resumedSubscriptionSettle.spec.ts b/browser_tests/tests/dialogs/resumedSubscriptionSettle.spec.ts index 8b5107df7dc..d80a5bb43c0 100644 --- a/browser_tests/tests/dialogs/resumedSubscriptionSettle.spec.ts +++ b/browser_tests/tests/dialogs/resumedSubscriptionSettle.spec.ts @@ -14,6 +14,7 @@ import { createWorkspaceBillingCapabilities } from '@e2e/fixtures/data/billingCa import { createPlan } from '@e2e/fixtures/data/billingPlans' import { CLOUD_SELF_EMAIL } from '@e2e/fixtures/helpers/CloudAuthHelper' import { FeatureFlagHelper } from '@e2e/fixtures/helpers/FeatureFlagHelper' +import type { ToastHelper } from '@e2e/fixtures/helpers/ToastHelper' import { APP_URL, setupCloudApp } from '@e2e/fixtures/utils/cloudAppSetup' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { member, workspace } from '@e2e/fixtures/utils/workspaceMocks' @@ -235,7 +236,11 @@ async function reloadWhileProcessing(page: Page, routes: ResumeRoutes) { .toBeGreaterThan(pollsBeforeReload) } -async function expectResumedSubscribeSettles(page: Page, rail: Rail) { +async function expectResumedSubscribeSettles( + page: Page, + toast: ToastHelper, + rail: Rail +) { const routes = await setupResume(page, rail) await page.goto(`${APP_URL}/?pricing=creator&cycle=yearly`) await expect( @@ -252,9 +257,9 @@ async function expectResumedSubscribeSettles(page: Page, rail: Rail) { await returnToTab(page) await expect( - page - .getByRole('alert') - .filter({ hasText: 'Subscription updated successfully' }) + toast.toastSuccesses.filter({ + hasText: 'Subscription updated successfully' + }) ).toBeVisible({ timeout: 45_000 }) const statusReadsAfterSettle = routes.statusRequests.slice( statusReadsBeforeSettle @@ -271,16 +276,18 @@ async function expectResumedSubscribeSettles(page: Page, rail: Rail) { test.describe('Resumed subscription settle', { tag: '@cloud' }, () => { test('reports a subscribe that settles after a reload on the SDK rail', async ({ - page + page, + toast }) => { test.setTimeout(120_000) - await expectResumedSubscribeSettles(page, 'sdk') + await expectResumedSubscribeSettles(page, toast, 'sdk') }) test('reports a subscribe that settles after a reload on the legacy rail', async ({ - page + page, + toast }) => { test.setTimeout(120_000) - await expectResumedSubscribeSettles(page, 'legacy') + await expectResumedSubscribeSettles(page, toast, 'legacy') }) }) diff --git a/browser_tests/tests/dialogs/signInDialogAuth.spec.ts b/browser_tests/tests/dialogs/signInDialogAuth.spec.ts index 3f666b73f44..dae4d5e96ec 100644 --- a/browser_tests/tests/dialogs/signInDialogAuth.spec.ts +++ b/browser_tests/tests/dialogs/signInDialogAuth.spec.ts @@ -1,5 +1,7 @@ import { expect } from '@playwright/test' +import enMessages from '@/locales/en/main.json' with { type: 'json' } + import { SignInDialog } from '@e2e/fixtures/components/SignInDialog' import { CLOUD_SELF_EMAIL } from '@e2e/fixtures/helpers/CloudAuthHelper' import { localSignedOutFixture as test } from '@e2e/fixtures/localSignedOutFixture' @@ -50,7 +52,7 @@ test.describe('Sign In dialog — live auth', () => { await expect(dialog.root).toBeVisible() await expect( - comfyPage.page.getByText('Invalid login credentials') + comfyPage.toast.withText('Invalid login credentials') ).toBeVisible() }) @@ -156,11 +158,11 @@ test.describe('Sign In dialog — live auth', () => { await dialog.forgotPasswordLink.click() await expect( - comfyPage.page.getByText('Password reset email sent') + comfyPage.toast.withText('Password reset email sent') ).toBeVisible() }) - test('warns instead of sending when the email field is empty', async ({ + test('flags the empty email field instead of sending a reset', async ({ comfyPage }) => { const dialog = new SignInDialog(comfyPage.page) @@ -168,8 +170,12 @@ test.describe('Sign In dialog — live auth', () => { await dialog.forgotPasswordLink.click() - await expect(comfyPage.page.getByText('Enter your email')).toBeVisible() + await expect(dialog.emailInput).toHaveAttribute('aria-invalid', 'true') + await expect( + dialog.root.getByText(enMessages.validation.invalidEmail) + ).toBeVisible() await expect(dialog.emailInput).toBeFocused() + await expect(comfyPage.toast.visibleToasts).toHaveCount(0) }) test('reports a real transport failure on password reset without claiming success', async ({ @@ -188,13 +194,13 @@ test.describe('Sign In dialog — live auth', () => { await resetFailed await expect( - comfyPage.page.getByText( + comfyPage.toast.withText( 'Network error. Please check your connection and try again.' ), 'a dropped connection must surface the network error, not a silent failure' ).toBeVisible() await expect( - comfyPage.page.getByText('Password reset email sent'), + comfyPage.toast.withText('Password reset email sent'), 'a real transport failure must not show the success confirmation' ).toBeHidden() }) diff --git a/browser_tests/tests/dialogs/signInDialogAuthErrors.spec.ts b/browser_tests/tests/dialogs/signInDialogAuthErrors.spec.ts index 2fc127a2477..c70b93989a7 100644 --- a/browser_tests/tests/dialogs/signInDialogAuthErrors.spec.ts +++ b/browser_tests/tests/dialogs/signInDialogAuthErrors.spec.ts @@ -32,7 +32,7 @@ test.describe('Sign In dialog — auth error codes', () => { await expect(dialog.root).toBeVisible() await expect( - comfyPage.page.getByText('Invalid login credentials'), + comfyPage.toast.withText('Invalid login credentials'), 'the same copy as a wrong password keeps sign-in from revealing whether an email has an account' ).toBeVisible() }) @@ -52,7 +52,7 @@ test.describe('Sign In dialog — auth error codes', () => { await dialog.signInButton.click() await expect( - comfyPage.page.getByText( + comfyPage.toast.withText( 'This account has been disabled. Please contact support.' ) ).toBeVisible() @@ -75,7 +75,7 @@ test.describe('Sign In dialog — auth error codes', () => { await dialog.signInButton.click() await expect( - comfyPage.page.getByText( + comfyPage.toast.withText( 'Too many login attempts. Please wait a moment and try again.' ) ).toBeVisible() @@ -99,7 +99,7 @@ test.describe('Sign In dialog — auth error codes', () => { await dialog.signUpButton.click() await expect( - comfyPage.page.getByText( + comfyPage.toast.withText( enMessages.auth.errors['auth/email-already-in-use'] ) ).toBeVisible() @@ -120,7 +120,7 @@ test.describe('Sign In dialog — auth error codes', () => { await dialog.signInButton.click() await expect( - comfyPage.page.getByText( + comfyPage.toast.withText( 'Network error. Please check your connection and try again.' ) ).toBeVisible() diff --git a/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts b/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts index ea712dbd297..02b8aed0285 100644 --- a/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/subscriptionLifecycleSdkRail.spec.ts @@ -450,7 +450,8 @@ test.describe( * reservation tells the customer why and asks neither transport. */ test('mints no portal session when the browser refuses the tab', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const routes = await mockCloudBoot(page, { railOnFeatures: true }) @@ -461,7 +462,7 @@ test.describe( await panel.getByRole('button', { name: 'Billing & invoices' }).click() await expect( - page.getByText( + toast.withText( "Couldn't open the billing page. Allow pop-ups for this site and try again." ) ).toBeVisible() diff --git a/browser_tests/tests/dialogs/subscriptionSdkRailOutcomes.spec.ts b/browser_tests/tests/dialogs/subscriptionSdkRailOutcomes.spec.ts index f27e2c6eb35..eda87eb7256 100644 --- a/browser_tests/tests/dialogs/subscriptionSdkRailOutcomes.spec.ts +++ b/browser_tests/tests/dialogs/subscriptionSdkRailOutcomes.spec.ts @@ -344,7 +344,8 @@ test.describe('Subscription rail outcomes', { tag: '@cloud' }, () => { }) test('opens the hosted payment page once for a parked subscribe, and settles when the operation succeeds', async ({ - page + page, + toast }) => { let operation: BillingOpStatusResponse = PARKED_OPERATION const routes = await setupRail(page, { @@ -373,7 +374,7 @@ test.describe('Subscription rail outcomes', { tag: '@cloud' }, () => { expect(routes.subscribeRequests).toHaveLength(1) expect(transport(routes.subscribeRequests[0])).toBe('fetch') await expect( - page.getByText('Verify your payment to finish setting up your workspace') + toast.withText('Verify your payment to finish setting up your workspace') ).toBeVisible() // A poll that still reports the same parked step must not offer it again. @@ -395,7 +396,8 @@ test.describe('Subscription rail outcomes', { tag: '@cloud' }, () => { }) test('shows the progress toast while a subscribe processes, and clears it when it settles', async ({ - page + page, + toast }) => { let operation: BillingOpStatusResponse = PROCESSING_OPERATION await setupRail(page, { @@ -419,7 +421,7 @@ test.describe('Subscription rail outcomes', { tag: '@cloud' }, () => { ).toBeVisible() await page.getByRole('button', { name: 'Confirm upgrade' }).click() - const progressToast = page.getByText( + const progressToast = toast.withText( 'Processing payment — setting up your workspace...' ) await expect(progressToast).toBeVisible() diff --git a/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts index 5c2085bd897..c2612dd5393 100644 --- a/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts +++ b/browser_tests/tests/dialogs/topUpNoPaymentMethod.spec.ts @@ -48,9 +48,9 @@ test.describe('Top-up without a saved payment method', () => { await topUpDialog.root.getByRole('button', { name: 'Pay $50.00' }).click() await expect( - page - .locator('.p-toast-message.p-toast-message-error') - .getByText(/Add one via Settings → Plan & Credits → Manage billing/) + comfyPage.toast.toastErrors.filter({ + hasText: /Add one via Settings → Plan & Credits → Manage billing/ + }) ).toBeVisible() }) }) diff --git a/browser_tests/tests/dialogs/topUpSdkRail.spec.ts b/browser_tests/tests/dialogs/topUpSdkRail.spec.ts index 2dbda778a9e..4cafd44a86f 100644 --- a/browser_tests/tests/dialogs/topUpSdkRail.spec.ts +++ b/browser_tests/tests/dialogs/topUpSdkRail.spec.ts @@ -195,7 +195,8 @@ test.describe('Top-up rail (FE-2475)', { tag: '@cloud' }, () => { * that has to be rewritten when it lands. */ test('surfaces a closed backend gate as a failed purchase, with no legacy retry', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const routes = await setupTopUp(page) @@ -206,8 +207,6 @@ test.describe('Top-up rail (FE-2475)', { tag: '@cloud' }, () => { await expect.poll(() => routes.purchaseRequests.length).toBe(1) expect(transport(routes.purchaseRequests[0])).toBe('fetch') - await expect( - page.locator('.p-toast-message.p-toast-message-error') - ).toBeVisible() + await expect(toast.toastErrors).toBeVisible() }) }) diff --git a/browser_tests/tests/dialogs/topUpSdkRailOutcomes.spec.ts b/browser_tests/tests/dialogs/topUpSdkRailOutcomes.spec.ts index caca6406f3d..5c160f5b5cc 100644 --- a/browser_tests/tests/dialogs/topUpSdkRailOutcomes.spec.ts +++ b/browser_tests/tests/dialogs/topUpSdkRailOutcomes.spec.ts @@ -206,12 +206,10 @@ async function openConfirmStep(page: Page) { const payButton = (dialog: TopUpCreditsDialog) => dialog.root.getByRole('button', { name: 'Pay $50.00' }) -const successToast = (page: Page) => - page.locator('.p-toast-message.p-toast-message-success') - test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { test('sends a purchase with no saved card to the hosted page and settles it on return', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupTopUp(page, { @@ -243,7 +241,7 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { await returnToTab(page) await expect( - successToast(page).getByText('Credits added successfully!') + toast.toastSuccesses.filter({ hasText: 'Credits added successfully!' }) ).toBeVisible() await expect(dialog.root).toBeHidden() expect(routes.balanceRequests.length).toBeGreaterThan( @@ -254,7 +252,8 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { }) test('fails a declined card the way the legacy rail does, without a retry', async ({ - page + page, + toast }) => { test.setTimeout(60_000) const routes = await setupTopUp(page, { @@ -273,12 +272,10 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { await payButton(dialog).click() await expect( - page - .locator('.p-toast-message.p-toast-message-error') - .getByText('Purchase Failed') + toast.toastErrors.filter({ hasText: 'Purchase Failed' }) ).toBeVisible() await expect(payButton(dialog)).toBeEnabled() - await expect(successToast(page)).toHaveCount(0) + await expect(toast.toastSuccesses).toHaveCount(0) // A settled purchase re-reads the balance; a declined one must not. expect(routes.balanceRequests).toHaveLength( routes.balanceReadsAtPurchase[0] @@ -337,7 +334,8 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { }) test('keeps a purchase started in one workspace out of another', async ({ - page + page, + toast }) => { test.setTimeout(150_000) const personal = workspace('personal', 'owner') @@ -402,13 +400,13 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { await returnToTab(page) expect(routes.pollRequests).toHaveLength(pollsBeforeTeam) - await expect(successToast(page)).toHaveCount(0) + await expect(toast.toastSuccesses).toHaveCount(0) expect(await operationPointerWorkspaces(page)).toEqual([personal.id]) await topUp.root.getByRole('button', { name: 'Close' }).click() await switchWorkspace(page, personal.name) await expect( - successToast(page).getByText('Credits added successfully') + toast.toastSuccesses.filter({ hasText: 'Credits added successfully' }) ).toBeVisible({ timeout: 45_000 }) expect(routes.pollRequests.length).toBeGreaterThan(pollsBeforeTeam) await expect.poll(() => operationPointerWorkspaces(page)).toEqual([]) @@ -416,7 +414,8 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { }) test('shows a failed bank verification with its reason and does not offer it again', async ({ - page + page, + toast }) => { test.setTimeout(90_000) const routes = await setupTopUp(page, { @@ -460,7 +459,7 @@ test.describe('Top-up rail outcomes', { tag: '@cloud' }, () => { await expect( dialog.root.getByRole('button', { name: 'Complete verification' }) ).toHaveCount(0) - await expect(successToast(page)).toHaveCount(0) + await expect(toast.toastSuccesses).toHaveCount(0) expect(routes.balanceRequests).toHaveLength(balanceReadsBeforeFailure) expect(await routes.hostedOpens()).toEqual([HOSTED_URL]) expect(routes.purchaseRequests).toHaveLength(1) diff --git a/browser_tests/tests/load3d/load3d.spec.ts b/browser_tests/tests/load3d/load3d.spec.ts index 12de83412b1..b26549b38f1 100644 --- a/browser_tests/tests/load3d/load3d.spec.ts +++ b/browser_tests/tests/load3d/load3d.spec.ts @@ -311,9 +311,9 @@ test.describe('Load3D silent 404 on missing output model', () => { await comfyPage.workflow.loadWorkflow('3d/load3d_missing_model') await responsePromise - await expect( - comfyPage.toast.visibleToasts.filter({ hasText: 'Error loading model' }) - ).toHaveCount(0) + await expect(comfyPage.toast.withText('Error loading model')).toHaveCount( + 0 + ) } ) @@ -331,13 +331,9 @@ test.describe('Load3D silent 404 on missing output model', () => { await responsePromise await expect - .poll( - () => - comfyPage.toast.visibleToasts - .filter({ hasText: 'Error loading model' }) - .count(), - { timeout: 10000 } - ) + .poll(() => comfyPage.toast.withText('Error loading model').count(), { + timeout: 10000 + }) .toBeGreaterThan(0) } ) @@ -366,9 +362,7 @@ test.describe('Load3D initialization failure', () => { await comfyPage.workflow.loadWorkflow('3d/load3d_node') await expect( - comfyPage.toast.visibleToasts.filter({ - hasText: 'Failed to initialize 3D Viewer' - }) + comfyPage.toast.withText('Failed to initialize 3D Viewer') ).not.toHaveCount(0) }) }) diff --git a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-unknown-color-palette-chromium-linux.png b/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-unknown-color-palette-chromium-linux.png index 1b3538d61ba..dbbc08feddd 100644 Binary files a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-unknown-color-palette-chromium-linux.png and b/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-unknown-color-palette-chromium-linux.png differ diff --git a/browser_tests/tests/nodeGhostPlacement.spec.ts b/browser_tests/tests/nodeGhostPlacement.spec.ts index 0ebb95024ea..0a6033f043e 100644 --- a/browser_tests/tests/nodeGhostPlacement.spec.ts +++ b/browser_tests/tests/nodeGhostPlacement.spec.ts @@ -221,7 +221,7 @@ for (const mode of ['litegraph', 'vue'] as const) { await comfyPage.command.executeCommand('Comfy.PublishSubgraph', { name: blueprintName }) - await expect(comfyPage.visibleToasts).toHaveCount(1, { + await expect(comfyPage.toast.visibleToasts).toHaveCount(1, { timeout: 5000 }) await comfyPage.toast.closeToasts(1) diff --git a/browser_tests/tests/nodeReplacement.spec.ts b/browser_tests/tests/nodeReplacement.spec.ts index 7a752de7f04..fbaf00b8d16 100644 --- a/browser_tests/tests/nodeReplacement.spec.ts +++ b/browser_tests/tests/nodeReplacement.spec.ts @@ -187,7 +187,7 @@ test.describe('Node replacement', { tag: ['@node', '@ui'] }, () => { .getByRole('button', { name: /replace node/i }) .click() - await expect(comfyPage.visibleToasts.first()).toContainText( + await expect(comfyPage.toast.visibleToasts.first()).toContainText( /replaced|swapped/i ) }) diff --git a/browser_tests/tests/nodeSearchBoxV2Extended.spec.ts b/browser_tests/tests/nodeSearchBoxV2Extended.spec.ts index 0630e42803d..8448030381c 100644 --- a/browser_tests/tests/nodeSearchBoxV2Extended.spec.ts +++ b/browser_tests/tests/nodeSearchBoxV2Extended.spec.ts @@ -298,7 +298,9 @@ test.describe('Node search box V2 extended', { tag: '@node' }, () => { await comfyPage.command.executeCommand('Comfy.PublishSubgraph', { name: blueprintName }) - await expect(comfyPage.visibleToasts).toHaveCount(1, { timeout: 5000 }) + await expect(comfyPage.toast.visibleToasts).toHaveCount(1, { + timeout: 5000 + }) await comfyPage.toast.closeToasts(1) const { searchBoxV2 } = comfyPage diff --git a/browser_tests/tests/sidebar/assets.spec.ts b/browser_tests/tests/sidebar/assets.spec.ts index 9cf71e960c1..c24b5a9f724 100644 --- a/browser_tests/tests/sidebar/assets.spec.ts +++ b/browser_tests/tests/sidebar/assets.spec.ts @@ -716,7 +716,7 @@ test.describe('Assets sidebar - context menu', () => { const cards = tab.assetCards await expect.poll(() => cards.count()).toBeGreaterThanOrEqual(2) - await tab.dismissToasts() + await comfyPage.toast.closeToasts() // useKeyModifier('Control') needs keyboard events, not click modifiers. await cards.first().click() @@ -1056,8 +1056,7 @@ test.describe('Assets sidebar - delete confirmation', () => { await expect(dialog).toBeHidden() await expect(tab.assetCards).toHaveCount(initialCount - 1) - const successToast = comfyPage.page.locator('.p-toast-message-success') - await expect(successToast).toBeVisible() + await expect(comfyPage.toast.toastSuccesses).toBeVisible() }) test('Cancelling delete preserves asset', async ({ comfyPage }) => { diff --git a/browser_tests/tests/sidebar/sidebarSplitterWidth.spec.ts b/browser_tests/tests/sidebar/sidebarSplitterWidth.spec.ts index 7275978c1e5..28b4dfe4532 100644 --- a/browser_tests/tests/sidebar/sidebarSplitterWidth.spec.ts +++ b/browser_tests/tests/sidebar/sidebarSplitterWidth.spec.ts @@ -16,21 +16,12 @@ test.describe('Sidebar splitter width independence', () => { } }) - async function dismissToasts(comfyPage: ComfyPage) { - const buttons = await comfyPage.page.locator('.p-toast-close-button').all() - for (const btn of buttons) { - await btn.click({ timeout: 2000 }).catch(() => {}) - } - // Brief wait for animations - await comfyPage.nextFrame() - } - async function openSidebarAt( comfyPage: ComfyPage, location: 'left' | 'right' ) { await comfyPage.settings.setSetting('Comfy.Sidebar.Location', location) - await dismissToasts(comfyPage) + await comfyPage.toast.closeToasts() await comfyPage.menu.nodeLibraryTab.open() } diff --git a/browser_tests/tests/subgraph/subgraphSearch.spec.ts b/browser_tests/tests/subgraph/subgraphSearch.spec.ts index dc7635797bb..eab49612bd4 100644 --- a/browser_tests/tests/subgraph/subgraphSearch.spec.ts +++ b/browser_tests/tests/subgraph/subgraphSearch.spec.ts @@ -22,7 +22,7 @@ async function exitSubgraphAndPublish( name: blueprintName }) - await expect(comfyPage.visibleToasts).toHaveCount(1) + await expect(comfyPage.toast.visibleToasts).toHaveCount(1) await comfyPage.toast.closeToasts(1) } diff --git a/browser_tests/tests/templates.spec.ts b/browser_tests/tests/templates.spec.ts index 16e2ed88333..0af1474ace9 100644 --- a/browser_tests/tests/templates.spec.ts +++ b/browser_tests/tests/templates.spec.ts @@ -281,7 +281,7 @@ test.describe('Templates', { tag: ['@slow', '@workflow'] }, () => { await expect(filterBar).toHaveScreenshot( 'template-filter-bar-select-components.png', { - mask: [comfyPage.page.locator('.p-toast')] + mask: [comfyPage.toast.visibleToasts] } ) } diff --git a/browser_tests/tests/toastNotifications.spec.ts b/browser_tests/tests/toastNotifications.spec.ts index 23f1483ba1b..94176ef06ba 100644 --- a/browser_tests/tests/toastNotifications.spec.ts +++ b/browser_tests/tests/toastNotifications.spec.ts @@ -2,30 +2,19 @@ import { comfyPageFixture as test, comfyExpect as expect } from '@e2e/fixtures/ComfyPage' +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' test.describe('Toast Notifications', { tag: '@ui' }, () => { - async function triggerErrorToast(comfyPage: { - page: { evaluate: (fn: () => void) => Promise } - nextFrame: () => Promise - }) { + async function triggerErrorToast(comfyPage: ComfyPage) { await comfyPage.page.evaluate(() => { - window.app!.extensionManager.toast.add({ - severity: 'error', - summary: 'Error', - detail: 'Test execution error', - life: 30000 + window.app!.extensionManager.toast.error('Error', { + description: 'Test execution error', + duration: 30000 }) }) - await comfyPage.nextFrame() } - test('Error toast appears when triggered', async ({ comfyPage }) => { - await triggerErrorToast(comfyPage) - - await expect(comfyPage.toast.visibleToasts.first()).toBeVisible() - }) - - test('Graph toast fallback respects the workspace inset', async ({ + test('Toasts outside the graph fall back to the workspace inset', async ({ comfyPage }) => { const workspaceInset = 240 @@ -45,9 +34,7 @@ test.describe('Toast Notifications', { tag: '@ui' }, () => { await triggerErrorToast(comfyPage) - const graphToast = comfyPage.page - .locator('.graph-toast .p-toast-message') - .filter({ hasText: 'Test execution error' }) + const graphToast = comfyPage.toast.withText('Test execution error') await expect(graphToast).toBeVisible() const bounds = await graphToast.boundingBox() @@ -59,43 +46,57 @@ test.describe('Toast Notifications', { tag: '@ui' }, () => { ) }) - test('Toast shows correct error severity class', async ({ comfyPage }) => { - await triggerErrorToast(comfyPage) - - const errorToast = comfyPage.page.locator( - '.p-toast-message.p-toast-message-error' - ) - await expect(errorToast.first()).toBeVisible() - }) + test('Toasts stay clear of the open properties panel', async ({ + comfyPage + }) => { + const { propertiesPanel } = comfyPage.menu + await propertiesPanel.toggleButton.click() + await expect(propertiesPanel.root).toBeVisible() - test('Toast can be dismissed via close button', async ({ comfyPage }) => { await triggerErrorToast(comfyPage) - await expect(comfyPage.toast.visibleToasts.first()).toBeVisible() - - const closeButton = comfyPage.page.locator('.p-toast-close-button').first() - await closeButton.click() + const graphToast = comfyPage.toast.withText('Test execution error') + await expect(graphToast).toBeVisible() - await expect(comfyPage.toast.visibleToasts).toHaveCount(0) + const toastBounds = await graphToast.boundingBox() + const panelBounds = await propertiesPanel.root.boundingBox() + expect(toastBounds).not.toBeNull() + expect(panelBounds).not.toBeNull() + expect(toastBounds!.x + toastBounds!.width).toBeLessThanOrEqual( + panelBounds!.x + ) }) - test('All toasts cleared via closeToasts helper', async ({ comfyPage }) => { + test('Toast can be dismissed via close button', async ({ comfyPage }) => { await triggerErrorToast(comfyPage) + const errorToast = comfyPage.toast.toastErrors.filter({ + hasText: 'Test execution error' + }) + await expect(errorToast).toBeVisible() - await expect(comfyPage.toast.visibleToasts.first()).toBeVisible() - - await comfyPage.toast.closeToasts() + await comfyPage.toast.dismiss(errorToast) await expect(comfyPage.toast.visibleToasts).toHaveCount(0) }) - test('Toast error count is accurate', async ({ comfyPage }) => { - await triggerErrorToast(comfyPage) + test('Legacy extension toast messages still render', async ({ + comfyPage + }) => { + await comfyPage.page.evaluate(() => { + window.app!.extensionManager.toast.add({ + severity: 'warn', + summary: 'Legacy summary', + detail: 'Legacy detail', + life: 30000 + }) + window.app!.extensionManager.toast.addAlert('Legacy alert') + }) await expect( - comfyPage.page.locator('.p-toast-message.p-toast-message-error').first() + comfyPage.toast.toastWarnings.filter({ hasText: 'Legacy detail' }) + ).toBeVisible() + await expect( + comfyPage.toast.toastWarnings.filter({ hasText: 'Legacy alert' }) ).toBeVisible() - - await expect(comfyPage.toast.toastErrors).not.toHaveCount(0) }) }) diff --git a/browser_tests/tests/versionMismatchWarnings.spec.ts b/browser_tests/tests/versionMismatchWarnings.spec.ts index 0e36431adf4..f455ea3c9ce 100644 --- a/browser_tests/tests/versionMismatchWarnings.spec.ts +++ b/browser_tests/tests/versionMismatchWarnings.spec.ts @@ -64,7 +64,7 @@ comfyPageFixture.describe('Version Mismatch Warnings', { tag: '@slow' }, () => { }) => { // Expect a warning toast to be shown await expect( - comfyPage.page.getByText('Version Compatibility Warning') + comfyPage.toast.withText('Version Compatibility Warning') ).toBeVisible() }) @@ -73,7 +73,7 @@ comfyPageFixture.describe('Version Mismatch Warnings', { tag: '@slow' }, () => { async ({ comfyPage }) => { // Expect no warning toast to be shown await expect( - comfyPage.page.getByText('Version Compatibility Warning') + comfyPage.toast.withText('Version Compatibility Warning') ).toBeHidden() } ) @@ -84,12 +84,9 @@ comfyPageFixture.describe('Version Mismatch Warnings', { tag: '@slow' }, () => { test.setTimeout(30_000) // Locate the warning toast and dismiss it - const warningToast = comfyPage.page.locator('.p-toast-message').filter({ - hasText: 'Version Compatibility' - }) - await warningToast.waitFor({ state: 'visible' }) - const dismissButton = warningToast.getByRole('button', { name: 'Close' }) - await dismissButton.click() + const warningToast = comfyPage.toast.withText('Version Compatibility') + await expect(warningToast).toBeVisible() + await comfyPage.toast.dismiss(warningToast) // Wait for the dismissed state to be persisted await comfyPage.page.waitForFunction( @@ -101,7 +98,7 @@ comfyPageFixture.describe('Version Mismatch Warnings', { tag: '@slow' }, () => { // The same warning from same versions should not be shown to the user again await expect( - comfyPage.page.getByText('Version Compatibility Warning') + comfyPage.toast.withText('Version Compatibility Warning') ).toBeHidden() }) }) diff --git a/browser_tests/tests/vueNodes/widgets/load/uploadWidgets.spec.ts b/browser_tests/tests/vueNodes/widgets/load/uploadWidgets.spec.ts index 7d6615add11..317f41a4067 100644 --- a/browser_tests/tests/vueNodes/widgets/load/uploadWidgets.spec.ts +++ b/browser_tests/tests/vueNodes/widgets/load/uploadWidgets.spec.ts @@ -100,10 +100,9 @@ test.describe('Vue Upload Widgets', { tag: '@vue-nodes' }, () => { await comfyPage.nodeOps.getNodeRefsByType('LoadVideo') expect(loadVideoNode, 'Load Video node was added').toBeDefined() const videoWidget = await loadVideoNode.getWidgetByName('file') - const rejectionToasts = comfyPage.page.getByText( - enMessages.g.videoFilenameExtensionRequired, - { exact: true } - ) + const rejectionToasts = comfyPage.toast.toastWarnings.filter({ + hasText: enMessages.g.videoFilenameExtensionRequired + }) let uploadRequests = 0 await comfyPage.page.route('**/upload/image', async (route) => { uploadRequests += 1 diff --git a/browser_tests/tests/webcamCapture.spec.ts b/browser_tests/tests/webcamCapture.spec.ts index 69eaa824b7e..c26bb425708 100644 --- a/browser_tests/tests/webcamCapture.spec.ts +++ b/browser_tests/tests/webcamCapture.spec.ts @@ -318,9 +318,7 @@ test.describe( await comfyPage.runButton.click() await expect( - comfyPage.toast.visibleToasts - .filter({ hasText: 'Error uploading camera image' }) - .first() + comfyPage.toast.withText('Error uploading camera image').first() ).toBeVisible() }) @@ -345,9 +343,7 @@ test.describe( await comfyPage.runButton.click() await expect( - comfyPage.toast.visibleToasts - .filter({ hasText: 'No webcam image captured' }) - .first() + comfyPage.toast.withText('No webcam image captured').first() ).toBeVisible() expect(uploadCalled).toBe(false) }) diff --git a/docs/testing/vitest-patterns.md b/docs/testing/vitest-patterns.md index c40230d5e3b..33b9488662d 100644 --- a/docs/testing/vitest-patterns.md +++ b/docs/testing/vitest-patterns.md @@ -50,11 +50,17 @@ Read an action from its store where it is used instead of caching it in a suite-level `let` assigned by `beforeEach`: ```typescript -vi.mocked(useToastStore().addAlert).mockImplementation(() => {}) -expect(useToastStore().addAlert).toHaveBeenCalledWith('Upload failed') +expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error', title: 'Upload failed' }) +]) +expect(useToast().error).toHaveBeenCalledWith('Upload failed') ``` -Use a test-local `const store = useToastStore()` when several accesses become +The global testing Pinia uses `stubActions: false`, so store actions run for +real and are already spies. Prefer asserting on store state; do not mock the +action. + +Use a test-local `const store = useToast()` when several accesses become hard to read. Keep shared variables when they own a per-test resource, a reactive fixture, or a value that teardown must restore. @@ -121,12 +127,12 @@ Real example: [`src/components/searchbox/v2/__test__/testUtils.ts`](../../src/co With empty messages, `t('foo.bar')` returns `'foo.bar'` (the key). Assert against the key directly — no need to mock `t`: ```typescript -expect(toastSpy).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'mediaAsset.selection.exportStarted' }) +expect(useToast().success).toHaveBeenCalledWith( + 'mediaAsset.selection.exportStarted' ) ``` -For pluralization / interpolation arguments, spy on the consumer (e.g. the toast `add` fn) and inspect the captured payload, rather than spying on `t` itself. +For pluralization / interpolation arguments, inspect the consumer's captured arguments (e.g. `useToast().success`) rather than spying on `t` itself. ## Mock Patterns diff --git a/packages/account-core/src/firebaseAuthError.test.ts b/packages/account-core/src/firebaseAuthError.test.ts index 935fd7b2668..d87a410b2b5 100644 --- a/packages/account-core/src/firebaseAuthError.test.ts +++ b/packages/account-core/src/firebaseAuthError.test.ts @@ -87,7 +87,7 @@ describe('severityForAuthError', () => { code: 'auth/cancelled-popup-request' }), 'the user closing a window is not an application error' - ).toBe('warn') + ).toBe('warning') for (const classification of [ { kind: 'unauthorized-domain', code: 'auth/unauthorized-domain' }, { kind: 'signup-blocked', code: 'auth/internal-error' }, diff --git a/packages/account-core/src/firebaseAuthError.ts b/packages/account-core/src/firebaseAuthError.ts index c96e97667aa..dbe8b53b492 100644 --- a/packages/account-core/src/firebaseAuthError.ts +++ b/packages/account-core/src/firebaseAuthError.ts @@ -70,7 +70,7 @@ export function classifyAuthError(error: unknown): AuthErrorClassification { return { kind: 'auth', code: error.code } } -export type AuthToastSeverity = 'error' | 'warn' +export type AuthToastSeverity = 'error' | 'warning' /** * The cloud app's toast-severity policy for classified auth failures: a @@ -80,7 +80,7 @@ export type AuthToastSeverity = 'error' | 'warn' export function severityForAuthError( classification: AuthErrorClassification ): AuthToastSeverity { - return classification.kind === 'popup-dismissed' ? 'warn' : 'error' + return classification.kind === 'popup-dismissed' ? 'warning' : 'error' } /** diff --git a/packages/design-system/src/css/style.css b/packages/design-system/src/css/style.css index 5c74a6e15a9..fc28786282f 100644 --- a/packages/design-system/src/css/style.css +++ b/packages/design-system/src/css/style.css @@ -1902,15 +1902,10 @@ audio.comfy-audio.empty-audio-widget { body-portaled overlays and makes them unclickable. PrimeVue's own Dialog sets pointer-events inline, but Select / ColorPicker / Popover / Autocomplete overlays do not, so they need to opt in here. - - Toasts opt in per message rather than on the `.p-toast` container: the - container spans the whole stack including the margin between messages, so - enabling it there would swallow scrim clicks in empty space beside a toast. */ .p-select-overlay, .p-colorpicker-panel, .p-popover, -.p-autocomplete-overlay, -.p-toast-message { +.p-autocomplete-overlay { pointer-events: auto; } diff --git a/scripts/primevue-import-allowlist.json b/scripts/primevue-import-allowlist.json index 44a42ad3a5d..eb8ce894b5d 100644 --- a/scripts/primevue-import-allowlist.json +++ b/scripts/primevue-import-allowlist.json @@ -12,15 +12,8 @@ "src/components/dialog/GlobalDialog.test.ts", "src/components/dialog/GlobalDialog.vue", "src/components/dialog/bodyPointerEventsRestore.test.ts", - "src/components/dialog/content/ErrorDialogContent.vue", - "src/components/dialog/content/TopUpCreditsDialogContentLegacy.test.ts", - "src/components/dialog/content/TopUpCreditsDialogContentLegacy.vue", "src/components/dialog/content/setting/SettingItem.test.ts", "src/components/dialog/content/setting/UsageLogsTable.test.ts", - "src/components/dialog/content/signin/SignInForm.test.ts", - "src/components/dialog/content/signin/SignInForm.vue", - "src/components/dialog/content/subscription/CancelSubscriptionDialogContent.test.ts", - "src/components/dialog/content/subscription/CancelSubscriptionDialogContent.vue", "src/components/graph/GraphCanvasMenu.vue", "src/components/graph/SelectionToolbox.test.ts", "src/components/graph/selectionToolbox/BypassButton.test.ts", @@ -29,8 +22,6 @@ "src/components/graph/selectionToolbox/InfoButton.test.ts", "src/components/graph/widgets/TextPreviewWidget.test.ts", "src/components/graph/widgets/TextPreviewWidget.vue", - "src/components/helpcenter/HelpCenterMenuContent.test.ts", - "src/components/helpcenter/HelpCenterMenuContent.vue", "src/components/node/NodePreview.test.ts", "src/components/rightSidePanel/errors/ErrorGroupList.test.ts", "src/components/rightSidePanel/errors/ErrorNodeCard.test.ts", @@ -41,21 +32,10 @@ "src/components/searchbox/NodeSearchBoxPopover.vue", "src/components/sidebar/SideToolbar.test.ts", "src/components/sidebar/SidebarIcon.test.ts", - "src/components/sidebar/tabs/AssetsSidebarTab.test.ts", - "src/components/sidebar/tabs/AssetsSidebarTab.vue", - "src/components/toast/GlobalToast.test.ts", - "src/components/toast/GlobalToast.vue", - "src/components/toast/RerouteMigrationToast.vue", "src/components/topbar/CurrentUserButton.vue", "src/components/topbar/CurrentUserPopoverLegacy.vue", "src/components/topbar/TopbarBadge.test.ts", - "src/composables/useCopyToClipboard.test.ts", - "src/composables/useCopyToClipboard.ts", - "src/composables/useReconnectingNotification.test.ts", - "src/composables/useReconnectingNotification.ts", "src/main.ts", - "src/platform/assets/composables/useMediaAssetActions.test.ts", - "src/platform/assets/composables/useMediaAssetActions.ts", "src/platform/cloud/onboarding/CloudSubscriptionRedirectView.vue", "src/platform/cloud/onboarding/skeletons/CloudLoginViewSkeleton.vue", "src/platform/cloud/onboarding/skeletons/CloudSurveyViewSkeleton.vue", @@ -63,50 +43,10 @@ "src/platform/missingModel/components/MissingModelCard.test.ts", "src/platform/nodeReplacement/components/SwapNodeGroupRow.test.ts", "src/platform/nodeReplacement/components/SwapNodesCard.test.ts", - "src/platform/updates/common/toastStore.ts", "src/platform/updates/components/WhatsNewPopup.test.ts", "src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.test.ts", - "src/platform/workflow/persistence/composables/useWorkflowPersistenceV2.ts", - "src/platform/workflow/sharing/components/ShareWorkflowDialogContent.test.ts", - "src/platform/workflow/sharing/components/ShareWorkflowDialogContent.vue", - "src/platform/workflow/sharing/components/profile/ComfyHubCreateProfileForm.vue", - "src/platform/workflow/sharing/components/publish/ComfyHubPublishDialog.test.ts", - "src/platform/workflow/sharing/components/publish/ComfyHubPublishDialog.vue", - "src/platform/workflow/sharing/composables/useSharedWorkflowUrlLoader.test.ts", - "src/platform/workflow/sharing/composables/useSharedWorkflowUrlLoader.ts", - "src/platform/workflow/templates/composables/useTemplateUrlLoader.test.ts", - "src/platform/workflow/templates/composables/useTemplateUrlLoader.ts", "src/platform/workspace/components/CurrentUserPopoverWorkspace.test.ts", "src/platform/workspace/components/CurrentUserPopoverWorkspace.vue", - "src/platform/workspace/components/InviteMembersForm.test.ts", - "src/platform/workspace/components/InviteMembersForm.vue", - "src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts", - "src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts", - "src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.vue", - "src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.test.ts", - "src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.vue", - "src/platform/workspace/components/dialogs/CreateWorkspaceDialogContent.vue", - "src/platform/workspace/components/dialogs/DeleteWorkspaceDialogContent.vue", - "src/platform/workspace/components/dialogs/DowngradeRemoveMembersDialogContent.test.ts", - "src/platform/workspace/components/dialogs/DowngradeRemoveMembersDialogContent.vue", - "src/platform/workspace/components/dialogs/EditWorkspaceDialogContent.vue", - "src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts", - "src/platform/workspace/components/dialogs/LeaveWorkspaceDialogContent.vue", - "src/platform/workspace/components/dialogs/RemoveMemberDialogContent.vue", - "src/platform/workspace/components/dialogs/RevokeInviteDialogContent.vue", - "src/platform/workspace/components/dialogs/TeamWorkspacesDialogContent.test.ts", - "src/platform/workspace/components/dialogs/TeamWorkspacesDialogContent.vue", - "src/platform/workspace/components/toasts/InviteAcceptedToast.vue", - "src/platform/workspace/composables/useInviteUrlLoader.test.ts", - "src/platform/workspace/composables/useInviteUrlLoader.ts", - "src/platform/workspace/composables/useMembersPanel.test.ts", - "src/platform/workspace/composables/useMembersPanel.ts", - "src/platform/workspace/composables/useResubscribe.test.ts", - "src/platform/workspace/composables/useResubscribe.ts", - "src/platform/workspace/composables/useSubscriptionCheckout.test.ts", - "src/platform/workspace/composables/useSubscriptionCheckout.ts", - "src/platform/workspace/stores/billingOperationStore.ts", - "src/renderer/extensions/linearMode/DropZone.test.ts", "src/renderer/extensions/vueNodes/VideoPreview.vue", "src/renderer/extensions/vueNodes/components/WidgetGrid.vue", "src/renderer/extensions/vueNodes/composables/processedWidgetRenderModel.ts", @@ -117,11 +57,8 @@ "src/renderer/extensions/vueNodes/widgets/components/WidgetRecordAudio.vue", "src/renderer/extensions/vueNodes/widgets/components/WidgetSelect.asset-mode.test.ts", "src/renderer/extensions/vueNodes/widgets/components/WidgetSelectDropdown.test.ts", - "src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.test.ts", - "src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue", "src/renderer/extensions/vueNodes/widgets/components/form/FormSelectButton.test.ts", "src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.test.ts", - "src/services/dialogService.errorCatalog.test.ts", "src/stores/dialogStore.ts", "src/workbench/extensions/manager/components/manager/PackVersionBadge.test.ts", "src/workbench/extensions/manager/components/manager/PackVersionSelectorPopover.test.ts", diff --git a/src/App.vue b/src/App.vue index dbb9d9220f9..bd850482007 100644 --- a/src/App.vue +++ b/src/App.vue @@ -83,17 +83,11 @@ onMounted(() => { window.addEventListener('vite:preloadError', (event) => { event.preventDefault() reportPreloadError(event.payload) - // Disabled: Third-party custom node extensions frequently trigger this toast + // No toast: third-party custom node extensions frequently trigger this // (e.g., bare "vue" imports, wrong relative paths to scripts/app.js, missing // core dependencies). These are plugin bugs, not ComfyUI core failures, but // the generic error message alarms users and offers no actionable guidance. // The reporter above still logs the details for developers to debug. - // useToastStore().add({ - // severity: 'error', - // summary: t('g.preloadErrorTitle'), - // detail: t('g.preloadError'), - // life: 10000 - // }) }) // Capture resource load failures (CSS, scripts) in non-localhost distributions diff --git a/src/assets/css/style.css b/src/assets/css/style.css index fc662b09abb..bbcfd6757fb 100644 --- a/src/assets/css/style.css +++ b/src/assets/css/style.css @@ -55,19 +55,6 @@ } } -/* Toasts teleport to . Reka's modal mode sets pointer-events: none on - the body, which left toast close buttons painted above dialogs but - unclickable — clicks fell through to whatever sat beneath (including the - payment dialog's X, closing the checkout mid-payment). Keep toasts - interactive regardless of modal state. */ -.p-toast { - pointer-events: none; -} - -.p-toast-message { - pointer-events: auto; -} - /* Use 0.001ms instead of 0s so transitionend/animationend events still fire and JS listeners aren't broken. */ .disable-animations *, diff --git a/src/base/common/downloadUtil.ts b/src/base/common/downloadUtil.ts index e4a717f811d..082146ff926 100644 --- a/src/base/common/downloadUtil.ts +++ b/src/base/common/downloadUtil.ts @@ -4,8 +4,8 @@ import { t } from '@/i18n' // oxlint-disable-next-line comfy/no-restricted-paths import { isCloud } from '@/platform/distribution/types' -// oxlint-disable-next-line comfy/no-restricted-paths -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' +import { getErrorMessage } from '@/utils/errorUtil' // Constants const DEFAULT_DOWNLOAD_FILENAME = 'download.png' @@ -220,9 +220,9 @@ export async function openFileInNewTab(url: string): Promise { } catch (error) { tab?.close() console.error('Failed to open image:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.errorOpenImage', { - error: error instanceof Error ? error.message : String(error) + error: getErrorMessage(error) ?? t('g.unknownError') }) ) } diff --git a/src/components/common/BackgroundImageUpload.vue b/src/components/common/BackgroundImageUpload.vue index 168e4020fa7..736a77c0da7 100644 --- a/src/components/common/BackgroundImageUpload.vue +++ b/src/components/common/BackgroundImageUpload.vue @@ -37,12 +37,16 @@ - - diff --git a/src/components/lightInfo/useLightInfo.test.ts b/src/components/lightInfo/useLightInfo.test.ts index b4e1c24278f..f991b154817 100644 --- a/src/components/lightInfo/useLightInfo.test.ts +++ b/src/components/lightInfo/useLightInfo.test.ts @@ -1,12 +1,12 @@ import { fromAny } from '@total-typescript/shoehorn' import { assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import { LightInfoViewport } from '@/extensions/core/lightInfo/LightInfoViewport' import type { LightInfoViewportOptions } from '@/extensions/core/lightInfo/LightInfoViewport' import { createDefaultLight } from '@/extensions/core/lightInfo/types' import type { LightInfoEntry } from '@/extensions/core/lightInfo/types' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { toNodeId } from '@/types/nodeId' import { widgetId } from '@/types/widgetId' @@ -174,10 +174,10 @@ describe('useLightInfo widget boundary', () => { useWidgetValueStore().setValue(editorId, [createDefaultLight('point')]) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - detail: - 'Failed to initialize Light Info viewer. Try reloading the page.' + kind: 'warning', + title: 'Failed to initialize Light Info viewer. Try reloading the page.' }) ]) expect(light.lights.value).toHaveLength(0) diff --git a/src/components/lightInfo/useLightInfo.ts b/src/components/lightInfo/useLightInfo.ts index 33d0ca324c0..b0dc43cd6bf 100644 --- a/src/components/lightInfo/useLightInfo.ts +++ b/src/components/lightInfo/useLightInfo.ts @@ -1,6 +1,7 @@ import { computed, ref, toRaw, unref } from 'vue' import type { MaybeRef } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { createSceneHoverHandlers, useViewportNodeWiring @@ -24,7 +25,6 @@ import { t } from '@/i18n' import { onGraphIntent } from '@/lib/litegraph/src/graphIntents' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' const EDITOR_WIDGET_NAME = 'editor_state' @@ -71,9 +71,7 @@ export function useLightInfo(nodeRef: MaybeRef) { surface: 'graph' }) cleanup() - useToastStore().addAlert( - t('toastMessages.failedToInitializeLightInfoViewer') - ) + useToast().warning(t('toastMessages.failedToInitializeLightInfoViewer')) } } diff --git a/src/components/load3d/controls/HDRIControls.test.ts b/src/components/load3d/controls/HDRIControls.test.ts index d6c7811dfb1..d7c4728a0eb 100644 --- a/src/components/load3d/controls/HDRIControls.test.ts +++ b/src/components/load3d/controls/HDRIControls.test.ts @@ -1,19 +1,13 @@ /* oxlint-disable testing-library/no-container, testing-library/no-node-access -- hidden file input has no role/label, queried by selector */ +import { describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' -import { beforeEach, describe, expect, it, vi } from 'vitest' import { ref } from 'vue' import { createI18n } from 'vue-i18n' import HDRIControls from '@/components/load3d/controls/HDRIControls.vue' import type { HDRIConfig } from '@/extensions/core/load3d/interfaces' -import { useToastStore } from '@/platform/updates/common/toastStore' - -beforeEach(() => { - addAlert = useToastStore().addAlert -}) - -let addAlert: ReturnType['addAlert'] const i18n = createI18n({ legacy: false, @@ -170,7 +164,7 @@ describe('HDRIControls', () => { fileInput.dispatchEvent(new Event('change')) expect(onUpdateHdriFile).toHaveBeenCalledWith(file) - expect(addAlert).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('rejects unsupported file extensions with a toast and no emit', async () => { @@ -185,7 +179,12 @@ describe('HDRIControls', () => { fileInput.dispatchEvent(new Event('change')) expect(onUpdateHdriFile).not.toHaveBeenCalled() - expect(addAlert).toHaveBeenCalledWith('Unsupported HDRI format') + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Unsupported HDRI format' + }) + ]) }) }) }) diff --git a/src/components/load3d/controls/HDRIControls.vue b/src/components/load3d/controls/HDRIControls.vue index ff19a767dc5..4b803cc112a 100644 --- a/src/components/load3d/controls/HDRIControls.vue +++ b/src/components/load3d/controls/HDRIControls.vue @@ -91,7 +91,7 @@ import { SUPPORTED_HDRI_EXTENSIONS_ACCEPT } from '@/extensions/core/load3d/constants' import type { HDRIConfig } from '@/extensions/core/load3d/interfaces' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { cn } from '@comfyorg/tailwind-utils' const { t } = useI18n() @@ -119,7 +119,7 @@ function onFileChange(event: Event) { if (file) { const ext = `.${file.name.split('.').pop()?.toLowerCase() ?? ''}` if (!SUPPORTED_HDRI_EXTENSIONS.has(ext)) { - useToastStore().addAlert(t('toastMessages.unsupportedHDRIFormat')) + useToast().warning(t('toastMessages.unsupportedHDRIFormat')) return } } diff --git a/src/components/load3d/menubar/HdriMenuGroup.vue b/src/components/load3d/menubar/HdriMenuGroup.vue index e558f6fef70..0cdd2a6c376 100644 --- a/src/components/load3d/menubar/HdriMenuGroup.vue +++ b/src/components/load3d/menubar/HdriMenuGroup.vue @@ -77,7 +77,7 @@ import { SUPPORTED_HDRI_EXTENSIONS_ACCEPT } from '@/extensions/core/load3d/constants' import type { LightConfig } from '@/extensions/core/load3d/interfaces' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' const { compact = false, sceneHasImage = false } = defineProps<{ compact?: boolean @@ -107,7 +107,7 @@ function onHdriFilePicked(event: Event) { if (file) { const ext = `.${file.name.split('.').pop()?.toLowerCase() ?? ''}` if (!SUPPORTED_HDRI_EXTENSIONS.has(ext)) { - useToastStore().addAlert(t('toastMessages.unsupportedHDRIFormat')) + useToast().warning(t('toastMessages.unsupportedHDRIFormat')) return } } diff --git a/src/components/sidebar/tabs/AssetsSidebarTab.test.ts b/src/components/sidebar/tabs/AssetsSidebarTab.test.ts index 3575f577528..e23dba9e463 100644 --- a/src/components/sidebar/tabs/AssetsSidebarTab.test.ts +++ b/src/components/sidebar/tabs/AssetsSidebarTab.test.ts @@ -82,13 +82,6 @@ vi.mock(import('@/platform/assets/composables/useMediaAssetActions')) vi.mock(import('@/platform/assets/utils/outputAssetUtil')) -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ add: vi.fn() }) - }) -) - const i18n = createI18n({ legacy: false, locale: 'en', diff --git a/src/components/sidebar/tabs/AssetsSidebarTab.vue b/src/components/sidebar/tabs/AssetsSidebarTab.vue index 7b75fa7cf60..353dd315f03 100644 --- a/src/components/sidebar/tabs/AssetsSidebarTab.vue +++ b/src/components/sidebar/tabs/AssetsSidebarTab.vue @@ -165,7 +165,7 @@ diff --git a/src/components/toast/RerouteMigrationToast.vue b/src/components/toast/RerouteMigrationToast.vue deleted file mode 100644 index e807994a3f0..00000000000 --- a/src/components/toast/RerouteMigrationToast.vue +++ /dev/null @@ -1,42 +0,0 @@ - - - diff --git a/src/components/ui/toast/ToastClose.vue b/src/components/ui/toast/ToastClose.vue new file mode 100644 index 00000000000..fa46a4a56cc --- /dev/null +++ b/src/components/ui/toast/ToastClose.vue @@ -0,0 +1,29 @@ + + + diff --git a/src/components/ui/toast/ToastDescription.vue b/src/components/ui/toast/ToastDescription.vue new file mode 100644 index 00000000000..dcffac7c399 --- /dev/null +++ b/src/components/ui/toast/ToastDescription.vue @@ -0,0 +1,26 @@ + + + diff --git a/src/components/ui/toast/ToastDock.test.ts b/src/components/ui/toast/ToastDock.test.ts new file mode 100644 index 00000000000..97f6a525dac --- /dev/null +++ b/src/components/ui/toast/ToastDock.test.ts @@ -0,0 +1,37 @@ +import { render, screen } from '@testing-library/vue' +import { describe, expect, it } from 'vitest' +import { defineComponent, nextTick, ref } from 'vue' + +import { vRekaZIndex } from '@/components/dialog/vRekaZIndex' +import { useModalLiftedZIndex } from '@/composables/useModalLiftedZIndex' + +import ToastDock from './ToastDock.vue' + +const DockedPopover = defineComponent({ + setup() { + return { lifted: useModalLiftedZIndex(ref(true)) } + }, + template: '
' +}) + +describe('ToastDock', () => { + it('stays above dialogs opened later and lifts its popovers above itself', async () => { + render({ + components: { DockedPopover, ToastDock }, + template: '' + }) + render({ + directives: { rekaZIndex: vRekaZIndex }, + template: '
' + }) + await nextTick() + + const dockZ = Number(screen.getByTestId('dock').style.zIndex) + expect(dockZ).toBeGreaterThan( + Number(screen.getByTestId('dialog').style.zIndex) + ) + expect(Number(screen.getByTestId('popover').style.zIndex)).toBeGreaterThan( + dockZ + ) + }) +}) diff --git a/src/components/ui/toast/ToastDock.vue b/src/components/ui/toast/ToastDock.vue new file mode 100644 index 00000000000..ba539bfbc97 --- /dev/null +++ b/src/components/ui/toast/ToastDock.vue @@ -0,0 +1,18 @@ + + + diff --git a/src/components/ui/toast/ToastPanel.stories.ts b/src/components/ui/toast/ToastPanel.stories.ts new file mode 100644 index 00000000000..52c6419e5a0 --- /dev/null +++ b/src/components/ui/toast/ToastPanel.stories.ts @@ -0,0 +1,110 @@ +import type { Meta, StoryObj } from '@storybook/vue3-vite' +import { ref } from 'vue' + +import ProgressToastItem from '@/components/toast/ProgressToastItem.vue' +import Button from '@/components/ui/button/Button.vue' +import type { AssetDownload } from '@/stores/assetDownloadStore' +import { cn } from '@comfyorg/tailwind-utils' + +import ToastDock from './ToastDock.vue' +import ToastPanel from './ToastPanel.vue' + +interface PanelStoryArgs { + expanded: boolean + jobs: AssetDownload[] + status: string + statusIcon: string +} + +function createMockJob(overrides: Partial = {}): AssetDownload { + return { + assetId: 'asset-1', + assetName: 'model-v1.safetensors', + bytesDownloaded: 0, + bytesTotal: 1000000, + lastUpdate: Date.now(), + progress: 0, + status: 'created', + taskId: 'task-1', + ...overrides + } +} + +const meta: Meta = { + title: 'Components/Toast/ToastPanel', + parameters: { layout: 'fullscreen' }, + argTypes: { expanded: { control: 'boolean' } }, + render: (args) => ({ + components: { Button, ProgressToastItem, ToastDock, ToastPanel }, + setup() { + return { args, cn, isExpanded: ref(args.expanded) } + }, + template: ` + + +
+

Download Queue

+
+
+ +
+ +
+
+ ` + }) +} + +export default meta +type Story = StoryObj + +export const InProgress: Story = { + args: { + expanded: false, + jobs: [ + createMockJob({ progress: 1, status: 'completed' }), + createMockJob({ + assetName: 'lora-style.safetensors', + progress: 0.45, + status: 'running', + taskId: 'task-2' + }), + createMockJob({ assetName: 'vae-decoder.safetensors', taskId: 'task-3' }) + ], + status: 'lora-style.safetensors', + statusIcon: + 'icon-[lucide--loader-circle] motion-safe:animate-spin text-muted-foreground' + } +} + +export const Completed: Story = { + args: { + expanded: false, + jobs: [ + createMockJob({ + bytesDownloaded: 1000000, + progress: 1, + status: 'completed' + }) + ], + status: 'All downloads completed', + statusIcon: 'icon-[lucide--check-circle] text-jade-600' + } +} + +export const WithError: Story = { + args: { + expanded: true, + jobs: [createMockJob({ progress: 0.23, status: 'failed' })], + status: '1 download failed', + statusIcon: 'icon-[lucide--circle-alert] text-destructive-background' + } +} diff --git a/src/components/ui/toast/ToastPanel.test.ts b/src/components/ui/toast/ToastPanel.test.ts new file mode 100644 index 00000000000..635a99e8002 --- /dev/null +++ b/src/components/ui/toast/ToastPanel.test.ts @@ -0,0 +1,62 @@ +import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' +import { describe, expect, it } from 'vitest' +import { defineComponent, ref } from 'vue' + +import ToastPanel from './ToastPanel.vue' + +const PanelWithToggle = defineComponent({ + components: { ToastPanel }, + props: { visible: { type: Boolean, default: true } }, + setup() { + return { expanded: ref(false) } + }, + template: ` + +
{{ expanded ? 'expanded' : 'collapsed' }}
+ +
+ ` +}) + +describe('ToastPanel', () => { + it('renders only while visible and keeps its content out of the live region', async () => { + const { rerender } = render(PanelWithToggle, { props: { visible: false } }) + expect(screen.queryByTestId('content')).not.toBeInTheDocument() + + await rerender({ visible: true }) + + expect(screen.getByTestId('content')).toHaveTextContent('collapsed') + expect(screen.getByRole('status')).not.toContainElement( + screen.getByTestId('content') + ) + }) + + it('announces its status politely only while visible', async () => { + const { rerender } = render(ToastPanel, { + props: { announcement: 'Importing Models', visible: false } + }) + const status = screen.getByRole('status') + expect(status).toBeEmptyDOMElement() + + await rerender({ announcement: 'Importing Models', visible: true }) + expect(status).toHaveTextContent('Importing Models') + + await rerender({ announcement: 'All downloads completed', visible: true }) + expect(screen.getByRole('status')).toBe(status) + expect(status).toHaveTextContent('All downloads completed') + }) + + it('expands and collapses from the footer toggle', async () => { + const user = userEvent.setup() + render(PanelWithToggle) + + await user.click(screen.getByRole('button', { name: 'Expand' })) + expect(screen.getByTestId('content')).toHaveTextContent('expanded') + + await user.click(screen.getByRole('button', { name: 'Collapse' })) + expect(screen.getByTestId('content')).toHaveTextContent('collapsed') + }) +}) diff --git a/src/components/ui/toast/ToastPanel.vue b/src/components/ui/toast/ToastPanel.vue new file mode 100644 index 00000000000..e8ac75dd247 --- /dev/null +++ b/src/components/ui/toast/ToastPanel.vue @@ -0,0 +1,50 @@ + + + diff --git a/src/components/ui/toast/ToastRoot.vue b/src/components/ui/toast/ToastRoot.vue new file mode 100644 index 00000000000..c1378dca62c --- /dev/null +++ b/src/components/ui/toast/ToastRoot.vue @@ -0,0 +1,29 @@ + + + diff --git a/src/components/ui/toast/ToastTitle.vue b/src/components/ui/toast/ToastTitle.vue new file mode 100644 index 00000000000..7b1e15dd923 --- /dev/null +++ b/src/components/ui/toast/ToastTitle.vue @@ -0,0 +1,23 @@ + + + diff --git a/src/components/ui/toast/ToastViewport.vue b/src/components/ui/toast/ToastViewport.vue new file mode 100644 index 00000000000..7f45dbd58cc --- /dev/null +++ b/src/components/ui/toast/ToastViewport.vue @@ -0,0 +1,35 @@ + + + diff --git a/src/components/ui/toast/Toaster.stories.ts b/src/components/ui/toast/Toaster.stories.ts new file mode 100644 index 00000000000..338024c7bf4 --- /dev/null +++ b/src/components/ui/toast/Toaster.stories.ts @@ -0,0 +1,43 @@ +import type { Meta, StoryObj } from '@storybook/vue3-vite' + +import Button from '@/components/ui/button/Button.vue' + +import Toaster from './Toaster.vue' +import { useToast } from './toastStore' + +const meta: Meta = { + title: 'Components/Toast/Toaster', + component: Toaster, + parameters: { layout: 'fullscreen' } +} + +export default meta +type Story = StoryObj + +export const Kinds: Story = { + render: () => ({ + components: { Button, Toaster }, + setup() { + const toast = useToast() + toast.dismissAll() + toast.success('Workflow saved') + toast.info('Update available', { description: 'Restart to apply.' }) + toast.loading('Uploading model.safetensors') + toast.warning('Pop-up blocked', { + action: { label: 'Try again', onClick: () => {} }, + description: 'Allow pop-ups for this site and try again.' + }) + toast.error('Save failed', { + description: 'ENOSPC: no space left on device, /home/user/workflows' + }) + return { toast } + }, + template: ` +
+ + + +
+ ` + }) +} diff --git a/src/components/ui/toast/Toaster.test.ts b/src/components/ui/toast/Toaster.test.ts new file mode 100644 index 00000000000..4c482a5a8e6 --- /dev/null +++ b/src/components/ui/toast/Toaster.test.ts @@ -0,0 +1,364 @@ +import { ZIndex } from '@primeuix/utils/zindex' +import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' +import { describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' +import { createI18n } from 'vue-i18n' + +import { MODAL_Z_BASE, vRekaZIndex } from '@/components/dialog/vRekaZIndex' + +import { createToastId } from '@/types/toastId' +import type { ToastId } from '@/types/toastId' + +import Toaster from './Toaster.vue' +import { useToast } from './toastStore' + +const i18n = createI18n({ + legacy: false, + locale: 'en', + messages: { + en: { + g: { close: 'Close' }, + toastMessages: { + notificationsLabel: 'Notification', + notificationsViewportLabel: 'Notifications ({hotkey})' + } + } + } +}) + +function renderToaster() { + return render(Toaster, { global: { plugins: [i18n] } }) +} + +function pressEscapePreventedUpstream() { + const prevent = (event: KeyboardEvent) => event.preventDefault() + window.addEventListener('keydown', prevent, { capture: true }) + window.dispatchEvent( + new KeyboardEvent('keydown', { + bubbles: true, + cancelable: true, + key: 'Escape' + }) + ) + window.removeEventListener('keydown', prevent, { capture: true }) +} + +describe('Toaster', () => { + it('announces errors and warnings assertively and other notifications politely', async () => { + renderToaster() + const toast = useToast() + + toast.success('Saved') + toast.loading('Uploading') + toast.error('Could not save', { description: 'Disk is full' }) + toast.warning('Pop-up blocked', { + action: { label: 'Try again', onClick: vi.fn() } + }) + await nextTick() + + const polite = screen.getByRole('status', { name: 'Notification' }) + const assertive = screen.getByRole('alert', { name: 'Notification' }) + expect(polite).toHaveTextContent('SavedUploading') + expect(assertive).toHaveTextContent( + 'Could not save. Disk is fullPop-up blocked. Try again' + ) + expect(polite).toHaveAttribute('aria-atomic', 'false') + expect(assertive).toHaveAttribute('aria-atomic', 'false') + }) + + it('does not announce a notification again after node picking ends', async () => { + renderToaster() + const toast = useToast() + toast.info('Uploaded') + await nextTick() + const announcement = screen.getByText('Uploaded', { + selector: '[role="status"] > p' + }) + + toast.held = true + await nextTick() + toast.held = false + await nextTick() + + expect( + screen.getByText('Uploaded', { selector: '[role="status"] > p' }) + ).toBe(announcement) + }) + + it('renders each notification once outside the live regions', async () => { + renderToaster() + + useToast().error('Save failed', { description: 'Try another location' }) + await nextTick() + await vi.advanceTimersByTimeAsync(1000) + + expect(screen.getByTestId('toast')).toHaveAttribute('aria-live', 'off') + expect(document.body.textContent.match(/Save failed/g)).toHaveLength(2) + }) + + it('runs a notification action from its button', async () => { + const user = userEvent.setup() + const onClick = vi.fn() + renderToaster() + + useToast().warning('Pop-up blocked', { + action: { label: 'Try again', onClick }, + description: 'Allow pop-ups and try again' + }) + await nextTick() + await user.click(screen.getByRole('button', { name: 'Try again' })) + + expect(onClick).toHaveBeenCalledOnce() + expect(screen.getByTestId('toast')).toHaveTextContent( + 'Pop-up blockedAllow pop-ups and try again' + ) + }) + + it('labels the notification regions in the active locale', async () => { + render(Toaster, { + global: { + plugins: [ + createI18n({ + legacy: false, + locale: 'fr', + messages: { + fr: { + g: { close: 'Fermer' }, + toastMessages: { + notificationsLabel: 'Notification FR', + notificationsViewportLabel: 'Notifications FR ({hotkey})' + } + } + } + }) + ] + } + }) + + useToast().info('Enregistré') + await nextTick() + + expect( + screen.getByRole('region', { name: 'Notifications FR (F8)' }) + ).toBeInTheDocument() + expect( + screen.getByRole('status', { name: 'Notification FR' }) + ).toHaveTextContent('Enregistré') + }) + + it('lifts a new notification above a dialog opened after the last one', async () => { + renderToaster() + useToast().info('Uploading') + await nextTick() + render({ + directives: { rekaZIndex: vRekaZIndex }, + template: '
' + }) + + useToast().info('Ready') + await nextTick() + + expect( + Number(screen.getByTestId('toast-viewport').style.zIndex) + ).toBeGreaterThan(Number(screen.getByTestId('dialog').style.zIndex)) + }) + + it('stays out of the modal stacking order while idle', async () => { + renderToaster() + const id = useToast().info('Ready') + await nextTick() + + useToast().dismiss(id) + await nextTick() + + expect(ZIndex.getCurrent('modal')).toBeLessThan(MODAL_Z_BASE) + expect(screen.queryByTestId('toast-viewport')).not.toBeInTheDocument() + }) + + it('drops its notifications when its layout unmounts', async () => { + const { unmount } = renderToaster() + useToast().error('Invalid login credentials') + await nextTick() + + unmount() + + expect(useToast().toasts).toEqual([]) + }) + + it.for([ + { name: 'a sticky replacement', elapsed: 0, replacement: undefined }, + { name: 'a reissued timed notification', elapsed: 2500, replacement: 3000 } + ])( + 'gives $name of an id a fresh lifetime', + async ({ elapsed, replacement }) => { + renderToaster() + const toast = useToast() + const id = createToastId() + toast.info('Uploading', { duration: 3000, id }) + await nextTick() + await vi.advanceTimersByTimeAsync(elapsed) + + toast.error('Upload failed', { duration: replacement, id }) + await nextTick() + await vi.advanceTimersByTimeAsync(3000 - elapsed + 100) + await nextTick() + + expect(screen.getByTestId('toast')).toHaveTextContent('Upload failed') + } + ) + + it('automatically dismisses a timed notification', async () => { + renderToaster() + + useToast().info('Uploaded', { duration: 1000 }) + await nextTick() + expect(screen.getByTestId('toast')).toHaveTextContent('Uploaded') + + await vi.advanceTimersByTimeAsync(1000) + await nextTick() + + expect(screen.queryByTestId('toast')).not.toBeInTheDocument() + }) + + it.for([ + { + name: 'the pointer closed the last notification', + pauseAndEmpty: async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) + await user.hover(screen.getByTestId('toast')) + await user.click(screen.getByRole('button', { name: 'Close' })) + } + }, + { + name: 'the last notification was dismissed while the window was blurred', + pauseAndEmpty: async (id: ToastId) => { + window.dispatchEvent(new Event('blur')) + useToast().dismiss(id) + await nextTick() + window.dispatchEvent(new Event('focus')) + } + } + ])('times out later notifications after $name', async ({ pauseAndEmpty }) => { + renderToaster() + const id = useToast().loading('Waiting for payment') + await nextTick() + + await pauseAndEmpty(id) + await nextTick() + useToast().success('Payment complete', { duration: 1000 }) + await nextTick() + await vi.advanceTimersByTimeAsync(1000) + await nextTick() + + expect(screen.queryByText('Payment complete')).not.toBeInTheDocument() + }) + + it('hides held notifications and restarts their timers when shown', async () => { + renderToaster() + const toast = useToast() + toast.held = true + + toast.info('Uploaded', { duration: 1000 }) + await nextTick() + await vi.advanceTimersByTimeAsync(5000) + expect(screen.queryByTestId('toast')).not.toBeInTheDocument() + + toast.held = false + await nextTick() + expect(screen.getByTestId('toast')).toHaveTextContent('Uploaded') + + await vi.advanceTimersByTimeAsync(1000) + await nextTick() + expect(screen.queryByTestId('toast')).not.toBeInTheDocument() + }) + + it('preserves notifications when Escape is pressed', async () => { + const user = userEvent.setup() + renderToaster() + + const toast = useToast() + toast.info('First') + toast.warning('Second') + await nextTick() + + await user.keyboard('{Escape}') + + expect( + screen.getAllByTestId('toast').map((element) => element.textContent) + ).toEqual(['First', 'Second']) + }) + + it('does not prevent the default Escape behavior', async () => { + renderToaster() + + useToast().info('Ready') + await nextTick() + + const event = new KeyboardEvent('keydown', { + bubbles: true, + cancelable: true, + key: 'Escape' + }) + window.dispatchEvent(event) + + expect(event.defaultPrevented).toBe(false) + }) + + it('still closes from its button after an Escape handled elsewhere', async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) + renderToaster() + useToast().warning('Check settings') + await nextTick() + + pressEscapePreventedUpstream() + await user.click(screen.getByRole('button', { name: 'Close' })) + + expect(useToast().toasts).toEqual([]) + }) + + it('still times out after an Escape handled elsewhere', async () => { + renderToaster() + useToast().info('Uploaded', { duration: 1000 }) + await nextTick() + + pressEscapePreventedUpstream() + await vi.advanceTimersByTimeAsync(1000) + await nextTick() + + expect(useToast().toasts).toEqual([]) + }) + + it('dismisses a notification from its close button', async () => { + const user = userEvent.setup() + renderToaster() + + useToast().warning('Check settings') + await nextTick() + await user.click(screen.getByRole('button', { name: 'Close' })) + + expect(screen.queryByText('Check settings')).not.toBeInTheDocument() + }) + + it('cannot swipe away a notification and keeps its text selectable', async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }) + renderToaster() + useToast().error('Sticky', { closable: false }) + await nextTick() + const notification = screen.getByTestId('toast') + notification.setPointerCapture = vi.fn() + notification.releasePointerCapture = vi.fn() + notification.hasPointerCapture = () => false + + await user.pointer([ + { coords: { x: 0, y: 0 }, keys: '[MouseLeft>]', target: notification }, + { coords: { x: 10, y: 0 } }, + { coords: { x: 80, y: 0 } }, + { keys: '[/MouseLeft]' } + ]) + await nextTick() + + expect(screen.getByTestId('toast')).toHaveTextContent('Sticky') + expect(screen.getByTestId('toast').style.userSelect).not.toBe('none') + }) +}) diff --git a/src/components/ui/toast/Toaster.vue b/src/components/ui/toast/Toaster.vue new file mode 100644 index 00000000000..7a2f280d5e3 --- /dev/null +++ b/src/components/ui/toast/Toaster.vue @@ -0,0 +1,134 @@ + + + diff --git a/src/components/ui/toast/toastStore.test.ts b/src/components/ui/toast/toastStore.test.ts new file mode 100644 index 00000000000..fd56d9917ec --- /dev/null +++ b/src/components/ui/toast/toastStore.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, expectTypeOf, it } from 'vitest' + +import { createToastId } from '@/types/toastId' +import type { ToastId } from '@/types/toastId' + +import { useToast } from './toastStore' + +describe('useToast', () => { + it('creates persistent notifications by default and dismisses by id', () => { + const toast = useToast() + const id = toast.error('Save failed', { description: 'Disk is full' }) + + expect(toast.toasts).toEqual([ + expect.objectContaining({ + description: 'Disk is full', + duration: Number.POSITIVE_INFINITY, + id, + kind: 'error', + title: 'Save failed' + }) + ]) + + toast.dismiss(id) + expect(toast.toasts).toEqual([]) + }) + + it('replaces the notification that holds a caller-provided id', () => { + const toast = useToast() + const id = createToastId() + + expect(toast.loading('Uploading', { id })).toBe(id) + toast.error('Upload failed', { id }) + + expect(toast.toasts).toEqual([ + expect.objectContaining({ id, kind: 'error', title: 'Upload failed' }) + ]) + }) + + it('reports whether dismissing removed a notification', () => { + const toast = useToast() + const id = toast.info('Saved') + + expect(toast.dismiss(id)).toBe(true) + expect(toast.dismiss(id)).toBe(false) + }) + + it('dismisses every notification at once', () => { + const toast = useToast() + toast.info('Saved') + toast.loading('Uploading') + + toast.dismissAll() + + expect(toast.toasts).toEqual([]) + }) + + it('accepts only minted toast ids', () => { + expectTypeOf().not.toExtend() + expectTypeOf(useToast().info('Saved')).toEqualTypeOf() + expectTypeOf(useToast().dismiss).parameter(0).toEqualTypeOf() + }) +}) diff --git a/src/components/ui/toast/toastStore.ts b/src/components/ui/toast/toastStore.ts new file mode 100644 index 00000000000..caa980a36c3 --- /dev/null +++ b/src/components/ui/toast/toastStore.ts @@ -0,0 +1,85 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' + +import { createToastId } from '@/types/toastId' +import type { ToastId } from '@/types/toastId' +import type { ToastAction, ToastOptions } from '@/types/extensionTypes' + +type ToastKind = 'error' | 'info' | 'loading' | 'success' | 'warning' + +export interface Toast { + closable: boolean + duration: number + id: ToastId + instance: symbol + kind: ToastKind + title: string + action?: ToastAction + description?: string +} + +export const useToast = defineStore('toast', () => { + const toasts = ref([]) + const held = ref(false) + + function add(kind: ToastKind, title: string, options: ToastOptions = {}) { + const id = options.id ?? createToastId() + toasts.value = [ + ...toasts.value.filter((toast) => toast.id !== id), + { + action: options.action, + closable: options.closable ?? true, + description: options.description, + duration: options.duration ?? Number.POSITIVE_INFINITY, + id, + instance: Symbol(), + kind, + title + } + ] + return id + } + + function success(title: string, options?: ToastOptions) { + return add('success', title, options) + } + + function error(title: string, options?: ToastOptions) { + return add('error', title, options) + } + + function info(title: string, options?: ToastOptions) { + return add('info', title, options) + } + + function warning(title: string, options?: ToastOptions) { + return add('warning', title, options) + } + + function loading(title: string, options?: ToastOptions) { + return add('loading', title, options) + } + + function dismiss(id: ToastId): boolean { + const remaining = toasts.value.filter((toast) => toast.id !== id) + const removed = remaining.length < toasts.value.length + toasts.value = remaining + return removed + } + + function dismissAll() { + toasts.value = [] + } + + return { + held, + toasts, + success, + error, + info, + warning, + loading, + dismiss, + dismissAll + } +}) diff --git a/src/composables/auth/useAuthActions.test.ts b/src/composables/auth/useAuthActions.test.ts index abf2b2c1875..69c90731006 100644 --- a/src/composables/auth/useAuthActions.test.ts +++ b/src/composables/auth/useAuthActions.test.ts @@ -1,6 +1,6 @@ import { useDialogService } from '@/services/dialogService' +import { useToast } from '@/components/ui/toast/toastStore' import { SsoRequiredAuthError, useAuthStore } from '@/stores/authStore' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { FirebaseError } from 'firebase/app' import { AuthErrorCodes } from 'firebase/auth' @@ -27,8 +27,6 @@ type ModifiedWorkflow = Pick let mockAuthStore: ReturnType -let mockToastStore: ReturnType - let mockWorkflowStore: ReturnType const mockToastErrorHandler = vi.hoisted(() => vi.fn()) @@ -44,12 +42,16 @@ const firebaseCodesWithOwnMessage = Object.keys(authErrorMessages).filter( (key) => key.startsWith('auth/') ) -const popupPermissionCodes = [ +const popupPermissionCodes: readonly string[] = [ AuthErrorCodes.POPUP_CLOSED_BY_USER, AuthErrorCodes.EXPIRED_POPUP_REQUEST, AuthErrorCodes.POPUP_BLOCKED ] +const errorCodesWithOwnMessage = firebaseCodesWithOwnMessage.filter( + (code) => !popupPermissionCodes.includes(code) +) + const accessErrorCodes = [ 'auth/unauthorized-domain', 'auth/invalid-dynamic-link-domain', @@ -119,7 +121,6 @@ beforeEach(() => { billingContext.isFreeTier = computed(() => true) stubFirebaseAuthHarness() mockAuthStore = useAuthStore() - mockToastStore = useToastStore() mockWorkflowStore = useWorkflowStore() vi.mocked(mockAuthStore.initiateCreditPurchase).mockResolvedValue({ checkout_url: 'https://checkout.stripe.test' @@ -372,7 +373,7 @@ describe('useAuthActions.logout', () => { expect(mockAuthStore.logout).not.toHaveBeenCalled() expect(mockClearAllWorkspaceStorage).not.toHaveBeenCalled() - expect(mockToastStore.add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('passes denyLabel "Sign out anyway" to the dialog', async () => { @@ -413,10 +414,8 @@ describe('useAuthActions auth flow error telemetry', () => { error_code: 'auth/user-not-found', auth_action: 'email_sign_in' }) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.auth/invalid-credential' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.auth/invalid-credential' }) }) @@ -450,7 +449,7 @@ describe('useAuthActions auth flow error telemetry', () => { ) expect(mockAuthStore.logout).toHaveBeenCalledOnce() expect(mockToastErrorHandler).not.toHaveBeenCalled() - expect(mockToastStore.add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('keeps the failure toast while SSO is off', async () => { @@ -504,16 +503,20 @@ describe('useAuthActions auth flow error telemetry', () => { }) describe('useAuthActions.reportError', () => { - it.for(firebaseCodesWithOwnMessage)( - 'maps %s to its own message rather than the generic fallback', + it.for(errorCodesWithOwnMessage)( + 'maps %s to its own error message rather than the generic fallback', (code) => { const { reportError } = useAuthActions() reportError(new FirebaseError(code, 'raw firebase')) - expect(mockToastStore.add).toHaveBeenCalledWith( - expect.objectContaining({ detail: `auth.errors.${code}` }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: `auth.errors.${code}`, + kind: 'error', + title: 'g.error' + }) + ]) expect(mockToastErrorHandler).not.toHaveBeenCalled() } ) @@ -525,9 +528,10 @@ describe('useAuthActions.reportError', () => { reportError(new FirebaseError(code, 'raw firebase')) - expect(mockToastStore.add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'g.error', expect.objectContaining({ - detail: 'auth.errors.auth/invalid-credential' + description: 'auth.errors.auth/invalid-credential' }) ) } @@ -544,7 +548,7 @@ describe('useAuthActions.reportError', () => { it('covers every popup-permission code with its own message', () => { expect(firebaseCodesWithOwnMessage).toEqual( - expect.arrayContaining(popupPermissionCodes) + expect.arrayContaining([...popupPermissionCodes]) ) }) @@ -560,10 +564,8 @@ describe('useAuthActions.reportError', () => { ) ) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.signupBlocked' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.signupBlocked' }) expect(mockToastErrorHandler).not.toHaveBeenCalled() }) @@ -575,10 +577,8 @@ describe('useAuthActions.reportError', () => { new FirebaseError('auth/internal-error', 'rejected: SIGNUP_BLOCKED') ) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.signupBlocked' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.signupBlocked' }) }) @@ -587,10 +587,8 @@ describe('useAuthActions.reportError', () => { reportError(new FirebaseError('auth/some-new-code', 'raw firebase')) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.generic' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.generic' }) expect(mockToastErrorHandler).not.toHaveBeenCalled() }) @@ -602,10 +600,8 @@ describe('useAuthActions.reportError', () => { new FirebaseError('app/no-app', 'Firebase: Error (app/no-app).') ) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.generic' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.generic' }) expect( mockToastErrorHandler, @@ -620,7 +616,7 @@ describe('useAuthActions.reportError', () => { reportError(networkError) expect(mockToastErrorHandler).toHaveBeenCalledWith(networkError) - expect(mockToastStore.add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it.for(popupPermissionCodes)( @@ -630,10 +626,8 @@ describe('useAuthActions.reportError', () => { reportError(new FirebaseError(code, 'raw firebase')) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'warn', - summary: 'g.warning', - detail: `auth.errors.${code}` + expect(useToast().warning).toHaveBeenCalledWith('g.warning', { + description: `auth.errors.${code}` }) expect(mockToastErrorHandler).not.toHaveBeenCalled() } @@ -646,10 +640,8 @@ describe('useAuthActions.reportError', () => { new FirebaseError('auth/account-exists-with-different-credential', 'raw') ) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: 'auth.errors.auth/account-exists-with-different-credential' + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'auth.errors.auth/account-exists-with-different-credential' }) expect(accessError.value).toBe(false) }) @@ -662,10 +654,8 @@ describe('useAuthActions.reportError', () => { reportError(new FirebaseError(code, 'raw firebase')) expect(accessError.value).toBe(true) - expect(mockToastStore.add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'g.error', - detail: `toastMessages.unauthorizedDomain:${window.location.hostname}:support@comfy.org` + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: `toastMessages.unauthorizedDomain:${window.location.hostname}:support@comfy.org` }) } ) diff --git a/src/composables/auth/useAuthActions.ts b/src/composables/auth/useAuthActions.ts index b46a1d20f72..ba10f137256 100644 --- a/src/composables/auth/useAuthActions.ts +++ b/src/composables/auth/useAuthActions.ts @@ -20,7 +20,7 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import type { AuthFlowAction } from '@/platform/telemetry/types' import { PaymentPopupBlockedError } from '@/platform/telemetry/utils/billingFailureCategory' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { clearAllWorkspaceStorage, prepareWorkflowLogoutTransition @@ -59,7 +59,7 @@ export const localizedAuthErrorCopy = (): AuthErrorCopy => ({ */ export const useAuthActions = () => { const authStore = useAuthStore() - const toastStore = useToastStore() + const toast = useToast() const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling() const accessError = ref(false) @@ -89,31 +89,24 @@ export const useAuthActions = () => { } const classification = classifyAuthError(error) // Ref: https://firebase.google.com/docs/auth/admin/errors - const severity = severityForAuthError(classification) - const summary = t(severity === 'warn' ? 'g.warning' : 'g.error') + const kind = severityForAuthError(classification) + const notify = (description: string) => + toast[kind](t(`g.${kind}`), { description }) if (classification.kind === 'unauthorized-domain') { accessError.value = true - toastStore.add({ - severity, - summary, - detail: t('toastMessages.unauthorizedDomain', { + notify( + t('toastMessages.unauthorizedDomain', { domain: window.location.hostname, email: 'support@comfy.org' }) - }) + ) } else if (classification.kind !== 'unknown') { - toastStore.add({ - severity, - summary, - detail: authErrorMessage(classification, localizedAuthErrorCopy()) - }) + notify(authErrorMessage(classification, localizedAuthErrorCopy())) } else if (error instanceof FirebaseError) { // classifyAuthError only knows auth/ codes; an app/ or installations/ // FirebaseError still gets the localized copy, never the raw SDK text. - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: st(`auth.errors.${error.code}`, t('auth.errors.generic')) + toast.error(t('g.error'), { + description: st(`auth.errors.${error.code}`, t('auth.errors.generic')) }) } else { toastErrorHandler(error) @@ -162,11 +155,9 @@ export const useAuthActions = () => { clearAllWorkspaceStorage() } - toastStore.add({ - severity: 'success', - summary: t('auth.signOut.success'), - detail: t('auth.signOut.successDetail'), - life: 5000 + toast.success(t('auth.signOut.success'), { + description: t('auth.signOut.successDetail'), + duration: 5000 }) if (isCloud) { @@ -184,11 +175,9 @@ export const useAuthActions = () => { const sendPasswordReset = wrapWithErrorHandlingAsync( async (email: string) => { await authStore.sendPasswordReset(email) - toastStore.add({ - severity: 'success', - summary: t('auth.login.passwordResetSent'), - detail: t('auth.login.passwordResetSentDetail'), - life: 5000 + toast.success(t('auth.login.passwordResetSent'), { + description: t('auth.login.passwordResetSentDetail'), + duration: 5000 }) return true }, @@ -340,11 +329,9 @@ export const useAuthActions = () => { const updatePassword = wrapWithErrorHandlingAsync( async (newPassword: string) => { await authStore.updatePassword(newPassword) - toastStore.add({ - severity: 'success', - summary: t('auth.passwordUpdate.success'), - detail: t('auth.passwordUpdate.successDetail'), - life: 5000 + toast.success(t('auth.passwordUpdate.success'), { + description: t('auth.passwordUpdate.successDetail'), + duration: 5000 }) }, reportError, diff --git a/src/composables/graph/useSelectionOperations.ts b/src/composables/graph/useSelectionOperations.ts index 7dc93a7009d..6baef52e986 100644 --- a/src/composables/graph/useSelectionOperations.ts +++ b/src/composables/graph/useSelectionOperations.ts @@ -1,7 +1,7 @@ // import { useSelectedLiteGraphItems } from '@/composables/canvas/useSelectedLiteGraphItems' // Unused for now import { t } from '@/i18n' import { LGraphNode } from '@/lib/litegraph/src/litegraph' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useCanvasStore, @@ -17,7 +17,7 @@ import { isSelectOnly } from '@/utils/litegraphUtil' export function useSelectionOperations() { // const { getSelectedNodes } = useSelectedLiteGraphItems() // Unused for now const canvasStore = useCanvasStore() - const toastStore = useToastStore() + const toast = useToast() const dialogService = useDialogService() const titleEditorStore = useTitleEditorStore() const workflowStore = useWorkflowStore() @@ -25,21 +25,17 @@ export function useSelectionOperations() { const copySelection = () => { const canvas = app.canvas if (canvas.selectedItems.size === 0) { - toastStore.add({ - severity: 'warn', - summary: t('g.nothingToCopy'), - detail: t('g.selectItemsToCopy'), - life: 3000 + toast.warning(t('g.nothingToCopy'), { + description: t('g.selectItemsToCopy'), + duration: 3000 }) return } canvas.copyToClipboard() - toastStore.add({ - severity: 'success', - summary: t('g.copied'), - detail: t('g.itemsCopiedToClipboard'), - life: 2000 + toast.success(t('g.copied'), { + description: t('g.itemsCopiedToClipboard'), + duration: 2000 }) } @@ -54,11 +50,9 @@ export function useSelectionOperations() { const duplicateSelection = () => { const canvas = app.canvas if (canvas.selectedItems.size === 0) { - toastStore.add({ - severity: 'warn', - summary: t('g.nothingToDuplicate'), - detail: t('g.selectItemsToDuplicate'), - life: 3000 + toast.warning(t('g.nothingToDuplicate'), { + description: t('g.selectItemsToDuplicate'), + duration: 3000 }) return } @@ -82,11 +76,9 @@ export function useSelectionOperations() { // mode ends. if (isSelectOnly(canvas)) return if (canvas.selectedItems.size === 0) { - toastStore.add({ - severity: 'warn', - summary: t('g.nothingToDelete'), - detail: t('g.selectItemsToDelete'), - life: 3000 + toast.warning(t('g.nothingToDelete'), { + description: t('g.selectItemsToDelete'), + duration: 3000 }) return } @@ -153,11 +145,9 @@ export function useSelectionOperations() { return } - toastStore.add({ - severity: 'warn', - summary: t('g.nothingToRename'), - detail: t('g.selectItemsToRename'), - life: 3000 + toast.warning(t('g.nothingToRename'), { + description: t('g.selectItemsToRename'), + duration: 3000 }) } diff --git a/src/composables/graph/useSubgraphOperations.test.ts b/src/composables/graph/useSubgraphOperations.test.ts index 4c719ab4193..d4dd84d1250 100644 --- a/src/composables/graph/useSubgraphOperations.test.ts +++ b/src/composables/graph/useSubgraphOperations.test.ts @@ -1,9 +1,9 @@ import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import type { LGraph, LGraphCanvas } from '@/lib/litegraph/src/litegraph' import { LGraphNode, SubgraphNode } from '@/lib/litegraph/src/litegraph' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' @@ -65,13 +65,9 @@ describe('useSubgraphOperations', () => { }) expect(revokeSubgraphPreviews).not.toHaveBeenCalled() expect(captureCanvasState).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toEqual([ - { - severity: 'error', - summary: 'Error', - detail: 'Unable to unpack the selected subgraph.' - } - ]) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: 'Unable to unpack the selected subgraph.' + }) }) it('updates previews and history only for successful unpacks', () => { diff --git a/src/composables/graph/useSubgraphOperations.ts b/src/composables/graph/useSubgraphOperations.ts index 7b639ffa570..7058e048e28 100644 --- a/src/composables/graph/useSubgraphOperations.ts +++ b/src/composables/graph/useSubgraphOperations.ts @@ -1,7 +1,7 @@ import { useSelectedLiteGraphItems } from '@/composables/canvas/useSelectedLiteGraphItems' +import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' import { SubgraphNode } from '@/lib/litegraph/src/litegraph' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' @@ -16,7 +16,7 @@ export function useSubgraphOperations() { const workflowStore = useWorkflowStore() const nodeOutputStore = useNodeOutputStore() const subgraphStore = useSubgraphStore() - const toastStore = useToastStore() + const toast = useToast() const convertToSubgraph = () => { const canvas = canvasStore.getCanvas() @@ -51,10 +51,8 @@ export function useSubgraphOperations() { changed = true } if (refused) { - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('g.subgraphUnpackFailed') + toast.error(t('g.error'), { + description: t('g.subgraphUnpackFailed') }) } if (changed) { diff --git a/src/composables/node/useNodeDragToCanvas.test.ts b/src/composables/node/useNodeDragToCanvas.test.ts index bbfe6eb8f63..87b37ad0ceb 100644 --- a/src/composables/node/useNodeDragToCanvas.test.ts +++ b/src/composables/node/useNodeDragToCanvas.test.ts @@ -1,9 +1,9 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ComfyNodeDefImpl } from '@/stores/nodeDefStore' import { useNodeDragToCanvas } from './useNodeDragToCanvas' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' -import { useToastStore } from '@/platform/updates/common/toastStore' import { LGraphNode } from '@/lib/litegraph/src/litegraph' import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph' import { fromPartial } from '@total-typescript/shoehorn' @@ -302,10 +302,10 @@ describe('useNodeDragToCanvas', () => { ) expect(mockSelectItems).toHaveBeenCalledWith([placedNode]) - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( + expect.any(String), expect.objectContaining({ - severity: 'warn', - detail: 'assetBrowser.failedToSetModelValue' + description: 'assetBrowser.failedToSetModelValue' }) ) expect(console.error).toHaveBeenCalledWith( @@ -333,10 +333,10 @@ describe('useNodeDragToCanvas', () => { }) ) - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), expect.objectContaining({ - severity: 'error', - detail: 'assetBrowser.failedToCreateNode' + description: 'assetBrowser.failedToCreateNode' }) ) }) diff --git a/src/composables/node/useNodeDragToCanvas.ts b/src/composables/node/useNodeDragToCanvas.ts index 65a67fe63c8..b56781b233d 100644 --- a/src/composables/node/useNodeDragToCanvas.ts +++ b/src/composables/node/useNodeDragToCanvas.ts @@ -4,7 +4,7 @@ import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import { withNodeAddSource } from '@/platform/telemetry/nodeAdded/nodeAddSource' import type { NodeAddSource } from '@/platform/telemetry/types' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useLitegraphService } from '@/services/litegraphService' import type { ComfyNodeDefImpl } from '@/stores/nodeDefStore' @@ -41,10 +41,8 @@ function applyWidgetValues(node: LGraphNode, values: WidgetValues) { const widget = node.widgets?.find((w) => w.name === name) if (!widget) { console.error(`Widget ${name} not found on node ${node.type}`) - useToastStore().add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('assetBrowser.failedToSetModelValue') + useToast().warning(t('g.warning'), { + description: t('assetBrowser.failedToSetModelValue') }) continue } @@ -80,10 +78,8 @@ function addNodeAtPosition(clientX: number, clientY: number): boolean { ) if (!node) { console.error(`Failed to add node to graph: ${nodeDef.name}`) - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('assetBrowser.failedToCreateNode') + useToast().error(t('g.error'), { + description: t('assetBrowser.failedToCreateNode') }) return true } diff --git a/src/composables/node/useNodeImageUpload.test.ts b/src/composables/node/useNodeImageUpload.test.ts index 2f061af660b..f89a9b9afbc 100644 --- a/src/composables/node/useNodeImageUpload.test.ts +++ b/src/composables/node/useNodeImageUpload.test.ts @@ -1,3 +1,4 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { fromAny } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -6,7 +7,6 @@ import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import type { ResultItem } from '@/platform/remote/comfyui/execution/types' import { api } from '@/scripts/api' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAssetsStore } from '@/stores/assetsStore' import type { Mock } from 'vitest' @@ -186,9 +186,7 @@ describe('useNodeImageUpload', () => { await capturedDragOnDrop([createFile()]) expect(t).toHaveBeenCalledWith('g.uploadFileTooLarge') - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.uploadFileTooLarge' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.uploadFileTooLarge') }) it('shows a file-too-large toast with the limit on a 413 when the server reports one', async () => { @@ -214,6 +212,19 @@ describe('useNodeImageUpload', () => { }) }) + it('shows a localized upload-failed toast when the upload throws', async () => { + vi.mocked(api.fetchApi).mockRejectedValueOnce(new Error('Network error')) + + await capturedDragOnDrop([createFile()]) + + expect(t).toHaveBeenCalledWith('g.uploadFailed', { + reason: 'Network error' + }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'warning', title: 'g.uploadFailed' }) + ]) + }) + it('resets isUploading even when upload fails', async () => { vi.mocked(api.fetchApi).mockRejectedValueOnce(new Error('Network error')) @@ -233,9 +244,7 @@ describe('useNodeImageUpload', () => { const second = await capturedDragOnDrop([createFile('b.png')]) expect(second).toEqual([]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.uploadAlreadyInProgress' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.uploadAlreadyInProgress') await first }) diff --git a/src/composables/node/useNodeImageUpload.ts b/src/composables/node/useNodeImageUpload.ts index 7f22d9b6b2d..289185bfdb0 100644 --- a/src/composables/node/useNodeImageUpload.ts +++ b/src/composables/node/useNodeImageUpload.ts @@ -2,13 +2,14 @@ import { useNodeDragAndDrop } from '@/composables/node/useNodeDragAndDrop' import { useNodeFileInput } from '@/composables/node/useNodeFileInput' import { useNodePaste } from '@/composables/node/useNodePaste' import { t } from '@/i18n' -import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' -import { useToastStore } from '@/platform/updates/common/toastStore' +import type { LGraphNode } from '@/lib/litegraph/src/litegraph' +import { useToast } from '@/components/ui/toast/toastStore' import type { ResultItem } from '@/platform/remote/comfyui/execution/types' import type { ResultItemType } from '@/schemas/resultItemTypeSchema' import { useAssetsStore } from '@/stores/assetsStore' import { api } from '@/scripts/api' +import { getErrorMessage } from '@/utils/errorUtil' const UPLOAD_TIMEOUT_MS = 120_000 const BYTES_PER_MB = 1024 * 1024 @@ -53,7 +54,7 @@ const uploadFile = async ( }) if (resp.status !== 200) { - useToastStore().addAlert(buildUploadErrorMessage(resp)) + useToast().warning(buildUploadErrorMessage(resp)) return } @@ -104,16 +105,20 @@ export const useNodeImageUpload = ( return path } catch (error) { if (error instanceof DOMException && error.name === 'TimeoutError') { - useToastStore().addAlert(t('g.uploadTimedOut')) + useToast().warning(t('g.uploadTimedOut')) } else { - useToastStore().addAlert(String(error)) + useToast().warning( + t('g.uploadFailed', { + reason: getErrorMessage(error) ?? t('g.unknownError') + }) + ) } } } const handleUploadBatch = async (files: File[]) => { if (node.isUploading) { - useToastStore().addAlert(t('g.uploadAlreadyInProgress')) + useToast().warning(t('g.uploadAlreadyInProgress')) return [] } node.isUploading = true diff --git a/src/composables/painter/usePainter.test.ts b/src/composables/painter/usePainter.test.ts index c3ccfee64b2..1908194aa9f 100644 --- a/src/composables/painter/usePainter.test.ts +++ b/src/composables/painter/usePainter.test.ts @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { api } from '@/scripts/api' @@ -486,6 +487,12 @@ describe('usePainter', () => { await expect( widgetOf('mask').serializeValue!(paintNode(), 0) ).rejects.toThrow(/missing 'name'/) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'painter.uploadMissingName' + }) + ]) }) it('throws when the upload response body is not valid JSON', async () => { diff --git a/src/composables/painter/usePainter.ts b/src/composables/painter/usePainter.ts index 0e10ce5daae..7941f2c3066 100644 --- a/src/composables/painter/usePainter.ts +++ b/src/composables/painter/usePainter.ts @@ -13,13 +13,14 @@ import { setNodeWidgetValue } from '@/core/graph/widgets/nodeWidgetValues' import { hexToRgb } from '@/utils/colorUtil' import type { Point } from '@/extensions/core/maskeditor/types' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { app } from '@/scripts/app' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { NodeId } from '@/types/nodeId' import { widgetId } from '@/types/widgetId' +import { getErrorMessage } from '@/utils/errorUtil' type PainterTool = 'brush' | 'eraser' @@ -38,7 +39,7 @@ export function usePainter(nodeId: NodeId, options: UsePainterOptions) { const { canvasEl, cursorEl, modelValue } = options const { t } = useI18n() const nodeOutputStore = useNodeOutputStore() - const toastStore = useToastStore() + const toast = useToast() const isDirty = ref(false) @@ -631,9 +632,9 @@ export function usePainter(nodeId: NodeId, options: UsePainterOptions) { } catch (e) { const err = t('painter.uploadError', { status: 0, - statusText: e instanceof Error ? e.message : String(e) + statusText: getErrorMessage(e) ?? t('g.unknownError') }) - toastStore.addAlert(err) + toast.warning(err) throw new Error(err, { cause: e }) } @@ -643,7 +644,7 @@ export function usePainter(nodeId: NodeId, options: UsePainterOptions) { status: resp.status, statusText: bodyText || resp.statusText || 'unknown error' }) - toastStore.addAlert(err) + toast.warning(err) throw new Error(err) } @@ -653,16 +654,17 @@ export function usePainter(nodeId: NodeId, options: UsePainterOptions) { } catch (e) { const err = t('painter.uploadError', { status: resp.status, - statusText: e instanceof Error ? e.message : String(e) + statusText: getErrorMessage(e) ?? t('g.unknownError') }) - toastStore.addAlert(err) + toast.warning(err) throw new Error(err, { cause: e }) } if (!data.name) { - const detail = `Painter upload succeeded (${resp.status}) but response is missing 'name'` - toastStore.addAlert(detail) - throw new Error(detail) + toast.warning(t('painter.uploadMissingName')) + throw new Error( + `Painter upload succeeded (${resp.status}) but response is missing 'name'` + ) } const result = `${data.name} [input]` diff --git a/src/composables/useCameraAngle.test.ts b/src/composables/useCameraAngle.test.ts index c3b168fb610..cfe3329a22e 100644 --- a/src/composables/useCameraAngle.test.ts +++ b/src/composables/useCameraAngle.test.ts @@ -2,8 +2,8 @@ import { ref } from 'vue' import type { Ref } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' interface ViewportInstance { @@ -157,7 +157,13 @@ describe('useCameraAngle', () => { const camera = useCameraAngle(nodeRef(makeNode(DEFAULT_WIDGETS))) expect(() => camera.initialize(document.createElement('div'))).not.toThrow() - expect(useToastStore().addAlert).toHaveBeenCalledOnce() + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'warning', + title: + 'Failed to initialize Camera Angle viewer. Try reloading the page.' + }) + ) }) it('writes viewport interaction results back into the widgets', () => { diff --git a/src/composables/useCameraAngle.ts b/src/composables/useCameraAngle.ts index 10009f74d68..7c4370b5213 100644 --- a/src/composables/useCameraAngle.ts +++ b/src/composables/useCameraAngle.ts @@ -30,7 +30,7 @@ import { import type { NodeWithWidgets } from '@/extensions/core/cameraAngle/widgetBridge' import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' const IMAGE_INPUT_NAME = 'image' @@ -88,9 +88,7 @@ export function useCameraAngle( } catch (error) { console.error('Failed to initialize CameraAngleViewport:', error) cleanup() - useToastStore().addAlert( - t('toastMessages.failedToInitializeCameraAngleViewer') - ) + useToast().warning(t('toastMessages.failedToInitializeCameraAngleViewer')) } } diff --git a/src/composables/useCameraInfo.test.ts b/src/composables/useCameraInfo.test.ts index 0018b9814ec..2e052b90b71 100644 --- a/src/composables/useCameraInfo.test.ts +++ b/src/composables/useCameraInfo.test.ts @@ -1,9 +1,9 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { ref } from 'vue' import type { Ref } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' interface ViewportInstance { ctorArgs: unknown[] @@ -116,7 +116,13 @@ describe('useCameraInfo', () => { const camera = useCameraInfo(nodeRef(makeNode({ mode: 'orbit' }))) expect(() => camera.initialize(document.createElement('div'))).not.toThrow() - expect(useToastStore().addAlert).toHaveBeenCalledOnce() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: + 'Failed to initialize Camera Info viewer. Try reloading the page.' + }) + ]) }) it('forwards toolbar actions to the viewport', () => { diff --git a/src/composables/useCameraInfo.ts b/src/composables/useCameraInfo.ts index f39c9f6e559..65c49e2daed 100644 --- a/src/composables/useCameraInfo.ts +++ b/src/composables/useCameraInfo.ts @@ -16,7 +16,7 @@ import { import type { NodeWithWidgets } from '@/extensions/core/cameraInfo/widgetBridge' import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' const WIDGET_NAMES = [ 'mode', @@ -65,9 +65,7 @@ export function useCameraInfo(nodeRef: MaybeRef) { } catch (error) { console.error('Failed to initialize CameraInfoViewport:', error) cleanup() - useToastStore().addAlert( - t('toastMessages.failedToInitializeCameraInfoViewer') - ) + useToast().warning(t('toastMessages.failedToInitializeCameraInfoViewer')) } } diff --git a/src/composables/useCopyToClipboard.test.ts b/src/composables/useCopyToClipboard.test.ts index f30a1856b93..edd0e8f22cc 100644 --- a/src/composables/useCopyToClipboard.test.ts +++ b/src/composables/useCopyToClipboard.test.ts @@ -1,17 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -const mockWriteText = vi.fn() -const mockToastAdd = vi.fn() - -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports +import { useToast } from '@/components/ui/toast/toastStore' - () => ({ - useToast: vi.fn(() => ({ - add: mockToastAdd - })) - }) -) +const mockWriteText = vi.fn() vi.mock(import('@/i18n')) @@ -34,8 +25,8 @@ describe('useCopyToClipboard', () => { expect(copied).toBe(true) expect(mockWriteText).toHaveBeenCalledWith('hello') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'success' }) ) }) @@ -46,7 +37,7 @@ describe('useCopyToClipboard', () => { const copied = await copyToClipboard('hello', { toastOnSuccess: false }) expect(copied).toBe(true) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('falls back to legacy when modern clipboard fails', async () => { @@ -59,8 +50,8 @@ describe('useCopyToClipboard', () => { expect(copied).toBe(true) expect(document.execCommand).toHaveBeenCalledWith('copy') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'success' }) ) }) @@ -73,8 +64,8 @@ describe('useCopyToClipboard', () => { expect(copied).toBe(false) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) @@ -92,8 +83,8 @@ describe('useCopyToClipboard', () => { expect(mockWriteText).not.toHaveBeenCalled() expect(document.execCommand).toHaveBeenCalledWith('copy') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'success' }) ) }) }) diff --git a/src/composables/useCopyToClipboard.ts b/src/composables/useCopyToClipboard.ts index a03333f97bb..b5e6852e71c 100644 --- a/src/composables/useCopyToClipboard.ts +++ b/src/composables/useCopyToClipboard.ts @@ -1,4 +1,4 @@ -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' @@ -44,20 +44,16 @@ export function useCopyToClipboard() { if (success && !toastOnSuccess) return true - toast.add( - success - ? { - severity: 'success', - summary: t('g.success'), - detail: t('clipboard.successMessage'), - life: 3000 - } - : { - severity: 'error', - summary: t('g.error'), - detail: t('clipboard.errorMessage') - } - ) + if (success) { + toast.success(t('g.success'), { + description: t('clipboard.successMessage'), + duration: 3000 + }) + } else { + toast.error(t('g.error'), { + description: t('clipboard.errorMessage') + }) + } return success } diff --git a/src/composables/useCoreCommands.test.ts b/src/composables/useCoreCommands.test.ts index 2a1ac3cb872..368cc4a2573 100644 --- a/src/composables/useCoreCommands.test.ts +++ b/src/composables/useCoreCommands.test.ts @@ -1,4 +1,5 @@ import { useDialogService } from '@/services/dialogService' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -17,7 +18,6 @@ import { app } from '@/scripts/app' import { useModelStore } from '@/stores/modelStore' import { useMissingModelStore } from '@/platform/missingModel/missingModelStore' import { resetOnboardingState } from '@/platform/onboarding/onboardingReset' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' import { useLitegraphService } from '@/services/litegraphService' @@ -378,9 +378,7 @@ describe('useCoreCommands', () => { await findCommand().function() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() expect(location.assign).not.toHaveBeenCalled() expect(location.reload).not.toHaveBeenCalled() }) @@ -781,9 +779,7 @@ describe('useCoreCommands', () => { await findCmd('Comfy.QueueSelectedOutputNodes').function() expect(mockBillingState.showSubscriptionDialog).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() }) it.for([ @@ -816,9 +812,7 @@ describe('useCoreCommands', () => { expect(app.queuePrompt).not.toHaveBeenCalled() expect(mockBillingState.showSubscriptionDialog).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn' }) - ) + expect(useToast().warning).toHaveBeenCalled() } ) @@ -902,7 +896,7 @@ describe('useCoreCommands', () => { asset, 'asset_browser' ) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows an error toast when the asset cannot start a drag', async () => { @@ -914,9 +908,7 @@ describe('useCoreCommands', () => { await selectAssetFromBrowser() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() }) }) }) diff --git a/src/composables/useCoreCommands.ts b/src/composables/useCoreCommands.ts index 6934e54ce7b..83e8b717cd7 100644 --- a/src/composables/useCoreCommands.ts +++ b/src/composables/useCoreCommands.ts @@ -31,7 +31,7 @@ import { buildSupportUrl } from '@/platform/support/config' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' import type { ExecutionTriggerSource } from '@/platform/telemetry/types' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' @@ -88,11 +88,9 @@ export function useCoreCommands(): ComfyCommand[] { function blockRunWithoutSubscription(): boolean { if (!isCloud || canAccessSubscriptionFeatures.value) return false if (isSalesManagedTier(subscription.value?.tier)) { - toastStore.add({ - severity: 'warn', - summary: t('subscription.salesManagedRunBlockedTitle'), - detail: t('subscription.salesManagedRunBlockedDetail'), - life: 5000 + toast.warning(t('subscription.salesManagedRunBlockedTitle'), { + description: t('subscription.salesManagedRunBlockedDetail'), + duration: 5000 }) } else { showSubscriptionDialog({ reason: 'subscribe_to_run' }) @@ -105,7 +103,7 @@ export function useCoreCommands(): ComfyCommand[] { const dialogService = useDialogService() const colorPaletteStore = useColorPaletteStore() const authActions = useAuthActions() - const toastStore = useToastStore() + const toast = useToast() const canvasStore = useCanvasStore() const executionStore = useExecutionStore() const modelStore = useModelStore() @@ -348,11 +346,9 @@ export function useCoreCommands(): ComfyCommand[] { category: 'essentials' as const, function: async () => { await api.interrupt(executionStore.activeJobId) - toastStore.add({ - severity: 'info', - summary: t('g.interrupted'), - detail: t('toastMessages.interrupted'), - life: 1000 + toast.info(t('g.interrupted'), { + description: t('toastMessages.interrupted'), + duration: 1000 }) } }, @@ -363,11 +359,9 @@ export function useCoreCommands(): ComfyCommand[] { category: 'essentials' as const, function: async () => { await useQueueStore().clear(['queue']) - toastStore.add({ - severity: 'info', - summary: t('g.confirmed'), - detail: t('toastMessages.pendingTasksDeleted'), - life: 3000 + toast.info(t('g.confirmed'), { + description: t('toastMessages.pendingTasksDeleted'), + duration: 3000 }) } }, @@ -427,10 +421,7 @@ export function useCoreCommands(): ComfyCommand[] { category: 'view-controls' as const, function: () => { if (app.canvas.empty) { - toastStore.add({ - severity: 'error', - summary: t('toastMessages.emptyCanvas') - }) + toast.error(t('toastMessages.emptyCanvas')) return } app.canvas.fitViewToSelectionAnimated({ @@ -578,10 +569,8 @@ export function useCoreCommands(): ComfyCommand[] { const selectedOutputNodes = filterOutputNodes(selectedNodes) if (selectedOutputNodes.length === 0) { - toastStore.add({ - severity: 'error', - summary: t('toastMessages.nothingToQueue'), - detail: t('toastMessages.pleaseSelectOutputNodes') + toast.error(t('toastMessages.nothingToQueue'), { + description: t('toastMessages.pleaseSelectOutputNodes') }) return } @@ -591,10 +580,8 @@ export function useCoreCommands(): ComfyCommand[] { getExecutionIdsForSelectedNodes(selectedOutputNodes) if (executionIds.length === 0) { - toastStore.add({ - severity: 'error', - summary: t('toastMessages.failedToQueue'), - detail: t('toastMessages.failedExecutionPathResolution') + toast.error(t('toastMessages.failedToQueue'), { + description: t('toastMessages.failedExecutionPathResolution') }) return } @@ -625,10 +612,8 @@ export function useCoreCommands(): ComfyCommand[] { function: () => { const { canvas } = app if (!canvas.selectedItems.size) { - toastStore.add({ - severity: 'error', - summary: t('toastMessages.nothingToGroup'), - detail: t('toastMessages.pleaseSelectNodesToGroup') + toast.error(t('toastMessages.nothingToGroup'), { + description: t('toastMessages.pleaseSelectNodesToGroup') }) return } @@ -921,11 +906,9 @@ export function useCoreCommands(): ComfyCommand[] { const result = await resetOnboardingState() if (result.status === 'failed') { - toastStore.add({ - severity: 'error', - summary: t('onboardingReplay.failedSummary'), - detail: t('onboardingReplay.failedDetail'), - life: 5000 + toast.error(t('onboardingReplay.failedSummary'), { + description: t('onboardingReplay.failedDetail'), + duration: 5000 }) reportError(result.cause, { surface: 'platform', @@ -1039,10 +1022,8 @@ export function useCoreCommands(): ComfyCommand[] { // For DISABLED state, show error toast instead of opening settings if (state === ManagerUIState.DISABLED) { - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('manager.notAvailable') + toast.error(t('g.error'), { + description: t('manager.notAvailable') }) return } @@ -1332,10 +1313,8 @@ export function useCoreCommands(): ComfyCommand[] { versionAdded: '1.16.4', function: async () => { if (!useSettingStore().get('Comfy.Memory.AllowManualUnload')) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('g.commandProhibited', { + toast.error(t('g.error'), { + description: t('g.commandProhibited', { command: 'Comfy.Memory.UnloadModels' }) }) @@ -1351,10 +1330,8 @@ export function useCoreCommands(): ComfyCommand[] { versionAdded: '1.16.4', function: async () => { if (!useSettingStore().get('Comfy.Memory.AllowManualUnload')) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('g.commandProhibited', { + toast.error(t('g.error'), { + description: t('g.commandProhibited', { command: 'Comfy.Memory.UnloadModelsAndExecutionCache' }) }) diff --git a/src/composables/useErrorHandling.test.ts b/src/composables/useErrorHandling.test.ts index d39082e39ff..3d2d2167007 100644 --- a/src/composables/useErrorHandling.test.ts +++ b/src/composables/useErrorHandling.test.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ErrorRecoveryStrategy } from '@/composables/useErrorHandling' import { useErrorHandling } from '@/composables/useErrorHandling' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' describe('useErrorHandling', () => { let errorHandler: ReturnType @@ -332,13 +332,9 @@ describe('useErrorHandling', () => { const wrapped = errorHandler.wrapWithErrorHandlingAsync(action) await wrapped() - const toastStore = useToastStore() - expect(toastStore.add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: t('g.disconnectedFromBackend') - }) - ) + expect(useToast().error).toHaveBeenCalledWith(t('g.error'), { + description: t('g.disconnectedFromBackend') + }) }) it('should not treat non-TypeError as network error', async () => { @@ -349,12 +345,9 @@ describe('useErrorHandling', () => { const wrapped = errorHandler.wrapWithErrorHandlingAsync(action) await wrapped() - const toastStore = useToastStore() - expect(toastStore.add).toHaveBeenCalledWith( - expect.objectContaining({ - detail: 'Failed to fetch' - }) - ) + expect(useToast().error).toHaveBeenCalledWith(t('g.error'), { + description: 'Failed to fetch' + }) }) }) diff --git a/src/composables/useErrorHandling.ts b/src/composables/useErrorHandling.ts index 9bee2812df7..9a25537f7e1 100644 --- a/src/composables/useErrorHandling.ts +++ b/src/composables/useErrorHandling.ts @@ -1,5 +1,5 @@ import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' /** * Strategy for recovering from specific error conditions. @@ -50,7 +50,7 @@ export interface ErrorRecoveryStrategy< } export function useErrorHandling() { - const toast = useToastStore() + const toast = useToast() const toastErrorHandler = (error: unknown) => { const isNetworkError = error instanceof TypeError && @@ -60,11 +60,7 @@ export function useErrorHandling() { : error instanceof Error ? error.message : t('g.unknownError') - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: message - }) + toast.error(t('g.error'), { description: message }) console.error(error) } diff --git a/src/composables/useLoad3d.test.ts b/src/composables/useLoad3d.test.ts index 13910715940..04e4c852af9 100644 --- a/src/composables/useLoad3d.test.ts +++ b/src/composables/useLoad3d.test.ts @@ -20,7 +20,7 @@ import type { LGraph } from '@/lib/litegraph/src/LGraph' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import type { IWidget } from '@/lib/litegraph/src/types/widgets' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' import { createMockCanvasPointerEvent } from '@/utils/__tests__/canvasTestUtils' @@ -68,7 +68,6 @@ describe('useLoad3d', () => { afterEach(() => scope.stop()) let mockLoad3d: Partial let mockNode: LGraphNode - let mockToastStore: ReturnType beforeEach(() => { vi.mocked(api.getServerFeature).mockReturnValue(false) @@ -191,8 +190,6 @@ describe('useLoad3d', () => { return this }) vi.mocked(createLoad3d).mockImplementation(() => mockLoad3d as Load3d) - - mockToastStore = useToastStore() }) describe('initialization', () => { @@ -348,7 +345,7 @@ describe('useLoad3d', () => { await composable.initializeLoad3d(containerRef) - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToInitializeLoad3dViewer' ) }) @@ -825,7 +822,7 @@ describe('useLoad3d', () => { await composable.handleExportModel('glb') - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.no3dSceneToExport' ) }) @@ -842,7 +839,7 @@ describe('useLoad3d', () => { await composable.handleExportModel('glb') - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) }) @@ -1069,9 +1066,7 @@ describe('useLoad3d', () => { await composable.handleModelDrop(file) expect(mockLoad3d.loadModel).not.toHaveBeenCalled() - expect(mockToastStore.addAlert).toHaveBeenCalledWith( - 'toastMessages.no3dScene' - ) + expect(useToast().warning).toHaveBeenCalledWith('toastMessages.no3dScene') }) }) @@ -1785,7 +1780,7 @@ describe('useLoad3d', () => { expect(throwing).toHaveBeenCalledTimes(1) expect(after).toHaveBeenCalledTimes(1) expect(mockLoad3d.addEventListener).toHaveBeenCalled() - expect(mockToastStore.addAlert).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(console.error).toHaveBeenCalledWith( 'Load3d ready callback failed:', expect.any(Error) diff --git a/src/composables/useLoad3d.ts b/src/composables/useLoad3d.ts index 15ff51c94fe..c3efa79198f 100644 --- a/src/composables/useLoad3d.ts +++ b/src/composables/useLoad3d.ts @@ -33,7 +33,7 @@ import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import { LiteGraph } from '@/lib/litegraph/src/litegraph' import { useSettingStore } from '@/platform/settings/settingStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { api } from '@/scripts/api' import { app } from '@/scripts/app' @@ -286,9 +286,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { } } catch (error) { console.error('Error initializing Load3d:', error) - useToastStore().addAlert( - t('toastMessages.failedToInitializeLoad3dViewer') - ) + useToast().warning(t('toastMessages.failedToInitializeLoad3dViewer')) } } @@ -769,7 +767,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { showAsBackground: false } } - useToastStore().addAlert(t('toastMessages.failedToLoadHDRI')) + useToast().warning(t('toastMessages.failedToLoadHDRI')) } finally { loading.value = false loadingMessage.value = '' @@ -800,7 +798,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { const handleExportModel = async (format: string) => { if (!load3d) { - useToastStore().addAlert(t('toastMessages.no3dSceneToExport')) + useToast().warning(t('toastMessages.no3dSceneToExport')) return } @@ -808,7 +806,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { await load3d.exportModel(format) } catch (error) { console.error('Error exporting model:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: format.toUpperCase() }) @@ -818,7 +816,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { const handleModelDrop = async (file: File) => { if (!load3d) { - useToastStore().addAlert(t('toastMessages.no3dScene')) + useToast().warning(t('toastMessages.no3dScene')) return } @@ -839,7 +837,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { const uploadedPath = await Load3dUtils.uploadFile(file, subfolder) if (!uploadedPath) { - useToastStore().addAlert(t('toastMessages.fileUploadFailed')) + useToast().warning(t('toastMessages.fileUploadFailed')) return } @@ -865,7 +863,7 @@ export const useLoad3d = (nodeOrRef: MaybeRef) => { } } catch (error) { console.error('Model drop failed:', error) - useToastStore().addAlert(t('toastMessages.failedToLoadModel')) + useToast().warning(t('toastMessages.failedToLoadModel')) } finally { loading.value = false loadingMessage.value = '' diff --git a/src/composables/useLoad3dDrag.test.ts b/src/composables/useLoad3dDrag.test.ts index f1913103462..4410ca78735 100644 --- a/src/composables/useLoad3dDrag.test.ts +++ b/src/composables/useLoad3dDrag.test.ts @@ -3,7 +3,7 @@ import { ref } from 'vue' import { useLoad3dDrag } from '@/composables/useLoad3dDrag' import { SUPPORTED_EXTENSIONS } from '@/extensions/core/load3d/constants' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { createMockFileList } from '@/utils/__tests__/litegraphTestUtils' vi.mock(import('@/i18n')) @@ -30,12 +30,9 @@ function createMockDragEvent( } describe('useLoad3dDrag', () => { - let mockToastStore: ReturnType let mockOnModelDrop: (file: File) => void | Promise beforeEach(() => { - mockToastStore = useToastStore() - mockOnModelDrop = vi.fn() }) @@ -137,7 +134,7 @@ describe('useLoad3dDrag', () => { await handleDrop(event) expect(mockOnModelDrop).not.toHaveBeenCalled() - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'load3d.unsupportedFileType' ) }) @@ -217,7 +214,7 @@ describe('useLoad3dDrag', () => { await handleDrop(event) expect(mockOnModelDrop).not.toHaveBeenCalled() - expect(mockToastStore.addAlert).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) }) diff --git a/src/composables/useLoad3dDrag.ts b/src/composables/useLoad3dDrag.ts index 87a8292ec25..00f4474aa63 100644 --- a/src/composables/useLoad3dDrag.ts +++ b/src/composables/useLoad3dDrag.ts @@ -3,7 +3,7 @@ import type { MaybeRefOrGetter } from 'vue' import { SUPPORTED_EXTENSIONS } from '@/extensions/core/load3d/constants' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' interface UseLoad3dDragOptions { onModelDrop: (file: File) => void | Promise @@ -56,7 +56,7 @@ export function useLoad3dDrag(options: UseLoad3dDragOptions) { if (modelFile) { await options.onModelDrop(modelFile) } else { - useToastStore().addAlert(t('load3d.unsupportedFileType')) + useToast().warning(t('load3d.unsupportedFileType')) } } diff --git a/src/composables/useLoad3dViewer.test.ts b/src/composables/useLoad3dViewer.test.ts index 25eabc194b1..7d83dbf6eec 100644 --- a/src/composables/useLoad3dViewer.test.ts +++ b/src/composables/useLoad3dViewer.test.ts @@ -7,7 +7,7 @@ import Load3dUtils from '@/extensions/core/load3d/Load3dUtils' import { createLoad3d } from '@/extensions/core/load3d/createLoad3d' import type { LGraph } from '@/lib/litegraph/src/LGraph' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useLoad3dService } from '@/services/load3dService' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' import { api } from '@/scripts/api' @@ -68,7 +68,6 @@ describe('useLoad3dViewer', () => { let mockLoad3d: Partial let mockSourceLoad3d: Partial let mockLoad3dService: ReturnType - let mockToastStore: ReturnType let mockNode: LGraphNode beforeEach(() => { @@ -188,8 +187,6 @@ describe('useLoad3dViewer', () => { typeof useLoad3dService > vi.mocked(useLoad3dService).mockReturnValue(mockLoad3dService) - - mockToastStore = useToastStore() }) describe('initialization', () => { @@ -250,7 +247,7 @@ describe('useLoad3dViewer', () => { await viewer.initializeViewer(containerRef, mockSourceLoad3d as Load3d) - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToInitializeLoad3dViewer' ) }) @@ -272,7 +269,7 @@ describe('useLoad3dViewer', () => { viewer.backgroundColor.value = '#ff0000' await nextTick() - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToUpdateBackgroundColor' ) }) @@ -302,7 +299,7 @@ describe('useLoad3dViewer', () => { await viewer.exportModel('glb') - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) }) @@ -603,7 +600,7 @@ describe('useLoad3dViewer', () => { const file = new File([''], 'test.jpg', { type: 'image/jpeg' }) await viewer.handleBackgroundImageUpdate(file) - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToUploadBackgroundImage' ) }) @@ -688,9 +685,7 @@ describe('useLoad3dViewer', () => { const file = new File([''], 'whatever.glb') await viewer.handleModelDrop(file) - expect(mockToastStore.addAlert).toHaveBeenCalledWith( - 'toastMessages.no3dScene' - ) + expect(useToast().warning).toHaveBeenCalledWith('toastMessages.no3dScene') expect(mockLoad3d.loadModel).not.toHaveBeenCalled() }) @@ -705,7 +700,7 @@ describe('useLoad3dViewer', () => { const file = new File([''], 'whatever.glb') await viewer.handleModelDrop(file) - expect(mockToastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.fileUploadFailed' ) expect(mockLoad3d.loadModel).not.toHaveBeenCalled() @@ -848,6 +843,24 @@ describe('useLoad3dViewer', () => { expect(viewer.backgroundColor.value).toBe('#282828') }) + it('warns when loading another model into the standalone viewer fails', async () => { + const viewer = useLoad3dViewer() + const containerRef = document.createElement('div') + await viewer.initializeStandaloneViewer(containerRef, 'model1.glb') + vi.mocked(mockLoad3d.loadModel!).mockRejectedValueOnce( + new Error('parse failed') + ) + + await viewer.initializeStandaloneViewer(containerRef, 'model2.glb') + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'toastMessages.failedToLoadModel' + }) + ]) + }) + it('should save configuration during cleanup in standalone mode', async () => { const viewer = useLoad3dViewer() const containerRef = document.createElement('div') diff --git a/src/composables/useLoad3dViewer.ts b/src/composables/useLoad3dViewer.ts index 335d722c774..cae2c3d78d4 100644 --- a/src/composables/useLoad3dViewer.ts +++ b/src/composables/useLoad3dViewer.ts @@ -24,7 +24,7 @@ import type { } from '@/extensions/core/load3d/interfaces' import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { useLoad3dService } from '@/services/load3dService' @@ -166,8 +166,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setBackgroundColor(newColor) } catch (error) { console.error('Error updating background color:', error) - useToastStore().addAlert( - t('toastMessages.failedToUpdateBackgroundColor', { color: newColor }) + useToast().warning( + t('toastMessages.failedToUpdateBackgroundColor', { + color: newColor + }) ) } }) @@ -178,8 +180,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.toggleGrid(newValue) } catch (error) { console.error('Error toggling grid:', error) - useToastStore().addAlert( - t('toastMessages.failedToToggleGrid', { show: newValue ? 'on' : 'off' }) + useToast().warning( + t('toastMessages.failedToToggleGrid', { + show: newValue ? 'on' : 'off' + }) ) } }) @@ -190,8 +194,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.toggleCamera(newCameraType) } catch (error) { console.error('Error toggling camera:', error) - useToastStore().addAlert( - t('toastMessages.failedToToggleCamera', { camera: newCameraType }) + useToast().warning( + t('toastMessages.failedToToggleCamera', { + camera: newCameraType + }) ) } }) @@ -202,9 +208,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setFOV(newFov) } catch (error) { console.error('Error updating FOV:', error) - useToastStore().addAlert( - t('toastMessages.failedToUpdateFOV', { fov: newFov }) - ) + useToast().warning(t('toastMessages.failedToUpdateFOV', { fov: newFov })) } }) @@ -214,8 +218,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setLightIntensity(newValue) } catch (error) { console.error('Error updating light intensity:', error) - useToastStore().addAlert( - t('toastMessages.failedToUpdateLightIntensity', { intensity: newValue }) + useToast().warning( + t('toastMessages.failedToUpdateLightIntensity', { + intensity: newValue + }) ) } }) @@ -227,7 +233,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { hasBackgroundImage.value = !!newValue } catch (error) { console.error('Error updating background image:', error) - useToastStore().addAlert(t('toastMessages.failedToUpdateBackgroundImage')) + useToast().warning(t('toastMessages.failedToUpdateBackgroundImage')) } }) @@ -237,7 +243,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setBackgroundRenderMode(newValue) } catch (error) { console.error('Error updating background render mode:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToUpdateBackgroundRenderMode', { mode: newValue }) @@ -251,8 +257,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setUpDirection(newValue) } catch (error) { console.error('Error updating up direction:', error) - useToastStore().addAlert( - t('toastMessages.failedToUpdateUpDirection', { direction: newValue }) + useToast().warning( + t('toastMessages.failedToUpdateUpDirection', { + direction: newValue + }) ) } }) @@ -263,8 +271,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { load3d.setMaterialMode(newValue) } catch (error) { console.error('Error updating material mode:', error) - useToastStore().addAlert( - t('toastMessages.failedToUpdateMaterialMode', { mode: newValue }) + useToast().warning( + t('toastMessages.failedToUpdateMaterialMode', { + mode: newValue + }) ) } }) @@ -460,9 +470,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { setupAnimationEvents() } catch (error) { console.error('Error initializing Load3d viewer:', error) - useToastStore().addAlert( - t('toastMessages.failedToInitializeLoad3dViewer') - ) + useToast().warning(t('toastMessages.failedToInitializeLoad3dViewer')) } } @@ -509,7 +517,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { persistStandaloneThumbnail(modelUrl) } catch (error) { console.error('Error initializing standalone 3D viewer:', error) - useToastStore().addAlert(t('toastMessages.failedToLoadModel')) + useToast().warning(t('toastMessages.failedToLoadModel')) } } @@ -542,7 +550,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { persistStandaloneThumbnail(modelUrl) } catch (error) { console.error('Error loading model in standalone viewer:', error) - useToastStore().addAlert('Failed to load 3D model') + useToast().warning(t('toastMessages.failedToLoadModel')) } } @@ -604,8 +612,10 @@ export const useLoad3dViewer = (node?: LGraphNode) => { await load3d.exportModel(format) } catch (error) { console.error('Error exporting model:', error) - useToastStore().addAlert( - t('toastMessages.failedToExportModel', { format: format.toUpperCase() }) + useToast().warning( + t('toastMessages.failedToExportModel', { + format: format.toUpperCase() + }) ) } } @@ -775,7 +785,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { } if (!load3d) { - useToastStore().addAlert(t('toastMessages.no3dScene')) + useToast().warning(t('toastMessages.no3dScene')) return } @@ -792,7 +802,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { } } catch (error) { console.error('Error uploading background image:', error) - useToastStore().addAlert(t('toastMessages.failedToUploadBackgroundImage')) + useToast().warning(t('toastMessages.failedToUploadBackgroundImage')) } } @@ -803,7 +813,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { */ const handleModelDrop = async (file: File) => { if (!load3d) { - useToastStore().addAlert(t('toastMessages.no3dScene')) + useToast().warning(t('toastMessages.no3dScene')) return } @@ -814,7 +824,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { ) if (!uploadedPath) { - useToastStore().addAlert(t('toastMessages.fileUploadFailed')) + useToast().warning(t('toastMessages.fileUploadFailed')) return } @@ -840,7 +850,7 @@ export const useLoad3dViewer = (node?: LGraphNode) => { } } catch (error) { console.error('Model drop failed:', error) - useToastStore().addAlert(t('toastMessages.failedToLoadModel')) + useToast().warning(t('toastMessages.failedToLoadModel')) } } diff --git a/src/composables/usePaste.test.ts b/src/composables/usePaste.test.ts index 887455bda6c..26adcc04151 100644 --- a/src/composables/usePaste.test.ts +++ b/src/composables/usePaste.test.ts @@ -21,7 +21,7 @@ import type { import { useCopy } from '@/composables/useCopy' import { CANVAS_CLIPBOARD_KEY } from '@/lib/litegraph/src/canvas/clipboardStorage' import { app } from '@/scripts/app' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' import { createNode } from '@/utils/litegraphUtil' import { shouldIgnoreCopyPaste } from '@/workbench/eventHelpers' @@ -784,8 +784,8 @@ describe('usePaste', () => { await vi.waitFor(() => { expect(mockCanvas._deserializeItems).not.toHaveBeenCalled() expect(mockCanvas.pasteFromClipboard).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) } @@ -807,8 +807,8 @@ describe('usePaste', () => { await vi.waitFor(() => { expect(mockCanvas._deserializeItems).not.toHaveBeenCalled() expect(mockCanvas.pasteFromClipboard).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) }) @@ -837,8 +837,8 @@ describe('usePaste', () => { document.dispatchEvent(event) await vi.waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) expect(mockCanvas.pasteFromClipboard).not.toHaveBeenCalled() }) @@ -887,12 +887,12 @@ describe('usePaste', () => { paste(otherApp) expect(mockCanvas.pasteFromClipboard).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'info', - summary: 'Nothing to paste into this node' + kind: 'info', + title: 'Nothing to paste into this node' }) - ) + ]) }) it('runs the default paste only for the latest copy', () => { @@ -937,7 +937,7 @@ describe('usePaste', () => { paste(clipboardData) expect(mockCanvas.pasteFromClipboard).toHaveBeenCalledOnce() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) } ) }) diff --git a/src/composables/usePaste.ts b/src/composables/usePaste.ts index e7a3623c081..f18441e0f52 100644 --- a/src/composables/usePaste.ts +++ b/src/composables/usePaste.ts @@ -1,11 +1,11 @@ import { useEventListener } from '@vueuse/core' +import { useToast } from '@/components/ui/toast/toastStore' import { parseClipboardHtml } from '@/composables/useCopy' import { useErrorHandling } from '@/composables/useErrorHandling' import { t } from '@/i18n' import { CANVAS_CLIPBOARD_KEY } from '@/lib/litegraph/src/canvas/clipboardStorage' import type { LGraphCanvas, LGraphNode } from '@/lib/litegraph/src/litegraph' -import { useToastStore } from '@/platform/updates/common/toastStore' import { zClipboardItems } from '@/platform/workflow/validation/schemas/workflowSchema' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { app } from '@/scripts/app' @@ -311,10 +311,8 @@ export const usePaste = () => { if (!isMediaNodeSelected || holdsLatestCanvasCopy(html)) { canvas.pasteFromClipboard() } else { - useToastStore().add({ - severity: 'info', - summary: t('toastMessages.nothingToPasteIntoNode'), - life: 3000 + useToast().info(t('toastMessages.nothingToPasteIntoNode'), { + duration: 3000 }) } } diff --git a/src/composables/useReconnectingNotification.test.ts b/src/composables/useReconnectingNotification.test.ts index 9c62b2db318..687ffa75d4a 100644 --- a/src/composables/useReconnectingNotification.test.ts +++ b/src/composables/useReconnectingNotification.test.ts @@ -3,23 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, nextTick } from 'vue' import { createI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' import { useReconnectingNotification } from '@/composables/useReconnectingNotification' import { useSettingStore } from '@/platform/settings/settingStore' -const mockToastAdd = vi.fn() -const mockToastRemove = vi.fn() - -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - - () => ({ - useToast: () => ({ - add: mockToastAdd, - remove: mockToastRemove - }) - }) -) - function setupComposable(): ReturnType { const i18n = createI18n({ legacy: false, @@ -55,7 +42,7 @@ describe('useReconnectingNotification', () => { onReconnecting() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows error toast after delay', () => { @@ -64,10 +51,10 @@ describe('useReconnectingNotification', () => { onReconnecting() vi.advanceTimersByTime(2000) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'error', - summary: 'Reconnecting' + kind: 'error', + title: 'Reconnecting' }) ) }) @@ -80,8 +67,7 @@ describe('useReconnectingNotification', () => { onReconnected() vi.advanceTimersByTime(2000) - expect(mockToastAdd).not.toHaveBeenCalled() - expect(mockToastRemove).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('removes toast and shows success when reconnected after delay', () => { @@ -89,23 +75,15 @@ describe('useReconnectingNotification', () => { onReconnecting() vi.advanceTimersByTime(2000) - mockToastAdd.mockClear() - onReconnected() - expect(mockToastRemove).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - summary: 'Reconnecting' - }) - ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'success', - summary: 'Reconnected', - life: 2000 + kind: 'success', + title: 'Reconnected', + duration: 2000 }) - ) + ]) }) it('does nothing when toast is disabled via setting', () => { @@ -117,8 +95,7 @@ describe('useReconnectingNotification', () => { vi.advanceTimersByTime(1500) onReconnected() - expect(mockToastAdd).not.toHaveBeenCalled() - expect(mockToastRemove).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('does nothing when onReconnected is called without prior onReconnecting', () => { @@ -126,19 +103,20 @@ describe('useReconnectingNotification', () => { onReconnected() - expect(mockToastAdd).not.toHaveBeenCalled() - expect(mockToastRemove).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) - it('handles multiple reconnecting events without duplicating toasts', () => { - const { onReconnecting } = setupComposable() + it('shows one reconnecting toast across repeated disconnects and clears it on reconnect', () => { + const { onReconnecting, onReconnected } = setupComposable() onReconnecting() - vi.advanceTimersByTime(2000) // first toast fires - onReconnecting() // second reconnecting event - vi.advanceTimersByTime(2000) // second toast fires + vi.advanceTimersByTime(2000) + onReconnecting() + vi.advanceTimersByTime(2000) + expect(useToast().toasts.map(({ kind }) => kind)).toEqual(['error']) - expect(mockToastAdd).toHaveBeenCalledTimes(2) + onReconnected() + expect(useToast().toasts.map(({ kind }) => kind)).toEqual(['success']) }) describe('tab visibility regained', () => { @@ -166,12 +144,12 @@ describe('useReconnectingNotification', () => { // Would have fired under the original (unextended) delay by now. vi.advanceTimersByTime(1900) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) // Extended delay (5000ms) elapses from the point visibility was regained. vi.advanceTimersByTime(3100) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error', summary: 'Reconnecting' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error', title: 'Reconnecting' }) ) }) @@ -187,8 +165,7 @@ describe('useReconnectingNotification', () => { onReconnected() vi.advanceTimersByTime(5000) - expect(mockToastAdd).not.toHaveBeenCalled() - expect(mockToastRemove).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('reverts to the base delay once the post-visibility grace period elapses', async () => { @@ -201,8 +178,8 @@ describe('useReconnectingNotification', () => { onReconnecting() vi.advanceTimersByTime(2000) // base delay again, not the extended one - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error', summary: 'Reconnecting' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error', title: 'Reconnecting' }) ) }) }) diff --git a/src/composables/useReconnectingNotification.ts b/src/composables/useReconnectingNotification.ts index 65d9fd451e7..9300f9e1bd2 100644 --- a/src/composables/useReconnectingNotification.ts +++ b/src/composables/useReconnectingNotification.ts @@ -1,9 +1,9 @@ import { useDocumentVisibility, useTimeoutFn } from '@vueuse/core' -import type { ToastMessageOptions } from 'primevue/toast' -import { useToast } from 'primevue/usetoast' import { ref, watch } from 'vue' import { useI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' +import { createToastId } from '@/types/toastId' import { useSettingStore } from '@/platform/settings/settingStore' const RECONNECT_TOAST_DELAY_MS = 2000 @@ -16,18 +16,12 @@ export function useReconnectingNotification() { const toast = useToast() const settingStore = useSettingStore() - const reconnectingMessage: ToastMessageOptions = { - severity: 'error', - summary: t('g.reconnecting') - } - - const reconnectingToastShown = ref(false) const toastDelayMs = ref(RECONNECT_TOAST_DELAY_MS) + const reconnectingToastId = createToastId() const { start, stop, isPending } = useTimeoutFn( () => { - toast.add(reconnectingMessage) - reconnectingToastShown.value = true + toast.error(t('g.reconnecting'), { id: reconnectingToastId }) }, toastDelayMs, { immediate: false } @@ -59,14 +53,8 @@ export function useReconnectingNotification() { function onReconnected() { stop() - if (reconnectingToastShown.value) { - toast.remove(reconnectingMessage) - toast.add({ - severity: 'success', - summary: t('g.reconnected'), - life: 2000 - }) - reconnectingToastShown.value = false + if (toast.dismiss(reconnectingToastId)) { + toast.success(t('g.reconnected'), { duration: 2000 }) } } diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index 263738f844f..709acf2abf7 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -51,7 +51,7 @@ describe('useWorkspaceInsetRight', () => { expect(readInset()).toBe('0px') }) - it('stops publishing once the owning scope is torn down', async () => { + it('clears the inset once the owning scope is torn down', async () => { const width = ref(420) const scope = effectScope() scope.run(() => useWorkspaceInsetRight(() => width.value)) diff --git a/src/core/graph/subgraph/promotionUtils.ts b/src/core/graph/subgraph/promotionUtils.ts index ab7a6e42b95..a4a5e4957e4 100644 --- a/src/core/graph/subgraph/promotionUtils.ts +++ b/src/core/graph/subgraph/promotionUtils.ts @@ -9,7 +9,7 @@ import type { LinkId } from '@/types/linkId' import { reorderSubgraphInputs } from '@/lib/litegraph/src/subgraph/subgraphUtils' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { nextUniqueName } from '@/lib/litegraph/src/strings' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { CANVAS_IMAGE_PREVIEW_WIDGET, supportsVirtualCanvasImagePreview @@ -494,10 +494,8 @@ function getParentNodes(): SubgraphNode[] { const { navigationStack } = useSubgraphNavigationStore() const subgraph = navigationStack.at(-1) if (!subgraph) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('subgraphStore.promoteOutsideSubgraph') + useToast().error(t('g.error'), { + description: t('subgraphStore.promoteOutsideSubgraph') }) return [] } diff --git a/src/extensions/core/electronAdapter.ts b/src/extensions/core/electronAdapter.ts index b3f3be155eb..19f169f91a4 100644 --- a/src/extensions/core/electronAdapter.ts +++ b/src/extensions/core/electronAdapter.ts @@ -3,7 +3,7 @@ import log from 'loglevel' import { useExternalLink } from '@/composables/useExternalLink' import { PYTHON_MIRROR } from '@/constants/uvMirrors' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { app } from '@/scripts/app' import { useDialogService } from '@/services/dialogService' @@ -17,7 +17,7 @@ void (async () => { const electronAPI = getElectronAPI() const desktopAppVersion = await electronAPI.getElectronVersion() const workflowStore = useWorkflowStore() - const toastStore = useToastStore() + const toast = useToast() const { staticUrls, buildDocsUrl } = useExternalLink() const onChangeRestartApp = async (newValue: unknown, oldValue: unknown) => { @@ -182,10 +182,8 @@ void (async () => { }) if (!updateInfo.isUpdateAvailable) { - toastStore.add({ - severity: 'info', - summary: t('desktopUpdate.noUpdateFound'), - life: 5_000 + toast.info(t('desktopUpdate.noUpdateFound'), { + duration: 5_000 }) return } @@ -202,19 +200,15 @@ void (async () => { await electronAPI.restartAndInstall() } catch (error) { log.error('Error installing update:', error) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('desktopUpdate.errorInstallingUpdate') + toast.error(t('g.error'), { + description: t('desktopUpdate.errorInstallingUpdate') }) } } } catch (error) { log.error('Error checking for updates:', error) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('desktopUpdate.errorCheckingUpdate') + toast.error(t('g.error'), { + description: t('desktopUpdate.errorCheckingUpdate') }) } } diff --git a/src/extensions/core/load3d.test.ts b/src/extensions/core/load3d.test.ts index b40f3cbe210..128a6117c3e 100644 --- a/src/extensions/core/load3d.test.ts +++ b/src/extensions/core/load3d.test.ts @@ -1,11 +1,11 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn' +import { useToast } from '@/components/ui/toast/toastStore' import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent } from 'vue' import type { useLoad3d } from '@/composables/useLoad3d' import type { CameraState } from '@/extensions/core/load3d/interfaces' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { ComfyApp } from '@/scripts/app' import { app } from '@/scripts/app' @@ -141,10 +141,6 @@ vi.mock(import('@/utils/litegraphUtil'), () => ({ isLoad3dNode: vi.fn(() => true) })) -vi.mock(import('@/lib/litegraph/src/litegraph'), () => ({ - LiteGraph: fromPartial({ ContextMenu: fromAny(vi.fn()) }) -})) - await import('@/extensions/core/load3d') const load3DExt = capture.getExtension('Comfy.Load3D') const preview3DExt = capture.getExtension('Comfy.Preview3D') @@ -459,7 +455,7 @@ describe('Comfy.Preview3D.nodeCreated', () => { await preview3DExt.nodeCreated!(node, app) node.onExecuted!({ result: [] }) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.unableToGetModelFilePath' ) }) @@ -579,7 +575,7 @@ describe('Comfy.Load3D.getCustomWidgets LOAD_3D', () => { await flush() expect(load3d.loadModel).toHaveBeenCalledWith('/api/view') - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToLoadModel' ) }) @@ -1082,7 +1078,7 @@ describe('Comfy.Preview3DAdvanced.nodeCreated', () => { await preview3DAdvancedExt.nodeCreated!(node, app) node.onExecuted!({ result: [] }) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.unableToGetModelFilePath' ) expect(configureForSaveMeshMock).not.toHaveBeenCalled() diff --git a/src/extensions/core/load3d.ts b/src/extensions/core/load3d.ts index 23ac56ccd17..4eff4992f2c 100644 --- a/src/extensions/core/load3d.ts +++ b/src/extensions/core/load3d.ts @@ -37,7 +37,7 @@ import type { INumericWidget, IStringWidget } from '@/lib/litegraph/src/types/widgets' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { NodeExecutionOutput, NodeOutputWith @@ -94,7 +94,7 @@ async function handleModelUpload(files: FileList, node: LGraphNode) { const uploadPath = await Load3dUtils.uploadFile(files[0], subfolder) if (!uploadPath) { - useToastStore().addAlert(t('toastMessages.fileUploadFailed')) + useToast().warning(t('toastMessages.fileUploadFailed')) return } @@ -109,7 +109,7 @@ async function handleModelUpload(files: FileList, node: LGraphNode) { try { await load3d.loadModel(modelUrl) } catch { - useToastStore().addAlert(t('toastMessages.failedToLoadModel')) + useToast().warning(t('toastMessages.failedToLoadModel')) } }) @@ -124,7 +124,7 @@ async function handleModelUpload(files: FileList, node: LGraphNode) { markLoad3dSceneDirty(node) } catch (error) { console.error('Model upload failed:', error) - useToastStore().addAlert(t('toastMessages.fileUploadFailed')) + useToast().warning(t('toastMessages.fileUploadFailed')) } } @@ -142,7 +142,7 @@ async function handleResourcesUpload(files: FileList, node: LGraphNode) { markLoad3dSceneDirty(node) } catch (error) { console.error('Extra resources upload failed:', error) - useToastStore().addAlert(t('toastMessages.extraResourcesUploadFailed')) + useToast().warning(t('toastMessages.extraResourcesUploadFailed')) } } @@ -666,7 +666,7 @@ useExtensionService().registerExtension({ if (!filePath) { const msg = t('toastMessages.unableToGetModelFilePath') console.error(msg) - useToastStore().addAlert(msg) + useToast().warning(msg) } const cameraState = result?.[1] @@ -903,7 +903,7 @@ function createPreview3DAdvancedExtension( if (!reported) { const msg = t('toastMessages.unableToGetModelFilePath') console.error(msg) - useToastStore().addAlert(msg) + useToast().warning(msg) return } diff --git a/src/extensions/core/load3d/Load3dUtils.test.ts b/src/extensions/core/load3d/Load3dUtils.test.ts index d1c0507a0bc..8e5a9563f3c 100644 --- a/src/extensions/core/load3d/Load3dUtils.test.ts +++ b/src/extensions/core/load3d/Load3dUtils.test.ts @@ -1,6 +1,10 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import Load3dUtils from '@/extensions/core/load3d/Load3dUtils' +import { api } from '@/scripts/api' + +vi.mock(import('@/scripts/api')) describe('Load3dUtils.mapSceneLightIntensityToHdri', () => { it('maps scene slider low end to a small positive HDRI intensity', () => { @@ -23,3 +27,54 @@ describe('Load3dUtils.mapSceneLightIntensityToHdri', () => { expect(Load3dUtils.mapSceneLightIntensityToHdri(3, 5, 5)).toBe(0.25) }) }) + +describe('Load3dUtils upload failures', () => { + const serverError = () => + new Response(null, { status: 500, statusText: 'Internal Server Error' }) + + it('warns with a localized title when the model upload is rejected', async () => { + vi.mocked(api.fetchApi).mockResolvedValue(serverError()) + + await expect( + Load3dUtils.uploadFile(new File(['x'], 'mesh.glb'), '3d') + ).resolves.toBeUndefined() + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Upload failed: 500 - Internal Server Error' + }) + ]) + }) + + it('warns with a localized title when the model upload throws', async () => { + vi.mocked(api.fetchApi).mockRejectedValue(new Error('Network Error')) + + await expect( + Load3dUtils.uploadFile(new File(['x'], 'mesh.glb'), '3d') + ).resolves.toBeUndefined() + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Upload failed: Network Error' + }) + ]) + }) + + it('warns with a localized title and throws when the temp image upload is rejected', async () => { + vi.mocked(fetch).mockResolvedValue(new Response(new Blob())) + vi.mocked(api.fetchApi).mockResolvedValue(serverError()) + + await expect( + Load3dUtils.uploadTempImage('data:image/png;base64,', 'scene') + ).rejects.toThrow('Error uploading temp file: 500 - Internal Server Error') + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Upload failed: 500 - Internal Server Error' + }) + ]) + }) +}) diff --git a/src/extensions/core/load3d/Load3dUtils.ts b/src/extensions/core/load3d/Load3dUtils.ts index 6e5e5c9cfdc..111df119d8b 100644 --- a/src/extensions/core/load3d/Load3dUtils.ts +++ b/src/extensions/core/load3d/Load3dUtils.ts @@ -1,7 +1,9 @@ import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { app } from '@/scripts/app' +import { uploadTempFile } from '@/services/uploadTempFile' +import { getErrorMessage } from '@/utils/errorUtil' class Load3dUtils { static async uploadTempImage( @@ -15,23 +17,10 @@ class Load3dUtils { type: fileType === 'mp4' ? 'video/mp4' : 'image/png' }) - const body = new FormData() - body.append('image', file) - body.append('subfolder', 'threed') - body.append('type', 'temp') - - const resp = await api.fetchApi('/upload/image', { - method: 'POST', - body - }) - - if (resp.status !== 200) { - const err = `Error uploading temp file: ${resp.status} - ${resp.statusText}` - useToastStore().addAlert(err) - throw new Error(err) - } - - return await resp.json() + const upload = await uploadTempFile(file, 'threed') + if (!upload.ok) + throw new Error(`Error uploading temp file: ${upload.reason}`) + return upload.file } static readonly MAX_UPLOAD_SIZE_MB = 100 @@ -50,7 +39,7 @@ class Load3dUtils { fileSizeMB.toFixed(2), 'MB' ) - useToastStore().addAlert(message) + useToast().warning(message) return undefined } @@ -75,14 +64,18 @@ class Load3dUtils { uploadPath = path } else { - useToastStore().addAlert(resp.status + ' - ' + resp.statusText) + useToast().warning( + t('g.uploadFailed', { + reason: `${resp.status} - ${resp.statusText}` + }) + ) } } catch (error) { console.error('[Load3D] uploadFile: exception', error) - useToastStore().addAlert( - error instanceof Error - ? error.message - : t('toastMessages.fileUploadFailed') + useToast().warning( + t('g.uploadFailed', { + reason: getErrorMessage(error) ?? t('g.unknownError') + }) ) } diff --git a/src/extensions/core/load3d/LoaderManager.test.ts b/src/extensions/core/load3d/LoaderManager.test.ts index 7c35cf96585..08736d9d1d0 100644 --- a/src/extensions/core/load3d/LoaderManager.test.ts +++ b/src/extensions/core/load3d/LoaderManager.test.ts @@ -1,8 +1,8 @@ +import { useToast } from '@/components/ui/toast/toastStore' import * as THREE from 'three' import { fromAny } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { useToastStore } from '@/platform/updates/common/toastStore' import { isGaussianSplatPLY } from '@/scripts/metadata/ply' import type { @@ -349,7 +349,7 @@ describe('LoaderManager', () => { await lm.loadModel('api/view?other=1') - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.couldNotDetermineFileType' ) expect(modelManager.setupModel).not.toHaveBeenCalled() @@ -513,7 +513,7 @@ describe('LoaderManager', () => { 'modelLoadingEnd', null ) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.errorLoadingModel' ) expect(console.error).toHaveBeenCalled() @@ -531,7 +531,7 @@ describe('LoaderManager', () => { }) expect(console.error).toHaveBeenCalled() - expect(useToastStore().addAlert).not.toHaveBeenCalledWith( + expect(useToast().warning).not.toHaveBeenCalledWith( 'toastMessages.errorLoadingModel' ) }) @@ -547,7 +547,7 @@ describe('LoaderManager', () => { silentOnNotFound: true }) - expect(useToastStore().addAlert).not.toHaveBeenCalledWith( + expect(useToast().warning).not.toHaveBeenCalledWith( 'toastMessages.errorLoadingModel' ) }) @@ -560,7 +560,7 @@ describe('LoaderManager', () => { silentOnNotFound: true }) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.errorLoadingModel' ) }) @@ -665,7 +665,7 @@ describe('LoaderManager', () => { await Promise.all([firstPromise, secondPromise]) - expect(useToastStore().addAlert).not.toHaveBeenCalled() + expect(useToast().warning).not.toHaveBeenCalled() const endEmits = eventManager.emitEvent.mock.calls.filter( (call: unknown[]) => call[0] === 'modelLoadingEnd' ) diff --git a/src/extensions/core/load3d/LoaderManager.ts b/src/extensions/core/load3d/LoaderManager.ts index a160297ae68..441de80fa46 100644 --- a/src/extensions/core/load3d/LoaderManager.ts +++ b/src/extensions/core/load3d/LoaderManager.ts @@ -1,7 +1,7 @@ import type * as THREE from 'three' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { MeshModelAdapter } from './MeshModelAdapter' import { createAdapterRef, fetchModelData } from './ModelAdapter' @@ -112,7 +112,7 @@ export class LoaderManager implements LoaderManagerInterface { } if (!fileExtension) { - useToastStore().addAlert(t('toastMessages.couldNotDetermineFileType')) + useToast().warning(t('toastMessages.couldNotDetermineFileType')) return } @@ -140,7 +140,7 @@ export class LoaderManager implements LoaderManagerInterface { this.eventManager.emitEvent('modelLoadingEnd', null) console.error('Error loading model:', error) if (!(options?.silentOnNotFound && isNotFoundError(error))) { - useToastStore().addAlert(t('toastMessages.errorLoadingModel')) + useToast().warning(t('toastMessages.errorLoadingModel')) } } } diff --git a/src/extensions/core/load3d/ModelExporter.test.ts b/src/extensions/core/load3d/ModelExporter.test.ts index 7f1c6561036..06342c8eaff 100644 --- a/src/extensions/core/load3d/ModelExporter.test.ts +++ b/src/extensions/core/load3d/ModelExporter.test.ts @@ -1,10 +1,10 @@ -import * as THREE from 'three' import { fromAny } from '@total-typescript/shoehorn' +import * as THREE from 'three' import { describe, expect, it, vi } from 'vitest' import { downloadBlob } from '@/base/common/downloadUtil' +import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' import { ModelExporter } from './ModelExporter' @@ -141,7 +141,7 @@ describe('ModelExporter', () => { await expect( ModelExporter.downloadFromURL('http://example.com/cube.glb', 'cube.glb') ).rejects.toThrow('network') - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToDownloadFile' ) vi.unstubAllGlobals() @@ -156,7 +156,7 @@ describe('ModelExporter', () => { ModelExporter.downloadFromURL('http://example.com/cube.glb', 'cube.glb') ).rejects.toThrow('HTTP 404') expect(downloadBlob).not.toHaveBeenCalled() - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToDownloadFile' ) vi.unstubAllGlobals() @@ -211,7 +211,7 @@ describe('ModelExporter', () => { const settled = Promise.allSettled([promise]) await vi.runAllTimersAsync() expect(await settled).toMatchObject([rejectedWith('parse fail')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) expect(t).toHaveBeenCalledWith('toastMessages.failedToExportModel', { @@ -256,7 +256,7 @@ describe('ModelExporter', () => { const settled = Promise.allSettled([promise]) await vi.runAllTimersAsync() expect(await settled).toMatchObject([rejectedWith('obj fail')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) expect(t).toHaveBeenCalledWith('toastMessages.failedToExportModel', { @@ -301,7 +301,7 @@ describe('ModelExporter', () => { const settled = Promise.allSettled([promise]) await vi.runAllTimersAsync() expect(await settled).toMatchObject([rejectedWith('stl fail')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) expect(t).toHaveBeenCalledWith('toastMessages.failedToExportModel', { @@ -330,7 +330,7 @@ describe('ModelExporter', () => { ModelExporter.exportDirect(null, 'out.spz', 'spz') ).rejects.toThrow('No source file available to export as spz') expect(downloadBlob).not.toHaveBeenCalled() - expect(useToastStore().addAlert).not.toHaveBeenCalled() + expect(useToast().warning).not.toHaveBeenCalled() }) }) @@ -369,7 +369,7 @@ describe('ModelExporter', () => { const settled = Promise.allSettled([promise]) await vi.runAllTimersAsync() expect(await settled).toMatchObject([rejectedWith('fbx fail')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.failedToExportModel' ) expect(t).toHaveBeenCalledWith('toastMessages.failedToExportModel', { diff --git a/src/extensions/core/load3d/ModelExporter.ts b/src/extensions/core/load3d/ModelExporter.ts index 6d340008713..112d9255523 100644 --- a/src/extensions/core/load3d/ModelExporter.ts +++ b/src/extensions/core/load3d/ModelExporter.ts @@ -6,7 +6,7 @@ import { STLExporter } from 'three/examples/jsm/exporters/STLExporter' import { downloadBlob } from '@/base/common/downloadUtil' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' export class ModelExporter { static detectFormatFromURL(url: string): string | null { @@ -46,7 +46,7 @@ export class ModelExporter { downloadBlob(desiredFilename, blob) } catch (error) { console.error('Error downloading from URL:', error) - useToastStore().addAlert(t('toastMessages.failedToDownloadFile')) + useToast().warning(t('toastMessages.failedToDownloadFile')) throw error } } @@ -83,7 +83,7 @@ export class ModelExporter { ModelExporter.saveArrayBuffer(result, filename) } catch (error) { console.error('Error exporting GLB:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: 'GLB' }) ) throw error @@ -111,7 +111,7 @@ export class ModelExporter { ModelExporter.saveString(result, filename) } catch (error) { console.error('Error exporting OBJ:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: 'OBJ' }) ) throw error @@ -146,7 +146,7 @@ export class ModelExporter { ) } catch (error) { console.error('Error exporting FBX:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: 'FBX' }) ) throw error @@ -174,7 +174,7 @@ export class ModelExporter { ModelExporter.saveString(result, filename) } catch (error) { console.error('Error exporting STL:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: 'STL' }) ) throw error diff --git a/src/extensions/core/load3d/exportMenuHelper.test.ts b/src/extensions/core/load3d/exportMenuHelper.test.ts index 99d296649f1..0df7c8d77b5 100644 --- a/src/extensions/core/load3d/exportMenuHelper.test.ts +++ b/src/extensions/core/load3d/exportMenuHelper.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' import { LiteGraph } from '@/lib/litegraph/src/litegraph' import type Load3d from './Load3d' @@ -106,17 +106,14 @@ describe('createExportMenuItems', () => { item.callback() await vi.waitFor(() => expect(exportModel).toHaveBeenCalledWith(value)) await vi.waitFor(() => - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'success', - summary: 'toastMessages.exportSuccess' - }) + expect(useToast().success).toHaveBeenCalledWith( + 'toastMessages.exportSuccess' ) ) expect(t).toHaveBeenCalledWith('toastMessages.exportSuccess', { format: label }) - expect(useToastStore().addAlert).not.toHaveBeenCalled() + expect(useToast().warning).not.toHaveBeenCalled() } ) @@ -136,9 +133,12 @@ describe('createExportMenuItems', () => { glb.callback() await vi.waitFor(() => - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'toastMessages.failedToExportModel' - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'toastMessages.failedToExportModel' + }) + ]) ) expect(t).toHaveBeenCalledWith('toastMessages.failedToExportModel', { format: 'GLB' @@ -147,6 +147,5 @@ describe('createExportMenuItems', () => { 'Export failed:', expect.any(Error) ) - expect(useToastStore().add).not.toHaveBeenCalled() }) }) diff --git a/src/extensions/core/load3d/exportMenuHelper.ts b/src/extensions/core/load3d/exportMenuHelper.ts index 871648f6385..88d0a8edb9d 100644 --- a/src/extensions/core/load3d/exportMenuHelper.ts +++ b/src/extensions/core/load3d/exportMenuHelper.ts @@ -1,6 +1,6 @@ import { t } from '@/i18n' import type { IContextMenuValue } from '@/lib/litegraph/src/types/contextMenu' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type Load3d from '@/extensions/core/load3d/Load3d' import { LiteGraph } from '@/lib/litegraph/src/litegraph' @@ -31,15 +31,14 @@ export function createExportMenuItems( void (async () => { try { await load3d.exportModel(format.value) - useToastStore().add({ - severity: 'success', - summary: t('toastMessages.exportSuccess', { + useToast().success( + t('toastMessages.exportSuccess', { format: format.label }) - }) + ) } catch (error) { console.error('Export failed:', error) - useToastStore().addAlert( + useToast().warning( t('toastMessages.failedToExportModel', { format: format.label }) diff --git a/src/extensions/core/load3dPreviewExtensions.test.ts b/src/extensions/core/load3dPreviewExtensions.test.ts index dd2ba97aaba..be5be669fda 100644 --- a/src/extensions/core/load3dPreviewExtensions.test.ts +++ b/src/extensions/core/load3dPreviewExtensions.test.ts @@ -1,9 +1,9 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn' +import { useToast } from '@/components/ui/toast/toastStore' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { useLoad3d } from '@/composables/useLoad3d' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' import { app } from '@/scripts/app' import type { useExtensionService } from '@/services/extensionService' import type { useLoad3dService } from '@/services/load3dService' @@ -412,7 +412,7 @@ describe('Comfy.PreviewGaussianSplat.nodeCreated', () => { await splatExt.nodeCreated!(node, app) node.onExecuted!({ result: [] }) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'toastMessages.unableToGetModelFilePath' ) }) diff --git a/src/extensions/core/load3dPreviewExtensions.ts b/src/extensions/core/load3dPreviewExtensions.ts index b1fa6ea19fa..e825e46b1d4 100644 --- a/src/extensions/core/load3dPreviewExtensions.ts +++ b/src/extensions/core/load3dPreviewExtensions.ts @@ -14,7 +14,7 @@ import { readModel3DOutput } from '@/extensions/core/load3d/model3dOutput' import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import type { IContextMenuValue } from '@/lib/litegraph/src/types/contextMenu' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { NodeExecutionOutput } from '@/platform/remote/comfyui/execution/types' import { app } from '@/scripts/app' import { useExtensionService } from '@/services/extensionService' @@ -201,7 +201,7 @@ function createPreview3DExtension( if (!reported) { const msg = t('toastMessages.unableToGetModelFilePath') console.error(msg) - useToastStore().addAlert(msg) + useToast().warning(msg) return } diff --git a/src/extensions/core/nodeTemplates.ts b/src/extensions/core/nodeTemplates.ts index a0d287aea81..d099579716c 100644 --- a/src/extensions/core/nodeTemplates.ts +++ b/src/extensions/core/nodeTemplates.ts @@ -3,10 +3,11 @@ import { t } from '@/i18n' import type { IContextMenuValue } from '@/lib/litegraph/src/types/contextMenu' import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogService } from '@/services/dialogService' import type { ComfyExtension } from '@/types/comfy' import { deserialiseAndCreate } from '@/utils/vintageClipboard' +import { getErrorMessage } from '@/utils/errorUtil' import { api } from '../../scripts/api' import { app } from '../../scripts/app' @@ -126,9 +127,9 @@ class ManageTemplates extends ComfyDialog { await api.storeUserData(file, templates, { stringify: false }) } catch (error) { console.error(error) - useToastStore().addAlert( - error instanceof Error ? error.message : String(error) - ) + useToast().warning(t('toastMessages.failedToSaveNodeTemplates'), { + description: getErrorMessage(error) ?? t('g.unknownError') + }) } } @@ -158,7 +159,7 @@ class ManageTemplates extends ComfyDialog { exportAll() { if (this.templates.length == 0) { - useToastStore().addAlert(t('toastMessages.noTemplatesToExport')) + useToast().warning(t('toastMessages.noTemplatesToExport')) return } @@ -406,7 +407,7 @@ const ext: ComfyExtension = { data = JSON.parse(template.data) } catch (error) { console.error('Failed to parse node template data', error) - useToastStore().addAlert(t('toastMessages.invalidTemplateData')) + useToast().warning(t('toastMessages.invalidTemplateData')) return } diff --git a/src/extensions/core/uploadAudio.test.ts b/src/extensions/core/uploadAudio.test.ts index a90820820cd..c0ac7d33154 100644 --- a/src/extensions/core/uploadAudio.test.ts +++ b/src/extensions/core/uploadAudio.test.ts @@ -1,11 +1,12 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import { api } from '@/scripts/api' import { app } from '@/scripts/app' import type { useAudioService } from '@/services/audioService' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { reportError } from '@/platform/telemetry/reportError' const { @@ -214,9 +215,7 @@ describe('Comfy.UploadAudio AUDIOUPLOAD widget', () => { const result = await capturedDragDrop!([createFile()]) expect(result).toEqual([]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.uploadAlreadyInProgress' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.uploadAlreadyInProgress') expect(api.fetchApi).not.toHaveBeenCalled() }) @@ -230,7 +229,10 @@ describe('Comfy.UploadAudio AUDIOUPLOAD widget', () => { expect(node.isUploading).toBe(false) expect(audioWidget.value).toBe('previous.mp3') - expect(useToastStore().addAlert).toHaveBeenCalledWith('500 - Server Error') + expect(useToast().warning).toHaveBeenCalledWith('g.uploadFailed') + expect(t).toHaveBeenCalledWith('g.uploadFailed', { + reason: '500 - Server Error' + }) expect(node.graph?.setDirtyCanvas).toHaveBeenCalledWith(true) }) @@ -247,7 +249,8 @@ describe('Comfy.UploadAudio AUDIOUPLOAD widget', () => { expect(node.isUploading).toBe(false) expect(audioWidget.value).toBe('previous.mp3') - expect(useToastStore().addAlert).toHaveBeenCalledWith(error.message) + expect(useToast().warning).toHaveBeenCalledWith('g.uploadFailed') + expect(t).toHaveBeenCalledWith('g.uploadFailed', { reason: error.message }) expect(node.graph?.setDirtyCanvas).toHaveBeenCalledWith(true) }) @@ -342,7 +345,7 @@ describe('Comfy.RecordAudio AUDIO_RECORD widget', () => { expect(mockMediaRecorderStart).toHaveBeenCalledTimes(1) expect(recordWidget.label).toBe('g.stopRecording') expect(reportError).not.toHaveBeenCalled() - expect(useToastStore().addAlert).not.toHaveBeenCalled() + expect(useToast().warning).not.toHaveBeenCalled() }) it('reports a recorder start failure after the microphone was granted', async () => { @@ -385,12 +388,8 @@ describe('Comfy.RecordAudio AUDIO_RECORD widget', () => { RECORDER_FAILURE_REPORT ) expect(mockStopAllTracks).toHaveBeenCalledWith(stream) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.recordingFailedToStart' - ) - expect(useToastStore().addAlert).not.toHaveBeenCalledWith( - 'g.micPermissionDenied' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.recordingFailedToStart') + expect(useToast().warning).not.toHaveBeenCalledWith('g.micPermissionDenied') expect(recordWidget.label).toBe('g.startRecording') }) @@ -407,9 +406,7 @@ describe('Comfy.RecordAudio AUDIO_RECORD widget', () => { await pressRecord() - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.micPermissionDenied' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.micPermissionDenied') expect(reportError).not.toHaveBeenCalled() expect(mockMediaRecorderConstruct).not.toHaveBeenCalled() }) @@ -426,12 +423,8 @@ describe('Comfy.RecordAudio AUDIO_RECORD widget', () => { accessError, RECORDER_FAILURE_REPORT ) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'g.recordingFailedToStart' - ) - expect(useToastStore().addAlert).not.toHaveBeenCalledWith( - 'g.micPermissionDenied' - ) + expect(useToast().warning).toHaveBeenCalledWith('g.recordingFailedToStart') + expect(useToast().warning).not.toHaveBeenCalledWith('g.micPermissionDenied') expect(mockMediaRecorderConstruct).not.toHaveBeenCalled() }) }) diff --git a/src/extensions/core/uploadAudio.ts b/src/extensions/core/uploadAudio.ts index 014b615560a..d14886199e1 100644 --- a/src/extensions/core/uploadAudio.ts +++ b/src/extensions/core/uploadAudio.ts @@ -11,7 +11,7 @@ import type { IStringWidget } from '@/lib/litegraph/src/types/widgets' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { getResourceURL, splitFilePath @@ -22,7 +22,7 @@ import type { DOMWidget } from '@/scripts/domWidget' import { useAudioService } from '@/services/audioService' import type { NodeLocatorId } from '@/types' import { widgetId } from '@/types/widgetId' -import { toError } from '@/utils/errorUtil' +import { getErrorMessage } from '@/utils/errorUtil' import { getNodeByLocatorId } from '@/utils/graphTraversalUtil' import { api } from '../../scripts/api' @@ -84,11 +84,17 @@ async function uploadFile( } return true } else { - useToastStore().addAlert(resp.status + ' - ' + resp.statusText) + useToast().warning( + t('g.uploadFailed', { reason: `${resp.status} - ${resp.statusText}` }) + ) return false } } catch (error) { - useToastStore().addAlert(toError(error).message) + useToast().warning( + t('g.uploadFailed', { + reason: getErrorMessage(error) ?? t('g.unknownError') + }) + ) return false } } @@ -249,7 +255,7 @@ app.registerExtension({ if (!files.length) return files if (node.isUploading) { - useToastStore().addAlert(t('g.uploadAlreadyInProgress')) + useToast().warning(t('g.uploadAlreadyInProgress')) return [] } @@ -346,7 +352,7 @@ app.registerExtension({ }, level: 'error' }) - useToastStore().addAlert(t('g.recordingFailedToStart')) + useToast().warning(t('g.recordingFailedToStart')) if (mediaRecorder) { try { @@ -378,7 +384,7 @@ app.registerExtension({ const audioSrc = audioUIWidget.element.src if (!audioSrc) { - useToastStore().addAlert(t('g.noAudioRecorded')) + useToast().warning(t('g.noAudioRecorded')) return '' } @@ -407,7 +413,7 @@ app.registerExtension({ err.name === 'NotAllowedError' ) { console.error('Error accessing microphone:', err) - useToastStore().addAlert(t('g.micPermissionDenied')) + useToast().warning(t('g.micPermissionDenied')) useAudioService().stopAllTracks(currentStream) currentStream = null } else { diff --git a/src/extensions/core/webcamCapture.ts b/src/extensions/core/webcamCapture.ts index 316569e13bc..3aa56d9681e 100644 --- a/src/extensions/core/webcamCapture.ts +++ b/src/extensions/core/webcamCapture.ts @@ -1,9 +1,9 @@ import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' +import { uploadTempFile } from '@/services/uploadTempFile' -import { api } from '../../scripts/api' import { app } from '../../scripts/app' const webcamReady = new WeakMap>() @@ -124,9 +124,8 @@ app.registerExtension({ if (captureOnQueue.value) { capture() } else if (!node.imgs?.length) { - const err = `No webcam image captured` - useToastStore().addAlert(err) - throw new Error(err) + useToast().warning(t('toastMessages.noWebcamImageCaptured')) + throw new Error('No webcam image captured') } // Upload image to temp storage @@ -137,20 +136,10 @@ app.registerExtension({ ) const name = `${+new Date()}.png` const file = new File([blob], name) - const body = new FormData() - body.append('image', file) - body.append('subfolder', 'webcam') - body.append('type', 'temp') - const resp = await api.fetchApi('/upload/image', { - method: 'POST', - body - }) - if (resp.status !== 200) { - const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}` - useToastStore().addAlert(err) - throw new Error(err) - } - const data = await resp.json() + const upload = await uploadTempFile(file, 'webcam') + if (!upload.ok) + throw new Error(`Error uploading camera image: ${upload.reason}`) + const data = upload.file const serverName = data.name || name const subfolder = data.subfolder || 'webcam' const type = data.type || 'temp' diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 8f9cda49af6..ab667c31bd9 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -264,7 +264,7 @@ "community": "Community", "all": "All", "versionMismatchWarning": "Version Compatibility Warning", - "versionMismatchWarningMessage": "{warning}: {detail} Visit https://docs.comfy.org/installation/update_comfyui#common-update-issues for update instructions.", + "versionMismatchUpdateInstructions": "{detail} Visit https://docs.comfy.org/installation/update_comfyui#common-update-issues for update instructions.", "frontendOutdated": "Frontend version {frontendVersion} is outdated. Backend requires {requiredVersion} or higher.", "frontendNewer": "Frontend version {frontendVersion} may not be compatible with backend version {backendVersion}.", "comfyPackageOutdated": "Installed {name} version {installedVersion} is lower than the required version {requiredVersion}.", @@ -2411,7 +2411,8 @@ "height": "Height", "background": "Background", "clear": "Clear", - "uploadError": "Failed to upload painter image: {status} - {statusText}" + "uploadError": "Failed to upload painter image: {status} - {statusText}", + "uploadMissingName": "Painter image upload returned no file name" }, "boundingBox": { "x": "X", @@ -2554,6 +2555,15 @@ }, "toastMessages": { "nothingToPasteIntoNode": "Nothing to paste into this node", + "notificationsLabel": "Notification", + "notificationsViewportLabel": "Notifications ({hotkey})", + "modelsAndCacheCleared": "Models and Execution Cache have been cleared.", + "modelsUnloaded": "Models have been unloaded.", + "unloadModelsFailed": "Unloading of models failed. Installed ComfyUI may be an outdated version.", + "unloadModelsError": "An error occurred while trying to unload models.", + "workflowLinksFixed": "Fixed {patched} node connections and removed {deleted} invalid links.", + "workflowLinksFixedTitle": "Workflow Links Fixed", + "workflowValidationTitle": "Workflow Validation", "nothingToQueue": "Nothing to queue", "pleaseSelectOutputNodes": "Please select output nodes", "failedToQueue": "Failed to queue", @@ -2568,6 +2578,7 @@ "a1111CoreNodesUnavailable": "Could not load the workflow because this ComfyUI installation is missing core nodes. Check that the backend started correctly.", "a1111EmbeddingsUnavailable": "Embeddings could not be loaded from the server. The workflow was imported, but embedding names were left as plain text.", "dropFileError": "Unable to process dropped item: {error}", + "failedToRegisterSubgraph": "Failed to register subgraph", "assetDropFailed": "Unable to load the dropped asset", "missingMediaVerificationFailed": "Failed to verify missing media. Some inputs may not be shown in the Issues tab.", "missingModelVerificationFailed": "Failed to verify missing models. Some models may not be shown in the Issues tab.", @@ -2578,6 +2589,7 @@ "emptyCanvas": "Empty canvas", "fileUploadFailed": "File upload failed", "extraResourcesUploadFailed": "Extra resources upload failed", + "noWebcamImageCaptured": "No webcam image captured", "fileTooLarge": "File too large ({size} MB). Maximum supported size is {maxSize} MB", "unableToGetModelFilePath": "Unable to get model file path", "couldNotDetermineFileType": "Could not determine file type", @@ -2591,6 +2603,7 @@ "errorOpenImage": "Error opening image: {error}", "noTemplatesToExport": "No templates to export", "invalidTemplateData": "Failed to load node template: invalid data", + "failedToSaveNodeTemplates": "Failed to save node templates", "failedToFetchLogs": "Failed to fetch server logs", "migrateToLitegraphReroute": "Reroute nodes will be removed in future versions. Click to migrate to litegraph-native reroute.", "legacyMaskEditorDeprecated": "The legacy mask editor is deprecated and will be removed soon.", @@ -3019,6 +3032,9 @@ "cancelTimeout": "Subscription cancellation timed out" }, "subscription": { + "planNotAvailable": "This plan is not available", + "previewLoadFailed": "Failed to load subscription preview", + "unableToSubscribe": "Unable to subscribe", "billingTabBlocked": "Couldn't open the billing page. Allow pop-ups for this site and try again.", "plansForWorkspace": "Plans for {workspace}", "personalWorkspace": "Personal Workspace", @@ -4304,7 +4320,7 @@ "assetDelete": { "error": "Items failed to delete", "success": "Deletion successful", - "warn": "Some items failed to delete" + "warning": "Some items failed to delete" }, "assetsDeleted": "{n} / {total} assets were deleted", "jobsDeleted": "{n} / {total} jobs were deleted", @@ -5277,7 +5293,7 @@ }, "workspace": { "inviteAccepted": "Invite Accepted", - "addedToWorkspace": "You have been added to:", + "addedToNamedWorkspace": "You have been added to {workspaceName}", "inviteFailed": "Failed to Accept Invite", "inviteSsoUnavailable": "Ask your admin to add you", "inviteSsoUnavailableDetail": "Invite links can't be accepted from an SSO account yet. Ask a workspace admin to add you to the workspace directly.", diff --git a/src/main.ts b/src/main.ts index 918a22b8441..59ddd323d3c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -5,7 +5,6 @@ import { captureMessage } from '@sentry/vue' import { createPinia } from 'pinia' import 'primeicons/primeicons.css' import PrimeVue from 'primevue/config' -import ToastService from 'primevue/toastservice' import Tooltip from 'primevue/tooltip' import { createApp } from 'vue' @@ -31,7 +30,7 @@ import '@/lib/litegraph/public/css/litegraph.css' import router from '@/router' import { isDesktop, isNightly } from '@/platform/distribution/types' import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useBootstrapStore } from '@/stores/bootstrapStore' import App from './App.vue' @@ -127,11 +126,7 @@ setAssertReporter( reportAssertFailure(message, context) } if (isNightly) { - useToastStore(pinia).add({ - severity: 'warn', - summary: 'Assertion failed', - detail: message - }) + useToast(pinia).warning('Assertion failed', { description: message }) } }, { forwardsToRum: isCloud } @@ -163,7 +158,6 @@ app } } }) - .use(ToastService) .use(pinia) .use(i18n) diff --git a/src/platform/assets/components/AssetExportProgressDialog.test.ts b/src/platform/assets/components/AssetExportProgressDialog.test.ts index 91f0491ab21..59258a1eab9 100644 --- a/src/platform/assets/components/AssetExportProgressDialog.test.ts +++ b/src/platform/assets/components/AssetExportProgressDialog.test.ts @@ -51,6 +51,38 @@ describe('AssetExportProgressDialog', () => { store.exportList[0].exportName = 'bundle.zip' await nextTick() - expect(screen.getByText('All exports completed')).toBeVisible() + expect( + screen.getByText('All exports completed', { selector: 'span' }) + ).toBeVisible() }) + + it('renders only while an export is tracked', async () => { + render(AssetExportProgressDialog, { global: { plugins: [i18n] } }) + expect(screen.queryByRole('button', { name: 'Expand' })).toBeNull() + + useAssetExportStore().trackExport('task-export-1') + await nextTick() + + expect(screen.getByRole('button', { name: 'Expand' })).toBeVisible() + }) +}) + +describe('AssetExportProgressDialog announcements', () => { + it.for([ + { status: 'running', announcement: 'Exporting Assets' }, + { status: 'failed', announcement: '1 export failed' }, + { status: 'completed', announcement: 'All exports completed' } + ] as const)( + 'announces "$announcement" when the export is $status', + async ({ status, announcement }) => { + const store = renderDialog() + + store.exportList[0].status = status + await nextTick() + + expect( + screen.getByText(announcement, { selector: '[role="status"]' }) + ).toBeInTheDocument() + } + ) }) diff --git a/src/platform/assets/components/AssetExportProgressDialog.vue b/src/platform/assets/components/AssetExportProgressDialog.vue index 4e7b64ef48c..0f3a25fb61a 100644 --- a/src/platform/assets/components/AssetExportProgressDialog.vue +++ b/src/platform/assets/components/AssetExportProgressDialog.vue @@ -3,7 +3,7 @@ import { computed, ref } from 'vue' import { useI18n } from 'vue-i18n' import Loader from '@/components/loader/Loader.vue' -import HoneyToast from '@/components/honeyToast/HoneyToast.vue' +import ToastPanel from '@/components/ui/toast/ToastPanel.vue' import Button from '@/components/ui/button/Button.vue' import type { AssetExport } from '@/stores/assetExportStore' import { useAssetExportStore } from '@/stores/assetExportStore' @@ -45,6 +45,10 @@ const footerLabel = computed(() => { return t('exportToast.allExportsCompleted') }) +const announcement = computed(() => + isInProgress.value ? t('exportToast.exportingAssets') : footerLabel.value +) + const footerIconClass = computed(() => { if (isInProgress.value) return 'icon-[lucide--loader-circle] animate-spin text-muted-foreground' @@ -72,7 +76,7 @@ function closeDialog() { diff --git a/src/platform/assets/components/ModelImportProgressDialog.test.ts b/src/platform/assets/components/ModelImportProgressDialog.test.ts index f263d1d727e..6a49d3cf7c1 100644 --- a/src/platform/assets/components/ModelImportProgressDialog.test.ts +++ b/src/platform/assets/components/ModelImportProgressDialog.test.ts @@ -5,15 +5,13 @@ import { describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' import enMessages from '@/locales/en/main.json' with { type: 'json' } +import { useToast } from '@/components/ui/toast/toastStore' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAssetDownloadStore } from '@/stores/assetDownloadStore' import ModelImportProgressDialog from './ModelImportProgressDialog.vue' -vi.mock(import('@/platform/telemetry/reportError'), () => ({ - reportError: vi.fn() -})) +vi.mock(import('@/platform/telemetry/reportError')) const i18n = createI18n({ legacy: false, @@ -52,8 +50,6 @@ describe('ModelImportProgressDialog cancellation', () => { it('reports cancellation failures and shows the error toast', async () => { const user = userEvent.setup() const store = renderDialog() - const toastStore = useToastStore() - const addToast = vi.spyOn(toastStore, 'add') const error = new Error('Cancellation unavailable') vi.spyOn(store, 'cancelDownload').mockResolvedValue({ ok: false, error }) @@ -66,10 +62,8 @@ describe('ModelImportProgressDialog cancellation', () => { errorType: 'asset_download_cancellation_failure', logToConsole: false }) - expect(addToast).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Error', - detail: 'Cancellation unavailable' + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: 'Cancellation unavailable' }) }) }) @@ -84,7 +78,6 @@ describe('ModelImportProgressDialog cancellation', () => { 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 () => { @@ -111,7 +104,7 @@ describe('ModelImportProgressDialog cancellation', () => { await user.click(screen.getByRole('button', { name: 'Close' })) - expect(screen.queryByRole('status')).toBeNull() + expect(store.hasDownloads).toBe(false) }) it('dismisses a failed download while reconciliation continues', async () => { @@ -123,6 +116,41 @@ describe('ModelImportProgressDialog cancellation', () => { await user.click(screen.getByRole('button', { name: 'Close' })) - expect(screen.queryByRole('status')).toBeNull() + expect(store.hasDownloads).toBe(false) }) }) + +it('renders only while a download is tracked', async () => { + render(ModelImportProgressDialog, { global: { plugins: [i18n] } }) + expect(screen.queryByRole('button', { name: 'Expand' })).toBeNull() + + useAssetDownloadStore().trackDownload( + 'task-123', + 'checkpoints', + 'model.safetensors' + ) + await nextTick() + + expect(screen.getByRole('button', { name: 'Expand' })).toBeVisible() +}) + +describe('ModelImportProgressDialog announcements', () => { + it.for([ + { status: 'running', announcement: 'Importing Models' }, + { status: 'failed', announcement: '1 download failed' }, + { status: 'completed', announcement: 'All downloads completed' }, + { status: 'cancelled', announcement: 'Cancelled' } + ] as const)( + 'announces "$announcement" when the import is $status', + async ({ status, announcement }) => { + const store = renderDialog() + + store.downloadList[0].status = status + await nextTick() + + expect( + screen.getByText(announcement, { selector: '[role="status"]' }) + ).toBeInTheDocument() + } + ) +}) diff --git a/src/platform/assets/components/ModelImportProgressDialog.vue b/src/platform/assets/components/ModelImportProgressDialog.vue index 770e0420f9d..e008963daa7 100644 --- a/src/platform/assets/components/ModelImportProgressDialog.vue +++ b/src/platform/assets/components/ModelImportProgressDialog.vue @@ -5,7 +5,7 @@ import { computed, ref } from 'vue' import { useI18n } from 'vue-i18n' import Loader from '@/components/loader/Loader.vue' -import HoneyToast from '@/components/honeyToast/HoneyToast.vue' +import ToastPanel from '@/components/ui/toast/ToastPanel.vue' import ProgressToastItem from '@/components/toast/ProgressToastItem.vue' import Button from '@/components/ui/button/Button.vue' import { useErrorHandling } from '@/composables/useErrorHandling' @@ -66,6 +66,19 @@ const currentJobName = computed(() => { return activeJob?.assetName || t('progressToast.downloadingModel') }) +const outcomeLabel = computed(() => { + if (failedJobs.value.length > 0) + return t('progressToast.downloadsFailed', { + count: failedJobs.value.length + }) + if (cancelledJobs.value.length > 0) return t('electronFileDownload.cancelled') + return t('progressToast.allDownloadsCompleted') +}) + +const announcement = computed(() => + isInProgress.value ? t('progressToast.importingModels') : outcomeLabel.value +) + const completedCount = computed( () => completedJobs.value.length + @@ -111,7 +124,7 @@ async function cancelDownload(taskId: TaskId) { - + diff --git a/src/platform/assets/composables/openModelLibraryBrowser.ts b/src/platform/assets/composables/openModelLibraryBrowser.ts index b2bf0cac1ad..588d156fd11 100644 --- a/src/platform/assets/composables/openModelLibraryBrowser.ts +++ b/src/platform/assets/composables/openModelLibraryBrowser.ts @@ -3,12 +3,12 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import { useAssetBrowserDialog } from '@/platform/assets/composables/useAssetBrowserDialog' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' export async function openModelLibraryBrowser(): Promise { if (!useFeatureFlags().flags.assetsEnabled) return - const toastStore = useToastStore() + const toast = useToast() const assetBrowserDialog = useAssetBrowserDialog() await assetBrowserDialog.browse({ assetType: 'models', @@ -22,10 +22,8 @@ export async function openModelLibraryBrowser(): Promise { tags: { code: error.code }, context: { assetId: error.assetId, details: error.details } }) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('assetBrowser.failedToCreateNode') + toast.error(t('g.error'), { + description: t('assetBrowser.failedToCreateNode') }) } } diff --git a/src/platform/assets/composables/useAssetDownload.ts b/src/platform/assets/composables/useAssetDownload.ts index 5df612288d4..422dab2d7f0 100644 --- a/src/platform/assets/composables/useAssetDownload.ts +++ b/src/platform/assets/composables/useAssetDownload.ts @@ -2,7 +2,7 @@ import { useI18n } from 'vue-i18n' import { downloadFile, downloadFileAsBlob } from '@/base/common/downloadUtil' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' interface DirectAssetDownload { mode: 'direct' @@ -22,7 +22,7 @@ export type AssetDownload = DirectAssetDownload | FetchedAssetDownload export function useAssetDownload() { const { t } = useI18n() - const toast = useToastStore() + const toast = useToast() async function downloadFiles(files: AssetDownload[]): Promise { const pending = files.map((file) => { @@ -49,11 +49,9 @@ export function useAssetDownload() { const successCount = files.length - failures.length if (successCount > 0) { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.selection.downloadsStarted', successCount), - life: 2000 + toast.success(t('g.success'), { + description: t('mediaAsset.selection.downloadsStarted', successCount), + duration: 2000 }) } @@ -65,10 +63,8 @@ export function useAssetDownload() { context: { filename: failure.filename } }) } - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('progressToast.downloadsFailed', failures.length) + toast.error(t('g.error'), { + description: t('progressToast.downloadsFailed', failures.length) }) } } diff --git a/src/platform/assets/composables/useAssetZipExport.ts b/src/platform/assets/composables/useAssetZipExport.ts index 36eef572ed3..48e26c9b989 100644 --- a/src/platform/assets/composables/useAssetZipExport.ts +++ b/src/platform/assets/composables/useAssetZipExport.ts @@ -1,14 +1,14 @@ import type { CreateAssetExportData } from '@comfyorg/ingest-types' import { useI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' import { assetService } from '@/platform/assets/services/assetService' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAssetExportStore } from '@/stores/assetExportStore' export function useAssetZipExport() { const { t } = useI18n() - const toast = useToastStore() + const toast = useToast() async function startZipExport( request: CreateAssetExportData['body'], @@ -17,15 +17,13 @@ export function useAssetZipExport() { try { const { task_id } = await assetService.createAssetExport(request) useAssetExportStore().trackExport(task_id) - toast.add({ - severity: 'info', - summary: t('exportToast.exportStarted'), - detail: t( + toast.info(t('exportToast.exportStarted'), { + description: t( 'mediaAsset.selection.exportStarted', { count: fileCount }, fileCount ), - life: 3000 + duration: 3000 }) } catch (error) { reportError(error, { @@ -33,10 +31,8 @@ export function useAssetZipExport() { surface: 'assets', context: { count: fileCount } }) - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('exportToast.exportFailedSingle') + toast.error(t('g.error'), { + description: t('exportToast.exportFailedSingle') }) } } diff --git a/src/platform/assets/composables/useMediaAssetActions.test.ts b/src/platform/assets/composables/useMediaAssetActions.test.ts index 51a351a6ef5..33c8b6e2711 100644 --- a/src/platform/assets/composables/useMediaAssetActions.test.ts +++ b/src/platform/assets/composables/useMediaAssetActions.test.ts @@ -4,10 +4,9 @@ import { useAssetExportStore } from '@/stores/assetExportStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { useNodeDefStore } from '@/stores/nodeDefStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { CreateAssetExportData } from '@comfyorg/ingest-types' import { fromAny, fromPartial } from '@total-typescript/shoehorn' -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { App } from 'vue' import { createApp, defineComponent, h, provide, ref } from 'vue' @@ -49,17 +48,6 @@ vi.mock(import('@/platform/distribution/types'), () => ({ } })) -vi.mock( - import('primevue/usetoast'), - - () => { - const add = vi.fn() - return { - useToast: () => ({ add }) - } - } -) - const mockShowDialog = vi.hoisted(() => vi.fn()) const mockInvalidateModelsForCategory = vi.hoisted(() => vi.fn()) @@ -443,15 +431,19 @@ describe('useMediaAssetActions', () => { .mocked(useLitegraphService()) .addNodeOnGraph.mock.calls.map(([, options]) => options) ).toEqual([{ pos: [100, 100] }, { pos: [150, 150] }]) - expect(useToast().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: i18n.global.t('g.warning'), - detail: i18n.global.t('mediaAsset.selection.partialAddNodesSuccess', { - succeeded: 2, - failed: 1 - }), - life: 3000 - }) + expect(useToast().warning).toHaveBeenCalledWith( + i18n.global.t('g.warning'), + { + description: i18n.global.t( + 'mediaAsset.selection.partialAddNodesSuccess', + { + succeeded: 2, + failed: 1 + } + ), + duration: 3000 + } + ) unmount() }) }) @@ -543,9 +535,7 @@ describe('useMediaAssetActions', () => { expect(mockLoadApiJson).toHaveBeenCalledWith(apiPrompt, 'open.json') expect(mockOpenWorkflowAction).not.toHaveBeenCalled() - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().success).toHaveBeenCalled() }) it('warns when loading the stored API graph fails', async () => { @@ -559,8 +549,9 @@ describe('useMediaAssetActions', () => { await actions.openWorkflow(createMockAsset()) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn', detail: 'boom' }) + expect(useToast().warning).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'boom' }) ) }) @@ -576,8 +567,9 @@ describe('useMediaAssetActions', () => { await actions.openWorkflow(createMockAsset()) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn', detail: 'network down' }) + expect(useToast().warning).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'network down' }) ) }) @@ -591,9 +583,7 @@ describe('useMediaAssetActions', () => { await actions.openWorkflow(createMockAsset()) expect(mockLoadApiJson).not.toHaveBeenCalled() - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn' }) - ) + expect(useToast().warning).toHaveBeenCalled() }) }) @@ -611,9 +601,7 @@ describe('useMediaAssetActions', () => { await actions.openMultipleWorkflows([createMockAsset()]) expect(mockLoadApiJson).toHaveBeenCalledWith(apiPrompt, 'bulk.json') - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().success).toHaveBeenCalled() }) }) @@ -639,7 +627,7 @@ describe('useMediaAssetActions', () => { await actions.exportWorkflow(createMockAsset()) - expect(useToast().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows a success toast on successful export', async () => { @@ -648,9 +636,7 @@ describe('useMediaAssetActions', () => { await actions.exportWorkflow(createMockAsset()) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().success).toHaveBeenCalled() }) it('shows an error toast on actual failure', async () => { @@ -659,9 +645,7 @@ describe('useMediaAssetActions', () => { await actions.exportWorkflow(createMockAsset()) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() }) it('shows a warning toast when the workflow is missing', async () => { @@ -670,9 +654,7 @@ describe('useMediaAssetActions', () => { await actions.exportWorkflow(createMockAsset()) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn' }) - ) + expect(useToast().warning).toHaveBeenCalled() }) it('shows no toast when every asset in a bulk export is cancelled', async () => { @@ -684,7 +666,7 @@ describe('useMediaAssetActions', () => { createMockAsset({ id: 'b' }) ]) - expect(useToast().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows a success toast for the succeeded subset when some bulk exports are cancelled', async () => { @@ -698,9 +680,7 @@ describe('useMediaAssetActions', () => { createMockAsset({ id: 'b' }) ]) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().success).toHaveBeenCalled() }) it('shows a partial-success warning toast when some bulk exports fail outright', async () => { @@ -714,9 +694,7 @@ describe('useMediaAssetActions', () => { createMockAsset({ id: 'b' }) ]) - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'warn' }) - ) + expect(useToast().warning).toHaveBeenCalled() }) }) @@ -825,17 +803,15 @@ describe('useMediaAssetActions', () => { expect(mockDownloadFile).toHaveBeenCalledTimes(2) await vi.waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().success).toHaveBeenCalledWith( + 'Success', expect.objectContaining({ - severity: 'success', - detail: 'Started downloading 1 file' + description: 'Started downloading 1 file' }) ) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: '1 download failed' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: '1 download failed' }) ) }) expect(mockReportError).toHaveBeenCalledWith(failure, { @@ -1424,10 +1400,12 @@ describe('useMediaAssetActions', () => { expect(mockCreateAssetExport).toHaveBeenCalledTimes(1) }) + const { info } = useToast() await vi.waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( + expect(info).toHaveBeenCalledWith( + 'Preparing ZIP download...', expect.objectContaining({ - detail: i18n.global.t( + description: i18n.global.t( 'mediaAsset.selection.exportStarted', { count }, count @@ -1632,11 +1610,9 @@ describe('useMediaAssetActions', () => { expect(mockDeleteAsset.mock.invocationCallOrder[0]).toBeLessThan( mockSetAssetDeleting.mock.invocationCallOrder[1] ) - expect(useToast().add).toHaveBeenCalledWith({ - severity: 'success', - summary: i18n.global.t('mediaAsset.assetDelete.success'), - detail: i18n.global.t('mediaAsset.assetsDeleted', { total: 1 }, 1), - life: 2000 + expect(useToast().success).toHaveBeenCalledWith('Deletion successful', { + description: i18n.global.t('mediaAsset.assetsDeleted', { total: 1 }, 1), + duration: 2000 }) unmount() @@ -1660,9 +1636,7 @@ describe('useMediaAssetActions', () => { expect(api.deleteItem).toHaveBeenCalledWith('history', 'job-1') expect(mockDeleteAsset).not.toHaveBeenCalled() - expect(useToast().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().success).toHaveBeenCalled() }) }) @@ -2044,11 +2018,9 @@ describe('useMediaAssetActions', () => { expect(mockInputAssets.items.map((item) => item.id)).toEqual([ 'asset-503' ]) - expect(useToast().add).toHaveBeenCalledWith({ - severity: 'error', - summary: i18n.global.t('mediaAsset.assetDelete.error'), - detail: i18n.global.t('mediaAsset.assetsDeleted', { total: 1 }, 0), - life: 5000 + expect(useToast().error).toHaveBeenCalledWith('Items failed to delete', { + description: i18n.global.t('mediaAsset.assetsDeleted', { total: 1 }, 0), + duration: 5000 }) expect(mockMarkMissingMedia).not.toHaveBeenCalled() expect(mockClearWidgetValues).not.toHaveBeenCalled() @@ -2057,12 +2029,17 @@ describe('useMediaAssetActions', () => { expect(mockDeleteAsset).toHaveBeenCalledTimes(2) expect(mockInputAssets.items).toEqual([]) - expect(useToast().add).toHaveBeenLastCalledWith({ - severity: 'success', - summary: i18n.global.t('mediaAsset.assetDelete.success'), - detail: i18n.global.t('mediaAsset.assetsDeleted', { total: 1 }, 1), - life: 2000 - }) + expect(useToast().success).toHaveBeenLastCalledWith( + 'Deletion successful', + { + description: i18n.global.t( + 'mediaAsset.assetsDeleted', + { total: 1 }, + 1 + ), + duration: 2000 + } + ) }) it('cleans up only the succeeded assets and clears every overlay when part of a batch fails', async () => { @@ -2106,12 +2083,17 @@ describe('useMediaAssetActions', () => { succeededVariants ) expect(mockCaptureCanvasState).toHaveBeenCalledTimes(1) - expect(useToast().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: i18n.global.t('mediaAsset.assetDelete.warn'), - detail: i18n.global.t('mediaAsset.assetsDeleted', { total: 3 }, 2), - life: 5000 - }) + expect(useToast().warning).toHaveBeenCalledWith( + 'Some items failed to delete', + { + description: i18n.global.t( + 'mediaAsset.assetsDeleted', + { total: 3 }, + 2 + ), + duration: 5000 + } + ) const flagsById: Record = {} for (const [id, flag] of mockSetAssetDeleting.mock.calls) { diff --git a/src/platform/assets/composables/useMediaAssetActions.ts b/src/platform/assets/composables/useMediaAssetActions.ts index 3d867ec277a..6b8e6eb644f 100644 --- a/src/platform/assets/composables/useMediaAssetActions.ts +++ b/src/platform/assets/composables/useMediaAssetActions.ts @@ -1,5 +1,5 @@ import { uniqBy } from 'es-toolkit' -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { inject } from 'vue' import { useI18n } from 'vue-i18n' @@ -251,11 +251,9 @@ export function useMediaAssetActions() { (getAssetType(targetAsset) === 'output' ? targetAsset.id : undefined) if (!jobId) { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.noJobIdFound'), - life: 2000 + toast.warning(t('g.warning'), { + description: t('mediaAsset.noJobIdFound'), + duration: 2000 }) return } @@ -277,11 +275,9 @@ export function useMediaAssetActions() { ) if (!nodeType || !widgetName) { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.unsupportedFileType'), - life: 2000 + toast.warning(t('g.warning'), { + description: t('mediaAsset.unsupportedFileType'), + duration: 2000 }) return } @@ -295,10 +291,8 @@ export function useMediaAssetActions() { ) if (!node) { - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('mediaAsset.failedToCreateNode') + toast.error(t('g.error'), { + description: t('mediaAsset.failedToCreateNode') }) return } @@ -312,11 +306,9 @@ export function useMediaAssetActions() { } node.graph?.setDirtyCanvas(true, true) - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.nodeAddedToWorkflow', { nodeType }), - life: 2000 + toast.success(t('g.success'), { + description: t('mediaAsset.nodeAddedToWorkflow', { nodeType }), + duration: 2000 }) } @@ -374,18 +366,14 @@ export function useMediaAssetActions() { const result = await openAssetWorkflow(targetAsset) if (!result.success) { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: result.error || t('mediaAsset.noWorkflowDataFound'), - life: 2000 + toast.warning(t('g.warning'), { + description: result.error || t('mediaAsset.noWorkflowDataFound'), + duration: 2000 }) } else { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.workflowOpenedInNewTab'), - life: 2000 + toast.success(t('g.success'), { + description: t('mediaAsset.workflowOpenedInNewTab'), + duration: 2000 }) } } @@ -410,19 +398,15 @@ export function useMediaAssetActions() { if (result.cancelled) return if (!result.success) { - const isNoWorkflow = result.error?.includes('No workflow') - toast.add({ - severity: isNoWorkflow ? 'warn' : 'error', - summary: isNoWorkflow ? t('g.warning') : t('g.error'), - detail: result.error || t('mediaAsset.failedToExportWorkflow'), - life: 3000 + const kind = result.error?.includes('No workflow') ? 'warning' : 'error' + toast[kind](t(`g.${kind}`), { + description: result.error || t('mediaAsset.failedToExportWorkflow'), + duration: 3000 }) } else { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.workflowExportedSuccessfully'), - life: 2000 + toast.success(t('g.success'), { + description: t('mediaAsset.workflowExportedSuccessfully'), + duration: 2000 }) } } @@ -475,29 +459,23 @@ export function useMediaAssetActions() { } if (failed === 0) { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.selection.nodesAddedToWorkflow', { + toast.success(t('g.success'), { + description: t('mediaAsset.selection.nodesAddedToWorkflow', { count: succeeded }), - life: 2000 + duration: 2000 }) } else if (succeeded === 0) { - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('mediaAsset.selection.failedToAddNodes') + toast.error(t('g.error'), { + description: t('mediaAsset.selection.failedToAddNodes') }) } else { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.selection.partialAddNodesSuccess', { + toast.warning(t('g.warning'), { + description: t('mediaAsset.selection.partialAddNodesSuccess', { succeeded, failed }), - life: 3000 + duration: 3000 }) } } @@ -524,28 +502,24 @@ export function useMediaAssetActions() { } if (failed === 0) { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.selection.workflowsOpened', { count: succeeded }), - life: 2000 + toast.success(t('g.success'), { + description: t('mediaAsset.selection.workflowsOpened', { + count: succeeded + }), + duration: 2000 }) } else if (succeeded === 0) { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.selection.noWorkflowsFound'), - life: 3000 + toast.warning(t('g.warning'), { + description: t('mediaAsset.selection.noWorkflowsFound'), + duration: 3000 }) } else { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.selection.partialWorkflowsOpened', { + toast.warning(t('g.warning'), { + description: t('mediaAsset.selection.partialWorkflowsOpened', { succeeded, failed }), - life: 3000 + duration: 3000 }) } } @@ -579,30 +553,24 @@ export function useMediaAssetActions() { if (succeeded === 0 && failed === 0) return if (failed === 0) { - toast.add({ - severity: 'success', - summary: t('g.success'), - detail: t('mediaAsset.selection.workflowsExported', { + toast.success(t('g.success'), { + description: t('mediaAsset.selection.workflowsExported', { count: succeeded }), - life: 2000 + duration: 2000 }) } else if (succeeded === 0) { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.selection.noWorkflowsToExport'), - life: 3000 + toast.warning(t('g.warning'), { + description: t('mediaAsset.selection.noWorkflowsToExport'), + duration: 3000 }) } else { - toast.add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('mediaAsset.selection.partialWorkflowsExported', { + toast.warning(t('g.warning'), { + description: t('mediaAsset.selection.partialWorkflowsExported', { succeeded, failed }), - life: 3000 + duration: 3000 }) } } @@ -803,11 +771,11 @@ export function useMediaAssetActions() { } } - const severity = + const outcome = failedDeletions.length === 0 ? 'success' : deletedJobCount || deletedAssetCount - ? 'warn' + ? 'warning' : 'error' const resultMessages: string[] = [] @@ -826,11 +794,9 @@ export function useMediaAssetActions() { ) } - toast.add({ - detail: resultMessages.join('\n'), - life: severity === 'success' ? 2000 : 5000, - severity, - summary: t(`mediaAsset.assetDelete.${severity}`) + toast[outcome](t(`mediaAsset.assetDelete.${outcome}`), { + description: resultMessages.join('\n'), + duration: outcome === 'success' ? 2000 : 5000 }) return true } diff --git a/src/platform/assets/composables/useNodeOutputsExport.test.ts b/src/platform/assets/composables/useNodeOutputsExport.test.ts index 8981587167c..a185e4f2d7d 100644 --- a/src/platform/assets/composables/useNodeOutputsExport.test.ts +++ b/src/platform/assets/composables/useNodeOutputsExport.test.ts @@ -5,13 +5,13 @@ import { h } from 'vue' import { downloadFile } from '@/base/common/downloadUtil' import GlobalDialog from '@/components/dialog/GlobalDialog.vue' +import { useToast } from '@/components/ui/toast/toastStore' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { i18n } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import { assetService } from '@/platform/assets/services/assetService' import type { ResultItem } from '@/platform/remote/comfyui/execution/types' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAssetExportStore } from '@/stores/assetExportStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' @@ -121,11 +121,11 @@ describe('useNodeOutputsExport', () => { await exportFromDialog(node, ['f2.exr']) await vi.waitFor(() => { - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'info', - summary: 'Preparing ZIP download...', - detail: 'Preparing ZIP export for 2 files' + kind: 'info', + title: 'Preparing ZIP download...', + description: 'Preparing ZIP export for 2 files' }) ]) }) @@ -226,10 +226,10 @@ describe('useNodeOutputsExport', () => { context: { count: 2 } }) }) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'Failed to create ZIP export' + kind: 'error', + description: 'Failed to create ZIP export' }) ]) expect(useAssetExportStore().exportList).toEqual([]) diff --git a/src/platform/assets/utils/createAssetWidget.ts b/src/platform/assets/utils/createAssetWidget.ts index 86913335af4..b6798bd79f6 100644 --- a/src/platform/assets/utils/createAssetWidget.ts +++ b/src/platform/assets/utils/createAssetWidget.ts @@ -11,7 +11,7 @@ import { assetFilenameSchema, assetItemSchema } from '@/platform/assets/schemas/assetSchema' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { getAssetFilename } from '@/platform/assets/utils/assetMetadataUtils' @@ -51,7 +51,7 @@ function createAssetWidgetOptions({ const assetBrowserDialog = useAssetBrowserDialog() async function openModal(widget: IBaseWidget) { - const toastStore = useToastStore() + const toast = useToast() await assetBrowserDialog.show({ nodeType: nodeTypeForBrowser, @@ -65,10 +65,8 @@ function createAssetWidgetOptions({ 'Invalid asset item:', fromZodError(validatedAsset.error).message ) - toastStore.add({ - severity: 'error', - summary: t('assetBrowser.invalidAsset'), - detail: t('assetBrowser.invalidAssetDetail') + toast.error(t('assetBrowser.invalidAsset'), { + description: t('assetBrowser.invalidAssetDetail') }) return } @@ -83,10 +81,8 @@ function createAssetWidgetOptions({ 'for asset:', validatedAsset.data.id ) - toastStore.add({ - severity: 'error', - summary: t('assetBrowser.invalidFilename'), - detail: t('assetBrowser.invalidFilenameDetail') + toast.error(t('assetBrowser.invalidFilename'), { + description: t('assetBrowser.invalidFilenameDetail') }) return } diff --git a/src/platform/auth/session/cloudWebSessionStore.ts b/src/platform/auth/session/cloudWebSessionStore.ts index 288594645fb..84e62384998 100644 --- a/src/platform/auth/session/cloudWebSessionStore.ts +++ b/src/platform/auth/session/cloudWebSessionStore.ts @@ -60,7 +60,7 @@ import { } from '@/platform/auth/session/webSessionFetch' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { api } from '@/scripts/api' @@ -137,13 +137,11 @@ function resetForAccountChange(change: WebSessionAccountChange): void { useTeamWorkspaceStore().resetForIdentityChange() void api.resetSocket() if (change.reason !== 'user_changed') return - useToastStore().add({ - severity: 'info', - summary: t('auth.accountChanged.title'), - detail: t('auth.accountChanged.detail', { + useToast().info(t('auth.accountChanged.title'), { + description: t('auth.accountChanged.detail', { email: change.session.user.email }), - life: 8000 + duration: 8000 }) } diff --git a/src/platform/auth/session/components/SignOutEverywhereButton.vue b/src/platform/auth/session/components/SignOutEverywhereButton.vue index cc11085f761..3de3eb0e700 100644 --- a/src/platform/auth/session/components/SignOutEverywhereButton.vue +++ b/src/platform/auth/session/components/SignOutEverywhereButton.vue @@ -14,35 +14,31 @@ import { ref } from 'vue' import { useI18n } from 'vue-i18n' import Button from '@/components/ui/button/Button.vue' +import { useToast } from '@/components/ui/toast/toastStore' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useCloudWebSessionStore, webSessionFailureMessage } from '@/platform/auth/session/cloudWebSessionStore' -import { useToastStore } from '@/platform/updates/common/toastStore' const { t } = useI18n() const { logout } = useAuthActions() const webSession = useCloudWebSessionStore() -const toastStore = useToastStore() +const toast = useToast() const signingOut = ref(false) async function revokeAllSessions(): Promise { const result = await webSession.revokeAllSessions() if (result.status === 'error') { - toastStore.add({ - severity: 'error', - summary: t('auth.signOutEverywhere.failed'), - detail: webSessionFailureMessage(result.code), - life: 8000 + toast.error(t('auth.signOutEverywhere.failed'), { + description: webSessionFailureMessage(result.code), + duration: 8000 }) return false } - toastStore.add({ - severity: 'success', - summary: t('auth.signOutEverywhere.success'), - detail: t('auth.signOutEverywhere.successDetail'), - life: 5000 + toast.success(t('auth.signOutEverywhere.success'), { + description: t('auth.signOutEverywhere.successDetail'), + duration: 5000 }) return true } diff --git a/src/platform/auth/sso/ssoRequired.ts b/src/platform/auth/sso/ssoRequired.ts index 5996cc97a0e..2a7d86ecb00 100644 --- a/src/platform/auth/sso/ssoRequired.ts +++ b/src/platform/auth/sso/ssoRequired.ts @@ -10,7 +10,7 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import { SSO_REQUIRED_DIALOG_KEY } from '@/platform/auth/sso/ssoRequiredDialogKey' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' export interface SsoRequiredContext { @@ -62,10 +62,8 @@ export function presentSsoRequired(context: SsoRequiredContext = {}): boolean { surface: 'auth', errorType: 'failure_loading_sso_required_dialog' }) - useToastStore().add({ - severity: 'error', - summary: t('auth.sso.required.title'), - detail: t('auth.sso.required.body') + useToast().error(t('auth.sso.required.title'), { + description: t('auth.sso.required.body') }) }) return true diff --git a/src/platform/auth/sso/ssoRequiredChunkFailure.test.ts b/src/platform/auth/sso/ssoRequiredChunkFailure.test.ts index a5179140347..4d659e0e894 100644 --- a/src/platform/auth/sso/ssoRequiredChunkFailure.test.ts +++ b/src/platform/auth/sso/ssoRequiredChunkFailure.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from 'vitest' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' vi.mock(import('@/composables/useFeatureFlags')) vi.mock(import('@/platform/telemetry/reportError')) @@ -17,11 +17,11 @@ describe('the SSO-required screen when its chunk fails to load', () => { expect(presentSsoRequired()).toBe(true) await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - summary: 'Your organization requires single sign-on', - detail: expect.stringContaining('Continue with SSO') + kind: 'error', + title: 'Your organization requires single sign-on', + description: expect.stringContaining('Continue with SSO') }) ]) ) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index 1389abe6806..2bac5336d16 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -61,7 +61,7 @@ import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { NoWorkspaceAccessError } from '@/platform/workspace/api/workspaceApiError' import { @@ -580,10 +580,10 @@ describe('cloud app on the shared web session (unified_web_session on)', () => { expect( sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE) ).toBeNull() - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'info', - detail: expect.stringContaining('user-b@example.com') + kind: 'info', + description: expect.stringContaining('user-b@example.com') }) ]) }) @@ -3576,9 +3576,10 @@ describe('an SSO session with no Firebase login reaching Firebase-only paths', ( await router.push(`/user-select?desktop_login_code=${desktopCode}`) const { path, query } = router.currentRoute.value - const ssoNotice = useToastStore().messagesToAdd.filter( - ({ summary }) => - summary === "Desktop sign-in isn't available for SSO accounts yet" + const ssoNotice = useToast().toasts.filter( + (toast) => + 'title' in toast && + toast.title === "Desktop sign-in isn't available for SSO accounts yet" ) expect({ path, diff --git a/src/platform/cloud/onboarding/CloudSurveyView.test.ts b/src/platform/cloud/onboarding/CloudSurveyView.test.ts index d471459ec7e..4874ba5b53d 100644 --- a/src/platform/cloud/onboarding/CloudSurveyView.test.ts +++ b/src/platform/cloud/onboarding/CloudSurveyView.test.ts @@ -7,10 +7,10 @@ import { createI18n } from 'vue-i18n' import { createMemoryHistory, createRouter } from 'vue-router' import enMessages from '@/locales/en/main.json' with { type: 'json' } +import { useToast } from '@/components/ui/toast/toastStore' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAuthStore } from '@/stores/authStore' import CloudSurveyView from './CloudSurveyView.vue' @@ -104,7 +104,6 @@ describe('CloudSurveyView', () => { vi.mocked(useTelemetry).mockReturnValue( fromPartial({ trackSurvey: mocks.trackSurvey }) ) - vi.spyOn(useToastStore(), 'add').mockImplementation(() => undefined) }) it('tracks and advances after storing a first survey', async () => { @@ -150,9 +149,7 @@ describe('CloudSurveyView', () => { surface: 'platform', errorType: 'error_submitting_onboarding_survey' }) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() expect(screen.getByRole('button', { name: 'Submit survey' })).toBeEnabled() }) @@ -167,7 +164,7 @@ describe('CloudSurveyView', () => { expect(router.currentRoute.value.name).toBe('survey') expect(mocks.reportError).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(screen.getByRole('button', { name: 'Submit survey' })).toBeEnabled() }) @@ -185,9 +182,7 @@ describe('CloudSurveyView', () => { surface: 'platform', errorType: 'error_submitting_onboarding_survey' }) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).toHaveBeenCalled() expect(screen.getByRole('button', { name: 'Submit survey' })).toBeEnabled() }) @@ -208,11 +203,9 @@ describe('CloudSurveyView', () => { surface: 'platform', errorType: 'error_navigating_from_onboarding_survey' }) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - summary: 'Survey saved, but onboarding could not continue', - detail: 'Please try again.' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Survey saved, but onboarding could not continue', + expect.objectContaining({ description: 'Please try again.' }) ) expect(screen.getByRole('button', { name: 'Submit survey' })).toBeEnabled() }) diff --git a/src/platform/cloud/onboarding/CloudSurveyView.vue b/src/platform/cloud/onboarding/CloudSurveyView.vue index 83c09f398a7..89191ad9736 100644 --- a/src/platform/cloud/onboarding/CloudSurveyView.vue +++ b/src/platform/cloud/onboarding/CloudSurveyView.vue @@ -19,6 +19,7 @@ import { computed, onMounted, ref } from 'vue' import { useI18n } from 'vue-i18n' import { isNavigationFailure, useRouter } from 'vue-router' +import { useToast } from '@/components/ui/toast/toastStore' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { getSurveyCompletedStatus, @@ -31,7 +32,6 @@ import { import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useAuthStore } from '@/stores/authStore' import DynamicSurveyForm from './survey/DynamicSurveyForm.vue' @@ -111,11 +111,9 @@ async function advanceFromSurvey(replaying: boolean, replayOwner: string) { surface: 'platform', errorType: 'error_navigating_from_onboarding_survey' }) - useToastStore().add({ - severity: 'error', - summary: t('cloudOnboarding.survey.navigationFailed'), - detail: t('cloudOnboarding.survey.navigationFailedDetail'), - life: 5000 + useToast().error(t('cloudOnboarding.survey.navigationFailed'), { + description: t('cloudOnboarding.survey.navigationFailedDetail'), + duration: 5000 }) } finally { isSubmitting.value = false @@ -127,11 +125,9 @@ function reportSurveySubmissionFailure(cause: unknown) { surface: 'platform', errorType: 'error_submitting_onboarding_survey' }) - useToastStore().add({ - severity: 'error', - summary: t('cloudOnboarding.survey.submitFailed'), - detail: t('cloudOnboarding.survey.submitFailedDetail'), - life: 5000 + useToast().error(t('cloudOnboarding.survey.submitFailed'), { + description: t('cloudOnboarding.survey.submitFailedDetail'), + duration: 5000 }) } diff --git a/src/platform/cloud/onboarding/components/CloudLayoutView.vue b/src/platform/cloud/onboarding/components/CloudLayoutView.vue index c5cdef46026..43021dacd0d 100644 --- a/src/platform/cloud/onboarding/components/CloudLayoutView.vue +++ b/src/platform/cloud/onboarding/components/CloudLayoutView.vue @@ -3,15 +3,14 @@ - - + diff --git a/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.test.ts b/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.test.ts index fa0e4b85cd5..4de7894b864 100644 --- a/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.test.ts +++ b/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.test.ts @@ -1,4 +1,5 @@ import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' import { render, screen, waitFor } from '@testing-library/vue' import userEvent from '@testing-library/user-event' @@ -9,17 +10,6 @@ import ChangeMemberRoleDialogContent from './ChangeMemberRoleDialogContent.vue' import type { WorkspaceRole } from '@/platform/workspace/api/workspaceApi' -const { mockToastAdd } = vi.hoisted(() => ({ mockToastAdd: vi.fn() })) - -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ - add: mockToastAdd - }) - }) -) - const i18n = createI18n({ legacy: false, locale: 'en', @@ -77,9 +67,12 @@ describe('ChangeMemberRoleDialogContent', () => { key: 'change-member-role' }) ) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'success', + title: 'workspacePanel.changeRoleDialog.success' + }) + ]) }) it('shows demote copy and confirms with Demote to member', async () => { @@ -117,9 +110,12 @@ describe('ChangeMemberRoleDialogContent', () => { ) await waitFor(() => - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + title: 'workspacePanel.changeRoleDialog.error' + }) + ]) ) expect(useDialogStore().closeDialog).not.toHaveBeenCalled() }) diff --git a/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.vue b/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.vue index 736994d0fb6..567307b746a 100644 --- a/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.vue +++ b/src/platform/workspace/components/dialogs/ChangeMemberRoleDialogContent.vue @@ -60,7 +60,7 @@ diff --git a/src/platform/workspace/composables/useInviteUrlLoader.test.ts b/src/platform/workspace/composables/useInviteUrlLoader.test.ts index a647bded451..e588d75f435 100644 --- a/src/platform/workspace/composables/useInviteUrlLoader.test.ts +++ b/src/platform/workspace/composables/useInviteUrlLoader.test.ts @@ -4,11 +4,12 @@ import type { User } from 'firebase/auth' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useDialogService } from '@/services/dialogService' import { useAuthStore } from '@/stores/authStore' +import { useToast } from '@/components/ui/toast/toastStore' import { WorkspaceApiError } from '../api/workspaceApi' import { useTeamWorkspaceStore } from '../stores/teamWorkspaceStore' import { fromAny, fromPartial } from '@total-typescript/shoehorn' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest' import { createApp, defineComponent } from 'vue' import type { App } from 'vue' import { createI18n } from 'vue-i18n' @@ -55,16 +56,6 @@ vi.mock(import('@/services/dialogService')) vi.mock(import('@/composables/useFeatureFlags')) vi.mock(import('firebase/auth')) -const mockToastAdd = vi.hoisted(() => vi.fn()) -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ - add: mockToastAdd - }) - }) -) - const apps: App[] = [] function useInviteUrlLoader(): ReturnType { @@ -85,13 +76,15 @@ function useInviteUrlLoader(): ReturnType { en: { workspace: { inviteAccepted: 'Invite Accepted', - addedToWorkspace: 'You have been added to {workspaceName}', + addedToNamedWorkspace: 'You have been added to {workspaceName}', + viewWorkspace: 'View workspace', inviteFailed: 'Failed to Accept Invite', inviteSsoUnavailable: 'Ask your admin to add you', inviteSsoUnavailableDetail: 'SSO accounts cannot accept invite links', inviteDirectoryManaged: 'Admin manages membership', - inviteDirectoryManagedDetail: 'Ask your organization admin' + inviteDirectoryManagedDetail: 'Ask your organization admin', + switchFailed: 'Failed to switch workspace' }, g: { unknownError: 'Unknown error' } } @@ -122,7 +115,7 @@ describe('useInviteUrlLoader', () => { await loadInviteFromUrl() expect(useTeamWorkspaceStore().acceptInvite).not.toHaveBeenCalled() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(mockRouterReplace).not.toHaveBeenCalled() }) @@ -163,17 +156,56 @@ describe('useInviteUrlLoader', () => { expect(useTeamWorkspaceStore().acceptInvite).toHaveBeenCalledWith( 'valid-token' ) - expect(mockToastAdd).toHaveBeenCalledWith({ - severity: 'success', - summary: 'Invite Accepted', - detail: { - text: 'You have been added to Test Workspace', - workspaceId: 'ws-123', - workspaceName: 'Test Workspace' - }, - group: 'invite-accepted', - closable: true + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + action: expect.objectContaining({ label: 'View workspace' }), + description: 'You have been added to Test Workspace', + kind: 'success', + title: 'Invite Accepted' + }) + ]) + }) + + it.for([ + { + name: 'dismisses the toast once the switch succeeds', + switchWorkspace: () => Promise.resolve(), + toasts: [] + }, + { + name: 'keeps the toast and reports a failed switch', + switchWorkspace: () => Promise.reject(new Error('switch failed')), + toasts: [ + expect.objectContaining({ + kind: 'success', + title: 'Invite Accepted' + }), + expect.objectContaining({ + duration: 5000, + kind: 'error', + title: 'Failed to switch workspace' + }) + ] + } + ])('View workspace $name', async ({ switchWorkspace, toasts }) => { + mockRouteQuery.value = { invite: 'valid-token' } + vi.mocked(useTeamWorkspaceStore().acceptInvite).mockResolvedValue({ + workspaceId: 'ws-123', + workspaceName: 'Test Workspace' }) + vi.mocked(useTeamWorkspaceStore().switchWorkspace).mockImplementation( + switchWorkspace + ) + await useInviteUrlLoader().loadInviteFromUrl() + const action = useToast().toasts.at(-1)?.action + assert(action) + + await action.onClick() + + expect(useTeamWorkspaceStore().switchWorkspace).toHaveBeenCalledWith( + 'ws-123' + ) + expect(useToast().toasts).toEqual(toasts) }) it('shows the invalid-link dialog instead of a toast on 404', async () => { @@ -188,7 +220,7 @@ describe('useInviteUrlLoader', () => { expect( vi.mocked(useDialogService().showInviteLinkInvalidDialog) ).toHaveBeenCalled() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) }) @@ -211,15 +243,14 @@ describe('useInviteUrlLoader', () => { expect( vi.mocked(useDialogService().showInviteWrongAccountDialog) ).toHaveBeenCalledWith({ inviteToken: 'other-account-token' }) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) - const DIRECTORY_TOAST = { - severity: 'info', - summary: 'Admin manages membership', - detail: 'Ask your organization admin', - closable: true - } + const DIRECTORY_TOAST = expect.objectContaining({ + description: 'Ask your organization admin', + kind: 'info', + title: 'Admin manages membership' + }) it.for([ { @@ -227,7 +258,7 @@ describe('useInviteUrlLoader', () => { sso: true, code: 'membership_managed_by_directory', wrongAccountDialogs: 0, - toasts: [[DIRECTORY_TOAST]] + toasts: [DIRECTORY_TOAST] }, { name: 'a directory-managed refusal with sso_enabled off opens the wrong-account dialog', @@ -256,7 +287,7 @@ describe('useInviteUrlLoader', () => { expect( vi.mocked(useDialogService().showInviteWrongAccountDialog) ).toHaveBeenCalledTimes(wrongAccountDialogs) - expect(mockToastAdd.mock.calls).toEqual(toasts) + expect(useToast().toasts).toEqual(toasts) expect(preservedQueryMocks.clearPreservedQuery).toHaveBeenCalledWith( 'invite' ) @@ -274,9 +305,12 @@ describe('useInviteUrlLoader', () => { expect( vi.mocked(useDialogService().showInviteLinkInvalidDialog) ).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + title: 'Failed to Accept Invite' + }) + ]) }) it('falls back to the toast when the dialog chunk fails to load', async () => { @@ -293,9 +327,12 @@ describe('useInviteUrlLoader', () => { const { loadInviteFromUrl } = useInviteUrlLoader() await expect(loadInviteFromUrl()).resolves.toBeUndefined() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + title: 'Failed to Accept Invite' + }) + ]) vi.mocked(useDialogService().showInviteLinkInvalidDialog).mockReset() }) @@ -311,10 +348,8 @@ describe('useInviteUrlLoader', () => { expect(useTeamWorkspaceStore().acceptInvite).toHaveBeenCalledWith( 'invalid-token' ) - expect(mockToastAdd).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed to Accept Invite', - detail: 'Invalid invite' + expect(useToast().error).toHaveBeenCalledWith('Failed to Accept Invite', { + description: 'Invalid invite' }) }) @@ -376,10 +411,8 @@ describe('useInviteUrlLoader', () => { expect(useTeamWorkspaceStore().acceptInvite).toHaveBeenCalledWith( 'any-token-format==' ) - expect(mockToastAdd).toHaveBeenCalledWith({ - severity: 'error', - summary: 'Failed to Accept Invite', - detail: 'Invalid token' + expect(useToast().error).toHaveBeenCalledWith('Failed to Accept Invite', { + description: 'Invalid token' }) }) @@ -466,8 +499,8 @@ describe('useInviteUrlLoader', () => { vi.mocked(useTeamWorkspaceStore().acceptInvite).mock.calls.length ).toBe(accepts ? 1 : 0) expect( - mockToastAdd.mock.calls.some( - ([toast]) => toast.summary === 'Ask your admin to add you' + useToast().toasts.some( + ({ title }) => title === 'Ask your admin to add you' ) ).toBe(!accepts) expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) diff --git a/src/platform/workspace/composables/useInviteUrlLoader.ts b/src/platform/workspace/composables/useInviteUrlLoader.ts index 9d35d7c4f87..d4e30c21c08 100644 --- a/src/platform/workspace/composables/useInviteUrlLoader.ts +++ b/src/platform/workspace/composables/useInviteUrlLoader.ts @@ -1,4 +1,4 @@ -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { useI18n } from 'vue-i18n' import { useRoute, useRouter } from 'vue-router' @@ -12,10 +12,12 @@ import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQuery import { reportError } from '@/platform/telemetry/reportError' import { useDialogService } from '@/services/dialogService' import { useAuthStore } from '@/stores/authStore' +import { getErrorMessage } from '@/utils/errorUtil' import { WorkspaceApiError } from '../api/workspaceApi' import { MEMBERSHIP_MANAGED_BY_DIRECTORY } from '../api/workspaceApiError' import { useTeamWorkspaceStore } from '../stores/teamWorkspaceStore' +import { useWorkspaceSwitch } from './useWorkspaceSwitch' function isDirectoryManagedRefusal(error: unknown): boolean { return ( @@ -41,6 +43,7 @@ export function useInviteUrlLoader() { const router = useRouter() const { t } = useI18n() const toast = useToast() + const { switchWorkspace } = useWorkspaceSwitch() const dialogService = useDialogService() const workspaceStore = useTeamWorkspaceStore() const authStore = useAuthStore() @@ -93,11 +96,8 @@ export function useInviteUrlLoader() { } if (authStore.signedInWithSso && authStore.currentUser === null) { - toast.add({ - severity: 'info', - summary: t('workspace.inviteSsoUnavailable'), - detail: t('workspace.inviteSsoUnavailableDetail'), - closable: true + toast.info(t('workspace.inviteSsoUnavailable'), { + description: t('workspace.inviteSsoUnavailableDetail') }) cleanupUrlParams() clearPreservedQuery(INVITE_NAMESPACE) @@ -107,20 +107,22 @@ export function useInviteUrlLoader() { try { const result = await workspaceStore.acceptInvite(inviteParam) - toast.add({ - severity: 'success', - summary: t('workspace.inviteAccepted'), - detail: { - text: t( - 'workspace.addedToWorkspace', - { workspaceName: result.workspaceName }, - { escapeParameter: false } - ), - workspaceName: result.workspaceName, - workspaceId: result.workspaceId - }, - group: 'invite-accepted', - closable: true + const inviteToastId = toast.success(t('workspace.inviteAccepted'), { + description: t( + 'workspace.addedToNamedWorkspace', + { workspaceName: result.workspaceName }, + { escapeParameter: false } + ), + action: { + label: t('workspace.viewWorkspace'), + onClick: async () => { + if (await switchWorkspace(result.workspaceId)) { + toast.dismiss(inviteToastId) + } else { + toast.error(t('workspace.switchFailed'), { duration: 5000 }) + } + } + } }) } catch (error) { await presentAcceptFailure(error, inviteParam) @@ -146,11 +148,8 @@ export function useInviteUrlLoader() { ? error.status : undefined if (isDirectoryManagedRefusal(error)) { - toast.add({ - severity: 'info', - summary: t('workspace.inviteDirectoryManaged'), - detail: t('workspace.inviteDirectoryManagedDetail'), - closable: true + toast.info(t('workspace.inviteDirectoryManaged'), { + description: t('workspace.inviteDirectoryManagedDetail') }) return } @@ -173,10 +172,8 @@ export function useInviteUrlLoader() { errorType: 'error_accepting_workspace_invite', surface: 'workspace' }) - toast.add({ - severity: 'error', - summary: t('workspace.inviteFailed'), - detail: error instanceof Error ? error.message : t('g.unknownError') + toast.error(t('workspace.inviteFailed'), { + description: getErrorMessage(error) ?? t('g.unknownError') }) } diff --git a/src/platform/workspace/composables/useMembersPanel.test.ts b/src/platform/workspace/composables/useMembersPanel.test.ts index ad95cad3e01..b6e6e497f98 100644 --- a/src/platform/workspace/composables/useMembersPanel.test.ts +++ b/src/platform/workspace/composables/useMembersPanel.test.ts @@ -1,4 +1,5 @@ import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogService } from '@/services/dialogService' import { getActivePinia } from 'pinia' import type { Pinia } from 'pinia' @@ -218,8 +219,6 @@ describe('sortPendingInvites', () => { }) }) -const mockToastAdd = vi.fn() - const { mockMaxSeats, mockOccupiedSeats, @@ -334,13 +333,6 @@ function setOriginalOwner(id = 'creator-1') { ] } -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ add: mockToastAdd }) - }) -) - vi.mock(import('@/platform/workspace/composables/useWorkspaceUI')) vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) @@ -669,11 +661,9 @@ describe('useMembersPanel', () => { const panel = await setup() await panel.handleResendInvite(createInvite({ id: 'inv-1' })) expect(workspaceStore.resendInvite).toHaveBeenCalledWith('inv-1') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'success', - summary: 'workspacePanel.toast.inviteResent' - }) + expect(useToast().success).toHaveBeenCalledWith( + 'workspacePanel.toast.inviteResent', + { duration: 2000 } ) }) @@ -683,11 +673,8 @@ describe('useMembersPanel', () => { ) const panel = await setup() await panel.handleResendInvite(createInvite({ id: 'inv-1' })) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - summary: 'workspacePanel.toast.inviteResendFailed' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'workspacePanel.toast.inviteResendFailed' ) }) }) diff --git a/src/platform/workspace/composables/useMembersPanel.ts b/src/platform/workspace/composables/useMembersPanel.ts index 32cfe49f998..69e91e95a6c 100644 --- a/src/platform/workspace/composables/useMembersPanel.ts +++ b/src/platform/workspace/composables/useMembersPanel.ts @@ -1,6 +1,6 @@ import type { MenuItem } from '@/components/ui/menu/types' import { storeToRefs } from 'pinia' -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { computed, ref } from 'vue' import { useI18n } from 'vue-i18n' @@ -357,16 +357,9 @@ export function useMembersPanel() { if (!permissions.value.canManageInvites) return try { await resendInvite(invite.id) - toast.add({ - severity: 'success', - summary: t('workspacePanel.toast.inviteResent'), - life: 2000 - }) + toast.success(t('workspacePanel.toast.inviteResent'), { duration: 2000 }) } catch { - toast.add({ - severity: 'error', - summary: t('workspacePanel.toast.inviteResendFailed') - }) + toast.error(t('workspacePanel.toast.inviteResendFailed')) } } diff --git a/src/platform/workspace/composables/useResubscribe.test.ts b/src/platform/workspace/composables/useResubscribe.test.ts index 6c58406f0c7..aa700744df0 100644 --- a/src/platform/workspace/composables/useResubscribe.test.ts +++ b/src/platform/workspace/composables/useResubscribe.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import { computed, createApp, defineComponent, ref } from 'vue' import type { App } from 'vue' import { createI18n } from 'vue-i18n' @@ -15,8 +16,7 @@ import { useResubscribe as createResubscribe } from './useResubscribe' const state = vi.hoisted(() => ({ shouldUseWorkspaceBilling: true, canManageSubscriptionLifecycle: true, - canReactivatePlan: true, - toastAdd: vi.fn() + canReactivatePlan: true })) vi.mock(import('@/composables/billing/useBillingContext')) @@ -31,13 +31,6 @@ vi.mock(import('@/platform/workspace/composables/useWorkspaceUI')) vi.mock(import('@/platform/telemetry')) -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ add: state.toastAdd }) - }) -) - const apps: App[] = [] function useResubscribe(): ReturnType { @@ -94,7 +87,7 @@ describe('useResubscribe', () => { expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() - expect(state.toastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(isResubscribing.value).toBe(false) }) @@ -108,7 +101,7 @@ describe('useResubscribe', () => { expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() - expect(state.toastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(isResubscribing.value).toBe(false) }) @@ -181,9 +174,12 @@ describe('useResubscribe', () => { // Exactly one started event on the legacy success rail: the pre-call start, // with no duplicate post-await started/pending emitted after resubscribe() resolves. expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledTimes(1) - expect(state.toastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'success', + title: 'subscription.resubscribeSuccess' + }) + ]) }) it('shows an error and resets loading when resubscription fails', async () => { @@ -195,12 +191,9 @@ describe('useResubscribe', () => { await handleResubscribe() expect(mockBillingContext().resubscribe).toHaveBeenCalledOnce() - expect(state.toastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Resubscribe failed for person@example.com' - }) - ) + expect(useToast().error).toHaveBeenCalledWith('g.error', { + description: 'Resubscribe failed for person@example.com' + }) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'resubscribe', stage: 'failed', diff --git a/src/platform/workspace/composables/useResubscribe.ts b/src/platform/workspace/composables/useResubscribe.ts index 93acac83d91..f9db644ba4f 100644 --- a/src/platform/workspace/composables/useResubscribe.ts +++ b/src/platform/workspace/composables/useResubscribe.ts @@ -1,4 +1,4 @@ -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { ref } from 'vue' import { useI18n } from 'vue-i18n' @@ -55,11 +55,7 @@ export function useResubscribe() { duration_ms: Date.now() - startedAt }) } - toast.add({ - severity: 'success', - summary: t('subscription.resubscribeSuccess'), - life: 5000 - }) + toast.success(t('subscription.resubscribeSuccess'), { duration: 5000 }) } catch (error) { const detail = error instanceof Error && error.message.trim() @@ -75,11 +71,7 @@ export function useResubscribe() { duration_ms: Date.now() - startedAt }) }) - toast.add({ - severity: 'error', - summary: t('g.error'), - detail - }) + toast.error(t('g.error'), { description: detail }) } finally { isResubscribing.value = false } diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index db7df9874d4..0a41827ea9d 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -1,3 +1,4 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { render } from '@testing-library/vue' import type { Mock } from 'vitest' @@ -198,9 +199,6 @@ const { mockReportError, mockPlans, mockResubscribe, - mockToastAdd, - mockToastRemove, - mockToastRemoveGroup, mockListSavedPaymentMethods, mockShowDowngradeToPersonalDialog, mockIsTeamPlan, @@ -225,9 +223,6 @@ const { mockReportError: vi.fn(), mockPlans: { value: [] as Plan[] }, mockResubscribe: vi.fn(), - mockToastAdd: vi.fn(), - mockToastRemove: vi.fn(), - mockToastRemoveGroup: vi.fn(), mockListSavedPaymentMethods: vi.fn(), mockShowDowngradeToPersonalDialog: vi.fn(), mockIsTeamPlan: { value: false }, @@ -413,23 +408,18 @@ vi.mock(import('@/config/comfyApi'), () => ({ getComfyPlatformBaseUrl: () => 'https://platform.comfy.org' })) -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ - add: mockToastAdd, - remove: mockToastRemove, - removeGroup: mockToastRemoveGroup - }) - }) -) - vi.mock(import('@/platform/telemetry')) vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: mockReportError })) +function latestPaymentRecoveryAction() { + const toast = useToast().toasts.at(-1) + assert(toast?.kind === 'warning' && toast.action) + return toast.action.onClick +} + const i18n = createI18n({ legacy: false, locale: 'en', @@ -437,9 +427,11 @@ const i18n = createI18n({ en: { g: { error: 'Error', warning: 'Warning' }, subscription: { - subscribeFailed: 'Subscription failed', - resubscribeSuccess: 'Subscription restored', planLoadErrorRetry: 'Try again', + planNotAvailable: 'This plan is not available', + resubscribeSuccess: 'Subscription restored', + subscribeFailed: 'Subscription failed', + unableToSubscribe: 'Unable to subscribe', tiers: { standard: { name: 'Standard' }, creator: { name: 'Creator' } @@ -1112,9 +1104,10 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Apply quote before continuing' + description: 'Apply quote before continuing' }) ) }) @@ -1229,8 +1222,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('preview') expect(checkout.previewData.value?.quote_id).toBe('quote_new') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Quote changed' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Quote changed' }) ) }) @@ -1258,10 +1252,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.previewData.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - detail: 'Quote refresh failed' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Quote refresh failed' }) ) }) @@ -1382,7 +1375,6 @@ describe('useSubscriptionCheckout', () => { ...refreshedQuote } mockPreviewSubscribe.mockResolvedValueOnce(refreshedPreview) - mockToastAdd.mockClear() await checkout.handleConfirmTransition() @@ -1437,9 +1429,9 @@ describe('useSubscriptionCheckout', () => { expect(mockSubscribe).not.toHaveBeenCalled() expect(checkout.previewData.value).toStrictEqual(refreshedPreview) expect(checkout.checkoutStep.value).not.toBe('pricing') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Reactivation amount changed' }) - ) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: 'Reactivation amount changed' + }) } ) @@ -1496,9 +1488,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(checkout.reactivationRequired.value).toBe(false) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Reactivate first' }) - ) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: 'Reactivate first' + }) }) it('returns to confirmation without an error when a subscribe reactivation block stands', async () => { @@ -1530,8 +1522,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(checkout.reactivationRequired.value).toBe(true) - expect(mockToastAdd).not.toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Reactivate first' }) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ description: 'Reactivate first' }) ) }) @@ -1561,9 +1553,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe() expect(checkout.reactivationRequired.value).toBe(false) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Reactivate first' }) - ) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: 'Reactivate first' + }) }) it('shows error toast when preview is disallowed', async () => { @@ -1579,11 +1571,9 @@ describe('useSubscriptionCheckout', () => { }) expect(checkout.checkoutStep.value).toBe('pricing') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Not allowed' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Not allowed' }) ) }) @@ -1619,7 +1609,7 @@ describe('useSubscriptionCheckout', () => { } ) - it('offers a retry action when the billing portal popup is blocked', async () => { + it('warns when the billing portal popup is blocked', async () => { mockOpen.mockReturnValueOnce(null) const checkout = await submitRejectedPreview( 'SUBSCRIPTION_PAYMENT_REQUIRED' @@ -1629,26 +1619,23 @@ describe('useSubscriptionCheckout', () => { expect(globalThis.location.href).toBe( 'https://app.test/subscribe?invite=secret#token' ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - group: 'payment-recovery', - severity: 'warn', - detail: expect.objectContaining({ - text: 'Payment popup blocked', - actionLabel: 'Try again', - onAction: expect.any(Function) - }) + action: { label: 'Try again', onClick: expect.any(Function) }, + description: 'Payment popup blocked', + kind: 'warning', + title: 'Warning' }) - ) + ]) }) it('opens the portal and arms the focus refresh when the retry action is clicked', async () => { mockOpen.mockReturnValueOnce(null) await submitRejectedPreview('SUBSCRIPTION_PAYMENT_REQUIRED') - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! + const onAction = latestPaymentRecoveryAction() mockOpen.mockReturnValueOnce({}) - detail.onAction() + onAction() expect(mockOpen).toHaveBeenLastCalledWith( 'https://billing.stripe.com/portal', @@ -1663,13 +1650,13 @@ describe('useSubscriptionCheckout', () => { const checkout = await submitRejectedPreview( 'SUBSCRIPTION_PAYMENT_REQUIRED' ) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ group: 'payment-recovery' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ action: expect.any(Object), kind: 'warning' }) + ]) checkout.handleBackToPricing() - expect(mockToastRemoveGroup).toHaveBeenCalledWith('payment-recovery') + expect(useToast().toasts).toEqual([]) }) it('removes the retry toast when the checkout composable is disposed', async () => { @@ -1691,13 +1678,13 @@ describe('useSubscriptionCheckout', () => { tierKey: 'standard', billingCycle: 'yearly' }) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ group: 'payment-recovery' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ action: expect.any(Object), kind: 'warning' }) + ]) unmount() - expect(mockToastRemoveGroup).toHaveBeenCalledWith('payment-recovery') + expect(useToast().toasts).toEqual([]) }) it('refreshes status on return even after checkout is disposed', async () => { @@ -1719,13 +1706,13 @@ describe('useSubscriptionCheckout', () => { tierKey: 'standard', billingCycle: 'yearly' }) - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! + const onAction = latestPaymentRecoveryAction() // Click retry (a real gesture opens the popup this time), then close // checkout — completing payment in that popup and returning must still // refresh status even though the checkout that armed this is gone. mockOpen.mockReturnValueOnce({}) - detail.onAction() + onAction() unmount() window.dispatchEvent(new Event('focus')) @@ -1764,8 +1751,9 @@ describe('useSubscriptionCheckout', () => { 'Plan change is unavailable' ) expect(mockGetPaymentPortalUrl).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Plan change is unavailable' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Plan change is unavailable' }) ) }) @@ -1783,9 +1771,10 @@ describe('useSubscriptionCheckout', () => { expect(globalThis.location.href).toBe( 'https://app.test/subscribe?invite=secret#token' ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Update your payment method before changing plans' + description: 'Update your payment method before changing plans' }) ) }) @@ -1806,8 +1795,9 @@ describe('useSubscriptionCheckout', () => { surface: 'workspace', errorType: 'billing_portal_open_failure' }) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Portal unavailable' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Portal unavailable' }) ) }) @@ -1840,9 +1830,10 @@ describe('useSubscriptionCheckout', () => { expect(globalThis.location.href).toBe( 'https://app.test/subscribe?invite=secret#token' ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Update your payment method before changing plans' + description: 'Update your payment method before changing plans' }) ) }) @@ -1976,9 +1967,10 @@ describe('useSubscriptionCheckout', () => { surface: 'workspace', errorType: 'billing_portal_open_failure' }) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Update your payment method before changing plans' + description: 'Update your payment method before changing plans' }) ) }) @@ -2072,9 +2064,9 @@ describe('useSubscriptionCheckout', () => { } ]) - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! + const onAction = latestPaymentRecoveryAction() mockOpen.mockReturnValueOnce({}) - detail.onAction() + onAction() leaveAndReturn() expect(portalEvents().slice(1)).toEqual([ @@ -2099,9 +2091,9 @@ describe('useSubscriptionCheckout', () => { mockOpen.mockReturnValueOnce(null) await submitRejectedPreview('SUBSCRIPTION_PAYMENT_REQUIRED') - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! + const onAction = latestPaymentRecoveryAction() mockOpen.mockReturnValueOnce(null) - detail.onAction() + onAction() leaveAndReturn() const blocked = { @@ -2194,11 +2186,9 @@ describe('useSubscriptionCheckout', () => { billingCycle: 'yearly' }) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'This plan is not available' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Unable to subscribe', + expect.objectContaining({ description: 'This plan is not available' }) ) expect(mockFetchPlans).toHaveBeenCalledOnce() }) @@ -2253,11 +2243,9 @@ describe('useSubscriptionCheckout', () => { billingCycle: 'yearly' }) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Network error' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Network error' }) ) }) @@ -2435,7 +2423,7 @@ describe('useSubscriptionCheckout', () => { expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ stage: 'intent', outcome: 'pending' }) ) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(useTelemetry()?.trackBeginCheckout).toHaveBeenCalledWith( expect.objectContaining({ tier: 'creator', @@ -2493,12 +2481,9 @@ describe('useSubscriptionCheckout', () => { expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ stage: 'intent', outcome: 'pending' }) ) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'success', - summary: 'Subscription updated' - }) - ) + expect(useToast().success).toHaveBeenCalledWith('Subscription updated', { + duration: 5000 + }) }) it('does not duplicate telemetry owned by the Team downgrade orchestration', async () => { @@ -2656,7 +2641,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.previewData.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledOnce() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) }) it.for([false, true])( @@ -2673,7 +2660,9 @@ describe('useSubscriptionCheckout', () => { expect(mockPreviewSubscribe).not.toHaveBeenCalled() expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.selectedTeamStop.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledOnce() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) } ) }) @@ -2860,20 +2849,20 @@ describe('useSubscriptionCheckout', () => { ) expect(checkout.checkoutStep.value).toBe('pricing') expect(mockOpen).not.toHaveBeenCalled() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('does nothing when the retry action is clicked after returning to pricing', async () => { mockOpen.mockReturnValueOnce(null) const { checkout, selection } = await startTeamPaymentRecovery() await selection - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! + const onAction = latestPaymentRecoveryAction() // The retry toast can survive a reset that raced ahead of removing it; // its action must still refuse to reopen a URL from the old attempt. checkout.handleBackToPricing() mockOpen.mockClear() - detail.onAction() + onAction() expect(mockOpen).not.toHaveBeenCalled() }) @@ -2889,12 +2878,13 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.selectedTeamStop.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledOnce() - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - detail: 'Update your payment method before changing plans' + description: 'Update your payment method before changing plans', + kind: 'error', + title: 'Error' }) - ) + ]) }) it('keeps the backend quote for a fresh subscription', async () => { @@ -3023,7 +3013,7 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value).toEqual(preview) expect(checkout.previewVariant.value).toBe('team-change') - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) mockPreviewSubscribe.mockResolvedValueOnce({ ...preview, @@ -3067,8 +3057,8 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value).toBeNull() expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.selectedTeamStop.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) @@ -3096,7 +3086,7 @@ describe('useSubscriptionCheckout', () => { expect(checkout.checkoutStep.value).toBe('preview') expect(checkout.previewVariant.value).toBe('team-new') expect(checkout.reactivationRequired.value).toBe(false) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('bounces a cancelled subscriber back to pricing when the preview request fails', async () => { @@ -3117,8 +3107,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value).toBeNull() expect(checkout.checkoutStep.value).toBe('pricing') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error', detail: 'not supported' }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'not supported' }) ) }) @@ -3214,8 +3205,9 @@ describe('useSubscriptionCheckout', () => { }) expect(mockOpenHostedBillingTab).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Team plan unavailable' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Team plan', + expect.objectContaining({ description: 'Team plan unavailable' }) ) }) @@ -3559,9 +3551,10 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value?.credits_next_period_cents).toBe( 300_000 ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Reactivation confirmation required' + description: 'Reactivation confirmation required' }) ) }) @@ -3615,9 +3608,10 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value?.proration_at).toBe( '2026-07-29T12:16:00Z' ) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Reactivation confirmation required' + description: 'Reactivation confirmation required' }) ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( @@ -3676,8 +3670,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ stage: 'intent', outcome: 'pending' }) @@ -3715,11 +3709,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe(true) expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Reactivation amount changed' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Reactivation amount changed' }) ) expect(checkout.previewData.value?.cost_today_cents).toBe(120_000) @@ -3763,11 +3755,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.isSubscribing.value).toBe(false) expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'status unavailable' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'status unavailable' }) ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ stage: 'intent', outcome: 'pending' }) @@ -3808,8 +3798,8 @@ describe('useSubscriptionCheckout', () => { expect(mockSubscribe).not.toHaveBeenCalled() expect(checkout.checkoutStep.value).toBe('pricing') expect(checkout.previewData.value).toBeNull() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) @@ -3865,9 +3855,10 @@ describe('useSubscriptionCheckout', () => { expect(checkout.reactivationRequired.value).toBe(true) expect(checkout.previewData.value).toStrictEqual(preview) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Reactivation confirmation required' + description: 'Reactivation confirmation required' }) ) expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( @@ -3975,8 +3966,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) }) @@ -3995,11 +3986,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Team payment failed' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Team payment failed' }) ) expect(useTelemetry()?.trackBeginCheckout).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ @@ -4032,8 +4021,9 @@ describe('useSubscriptionCheckout', () => { expect(mockSubscribe).not.toHaveBeenCalled() expect(checkout.checkoutStep.value).toBe('pricing') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'not supported' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Team plan', + expect.objectContaining({ description: 'not supported' }) ) }) @@ -4072,8 +4062,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleTeamSubscribe() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) expect(checkout.previewData.value?.cost_today_cents).toBe(110_000) @@ -4922,17 +4912,14 @@ describe('useSubscriptionCheckout', () => { await checkout.handleAddCreditCard() - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - group: 'payment-recovery', - severity: 'warn', - detail: expect.objectContaining({ - text: 'Payment popup blocked', - actionLabel: 'Try again', - onAction: expect.any(Function) - }) + action: { label: 'Try again', onClick: expect.any(Function) }, + description: 'Payment popup blocked', + kind: 'warning', + title: 'Warning' }) - ) + ]) expect(useBillingOperationStore().startOperation).toHaveBeenCalledWith( 'op-blocked', 'subscription', @@ -4940,14 +4927,18 @@ describe('useSubscriptionCheckout', () => { 'https://stripe.com/pay' ) - const [{ detail }] = mockToastAdd.mock.calls.at(-1)! - openSpy.mockClear().mockReturnValue({} as Window) - detail.onAction() - expect(openSpy).toHaveBeenLastCalledWith( + const onAction = latestPaymentRecoveryAction() + openSpy.mockClear().mockReturnValue(window) + onAction() + expect(openSpy).toHaveBeenCalledExactlyOnceWith( 'https://stripe.com/pay', '_blank' ) + checkout.handleBackToPricing() + openSpy.mockClear() + onAction() + expect(openSpy).not.toHaveBeenCalled() openSpy.mockRestore() }) @@ -4965,11 +4956,9 @@ describe('useSubscriptionCheckout', () => { expect(openSpy).not.toHaveBeenCalled() expect(useBillingOperationStore().startOperation).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Stripe unavailable' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Stripe unavailable' }) ) openSpy.mockRestore() }) @@ -5365,11 +5354,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleAddCreditCard() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Payment failed' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Payment failed' }) ) expect(useTelemetry()?.trackBeginCheckout).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ @@ -5470,12 +5457,13 @@ describe('useSubscriptionCheckout', () => { new Error('Your bank declined this payment.') ) await checkout.handleConfirmTransition() - const declineToast = mockToastAdd.mock.calls - .map(([message]) => message) - .find( - (message) => message.detail === 'Your bank declined this payment.' - ) - expect(declineToast).toBeDefined() + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'Your bank declined this payment.', + kind: 'error', + title: 'Error' + }) + ]) mockSubscribe.mockResolvedValueOnce({ status: 'subscribed', @@ -5484,7 +5472,7 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(checkout.checkoutStep.value).toBe('success') - expect(mockToastRemove).toHaveBeenCalledWith(declineToast) + expect(useToast().toasts).toEqual([]) }) it('counts the conversion and announces a subscribe the server charged for', async () => { @@ -5510,12 +5498,9 @@ describe('useSubscriptionCheckout', () => { payment_intent_source: undefined, billing_op_id: 'op-3' }) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'success', - summary: 'Subscription updated' - }) - ) + expect(useToast().success).toHaveBeenCalledWith('Subscription updated', { + duration: 5000 + }) }) it('counts neither for a subscribe the server activated without a payment', async () => { @@ -5536,7 +5521,7 @@ describe('useSubscriptionCheckout', () => { expect( useTelemetry()?.trackMonthlySubscriptionSucceeded ).not.toHaveBeenCalled() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows error toast on failure', async () => { @@ -5547,11 +5532,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Transition error' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Transition error' }) ) }) @@ -5592,7 +5575,7 @@ describe('useSubscriptionCheckout', () => { 'https://billing.stripe.com/portal', '_blank' ) - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('forwards confirmReactivation true when the disclosure banner reports consent', async () => { @@ -5659,9 +5642,10 @@ describe('useSubscriptionCheckout', () => { expect(checkout.reactivationRequired.value).toBe(true) expect(checkout.previewData.value).toStrictEqual(preview) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - detail: 'Reactivation confirmation required' + description: 'Reactivation confirmation required' }) ) expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( @@ -5776,10 +5760,9 @@ describe('useSubscriptionCheckout', () => { expect(checkout.previewData.value?.proration_at).toBe( '2026-07-29T12:16:00Z' ) - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - detail: 'Reactivation amount changed' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Reactivation amount changed' }) ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( expect.objectContaining({ @@ -5844,13 +5827,12 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition(true) expect(checkout.checkoutStep.value).toBe('preview') - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Preview offline' }) + expect(useToast().error).toHaveBeenCalledWith( + 'Error', + expect.objectContaining({ description: 'Preview offline' }) ) - expect(mockToastAdd).not.toHaveBeenCalledWith( - expect.objectContaining({ - detail: 'Reactivation unavailable' - }) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ description: 'Reactivation unavailable' }) ) }) @@ -5863,8 +5845,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalled() }) @@ -5890,11 +5872,9 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition(true) expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: 'Reactivation amount changed' - }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'Reactivation amount changed' }) ) expect(checkout.previewData.value?.cost_today_cents).toBe(2000) @@ -5980,7 +5960,7 @@ describe('useSubscriptionCheckout', () => { expect(mockSubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackBeginCheckout).not.toHaveBeenCalled() expect(emit).not.toHaveBeenCalled() - expect(mockToastAdd).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('refreshes a required reactivation before submit and lets a retry succeed', async () => { @@ -6010,8 +5990,8 @@ describe('useSubscriptionCheckout', () => { await checkout.handleConfirmTransition() expect(mockSubscribe).not.toHaveBeenCalled() - expect(mockToastAdd).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ kind: 'error' }) ) expect(checkout.checkoutStep.value).toBe('preview') expect(checkout.previewData.value?.cost_today_cents).toBe(1600) @@ -6127,10 +6107,10 @@ describe('useSubscriptionCheckout', () => { await checkout.handleResubscribe() - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + 'Error', expect.objectContaining({ - severity: 'error', - detail: 'Resubscribe failed for person@example.com' + description: 'Resubscribe failed for person@example.com' }) ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.ts b/src/platform/workspace/composables/useSubscriptionCheckout.ts index 0ef72f34f04..fbbf7a73c06 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.ts @@ -3,11 +3,11 @@ import type { CheckoutEntryFlow, SubscriptionCheckoutType } from '@comfyorg/account-core/billing' -import { useToast } from 'primevue/usetoast' -import type { ToastMessageOptions } from 'primevue/toast' import { computed, onScopeDispose, ref, watch } from 'vue' import { useI18n } from 'vue-i18n' +import type { ToastId } from '@/types/toastId' +import { useToast } from '@/components/ui/toast/toastStore' import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingRouting } from '@/composables/billing/useBillingRouting' import { getComfyPlatformBaseUrl } from '@/config/comfyApi' @@ -25,6 +25,7 @@ import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFai import { createBillingPortalReporter } from '@/platform/telemetry/utils/billingPortalTelemetry' import { api } from '@/scripts/api' import { useAuthStore } from '@/stores/authStore' +import { getErrorMessage } from '@/utils/errorUtil' import type { Plan, PreviewSubscribeOptions, @@ -205,9 +206,11 @@ export function useSubscriptionCheckout( let checkoutMutationSeq = 0 let activeCheckoutAttemptStartedAt: number | undefined let lastEmittedPreviewRevision: string | undefined - // The payment-recovery toast is sticky and can outlive this checkout; - // drop it with the checkout rather than leave a button for a dead context. - onScopeDispose(() => toast.removeGroup('payment-recovery')) + const paymentRecoveryToasts: ToastId[] = [] + function dismissToasts(ids: ToastId[]) { + for (const id of ids.splice(0)) toast.dismiss(id) + } + onScopeDispose(() => dismissToasts(paymentRecoveryToasts)) useCheckoutJourneyExit() // Some legacy-rail status reads cannot expose a scheduled cancellation even // though the subscribe authority can see it in Stripe. Once that authority @@ -460,10 +463,8 @@ export function useSubscriptionCheckout( // a request the BE is guaranteed to reject with no way for the user to // consent. function notifyReactivationConfirmationRequired(): void { - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.reactivation.confirmationRequired') + toast.error(t('g.error'), { + description: t('subscription.preview.reactivation.confirmationRequired') }) } @@ -669,26 +670,25 @@ export function useSubscriptionCheckout( // The open above ran after an await, so it had no user gesture behind // it and got blocked. The toast's own button click is a gesture, so // retrying from there isn't blocked. - toast.add({ - group: 'payment-recovery', - severity: 'warn', - summary: t('g.warning'), - detail: { - text: t('subscription.preview.paymentPopupBlocked'), - actionLabel: t('subscription.planLoadErrorRetry'), - // The toast can outlive this attempt (a newer one started, or the - // checkout reset); a stale click must not reopen its captured URL. - onAction: () => { - if (!isCurrent()) return - if (window.open(portalUrl.href, '_blank')) { - portal.opened(billingClient) - } else { - portal.blocked(billingClient) + paymentRecoveryToasts.push( + toast.warning(t('g.warning'), { + description: t('subscription.preview.paymentPopupBlocked'), + action: { + label: t('subscription.planLoadErrorRetry'), + // The toast can outlive this attempt (a newer one started, or the + // checkout reset); a stale click must not reopen its captured URL. + onClick: () => { + if (!isCurrent()) return + if (window.open(portalUrl.href, '_blank')) { + portal.opened(billingClient) + } else { + portal.blocked(billingClient) + } + armPaymentRecoveryReturnRefresh() } - armPaymentRecoveryReturnRefresh() } - } - }) + }) + ) return 'blocked' } portal.opened(billingClient) @@ -727,10 +727,8 @@ export function useSubscriptionCheckout( } if (!isReactivationCapablePreview(freshPreview)) { resetToPricing() - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.reactivation.unavailable') + toast.error(t('g.error'), { + description: t('subscription.preview.reactivation.unavailable') }) return true } @@ -739,10 +737,8 @@ export function useSubscriptionCheckout( !previewData.value || amountDueTodayChanged(previewData.value, freshPreview) installPreview(freshPreview) - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t( + toast.error(t('g.error'), { + description: t( amountChanged ? 'subscription.preview.reactivation.amountChanged' : 'subscription.preview.reactivation.confirmationRequired' @@ -794,19 +790,15 @@ export function useSubscriptionCheckout( amountDueTodayChanged(previewData.value, freshPreview) installPreview(freshPreview) if (!amountChanged) return false - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.reactivation.amountChanged') + toast.error(t('g.error'), { + description: t('subscription.preview.reactivation.amountChanged') }) return true } reactivationRequired.value = false resetToPricing() - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.reactivation.unavailable') + toast.error(t('g.error'), { + description: t('subscription.preview.reactivation.unavailable') }) return true } @@ -930,10 +922,8 @@ export function useSubscriptionCheckout( planSlug = getApiPlanSlug(tierKey, billingCycle) } if (!planSlug) { - toast.add({ - severity: 'error', - summary: 'Unable to subscribe', - detail: 'This plan is not available' + toast.error(t('subscription.unableToSubscribe'), { + description: t('subscription.planNotAvailable') }) return } @@ -969,10 +959,8 @@ export function useSubscriptionCheckout( failure_category: 'unknown' }) } - toast.add({ - severity: 'error', - summary: 'Unable to subscribe', - detail: response?.reason || 'This plan is not available' + toast.error(t('subscription.unableToSubscribe'), { + description: response?.reason || t('subscription.planNotAvailable') }) return } @@ -991,14 +979,9 @@ export function useSubscriptionCheckout( failure_category: categorizeBillingApiError(error) }) } - const message = - error instanceof Error - ? error.message - : 'Failed to load subscription preview' - toast.add({ - severity: 'error', - summary: 'Error', - detail: message + toast.error(t('g.error'), { + description: + getErrorMessage(error) ?? t('subscription.previewLoadFailed') }) } finally { isLoadingPreview.value = false @@ -1062,10 +1045,8 @@ export function useSubscriptionCheckout( if (!embeddedCheckoutEnabled) { const teamCreditStopId = payload.stop.id if (!teamCreditStopId) { - toast.add({ - severity: 'error', - summary: t('subscription.teamPlan.name'), - detail: t('subscription.teamPlan.unavailable') + toast.error(t('subscription.teamPlan.name'), { + description: t('subscription.teamPlan.unavailable') }) resetToPricing() return @@ -1102,13 +1083,10 @@ export function useSubscriptionCheckout( checkoutStep.value = 'preview' return } - toast.add({ - severity: 'error', - summary: t('subscription.teamPlan.name'), - detail: - previewError instanceof Error - ? previewError.message - : response?.reason || t('subscription.subscribeFailed') + toast.error(t('subscription.teamPlan.name'), { + description: + getErrorMessage(previewError) ?? + (response?.reason || t('subscription.subscribeFailed')) }) checkoutStep.value = 'pricing' selectedTeamCheckout.value = null @@ -1156,13 +1134,10 @@ export function useSubscriptionCheckout( checkoutStep.value = 'preview' return } - toast.add({ - severity: 'error', - summary: t('subscription.teamPlan.name'), - detail: - previewError instanceof Error - ? previewError.message - : response?.reason || t('subscription.subscribeFailed') + toast.error(t('subscription.teamPlan.name'), { + description: + getErrorMessage(previewError) ?? + (response?.reason || t('subscription.subscribeFailed')) }) checkoutStep.value = 'pricing' selectedTeamCheckout.value = null @@ -1179,7 +1154,7 @@ export function useSubscriptionCheckout( selectedTeamCheckout.value = null activeCheckoutOperationId.value = null activeCheckoutAttemptStartedAt = undefined - toast.removeGroup('payment-recovery') + dismissToasts(paymentRecoveryToasts) } function handleBackToPricing() { @@ -1316,24 +1291,19 @@ export function useSubscriptionCheckout( // A refused attempt's toast stays until dismissed; a later attempt that // succeeds takes them down rather than leaving a decline over the success. - const attemptErrorToasts: ToastMessageOptions[] = [] + const attemptErrorToasts: ToastId[] = [] function showSubscribeError(error: unknown) { - const message: ToastMessageOptions = { - severity: 'error', - summary: t('g.error'), - detail: - error instanceof Error - ? error.message - : t('subscription.subscribeFailed') - } - attemptErrorToasts.push(message) - toast.add(message) + attemptErrorToasts.push( + toast.error(t('g.error'), { + description: getErrorMessage(error) ?? t('subscription.subscribeFailed') + }) + ) } watch(checkoutStep, (step) => { if (step !== 'success') return - for (const message of attemptErrorToasts.splice(0)) toast.remove(message) + dismissToasts(attemptErrorToasts) }) async function recoverStaleQuote(error: unknown): Promise { @@ -1346,17 +1316,13 @@ export function useSubscriptionCheckout( ) if (!refreshed) { resetToPricing() - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.quoteRefreshFailed') + toast.error(t('g.error'), { + description: t('subscription.preview.quoteRefreshFailed') }) return true } - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('subscription.preview.quoteStale') + toast.error(t('g.error'), { + description: t('subscription.preview.quoteStale') }) return true } @@ -1626,10 +1592,8 @@ export function useSubscriptionCheckout( // The poller announced every subscription operation it settled, whatever // the caller was tracking; on this rail there is no poller to do it. if (response.requiredPayment) { - toast.add({ - severity: 'success', - summary: t('billingOperation.subscriptionSuccess'), - life: 5000 + toast.success(t('billingOperation.subscriptionSuccess'), { + duration: 5000 }) } checkoutStep.value = 'success' @@ -1651,20 +1615,19 @@ export function useSubscriptionCheckout( if (!paymentWindow) { const paymentMethodUrl = initialActionUrl const opId = response.billing_op_id - toast.add({ - group: 'payment-recovery', - severity: 'warn', - summary: t('g.warning'), - detail: { - text: t('subscription.preview.paymentPopupBlocked'), - actionLabel: t('subscription.planLoadErrorRetry'), - // Not the mutation lock, which is released once the op is adopted. - onAction: () => { - if (activeCheckoutOperationId.value !== opId) return - window.open(paymentMethodUrl, '_blank') + paymentRecoveryToasts.push( + toast.warning(t('g.warning'), { + description: t('subscription.preview.paymentPopupBlocked'), + action: { + label: t('subscription.planLoadErrorRetry'), + // Not the mutation lock, which is released once the op is adopted. + onClick: () => { + if (activeCheckoutOperationId.value !== opId) return + window.open(paymentMethodUrl, '_blank') + } } - } - }) + }) + ) } } await advanceToSuccessOnOperation( @@ -1784,10 +1747,8 @@ export function useSubscriptionCheckout( const teamCheckout = selectedTeamCheckout.value if (!teamCheckout.stop.id) { - toast.add({ - severity: 'error', - summary: t('subscription.teamPlan.name'), - detail: t('subscription.teamPlan.unavailable') + toast.error(t('subscription.teamPlan.name'), { + description: t('subscription.teamPlan.unavailable') }) finishCheckoutMutation(mutationToken) return @@ -1943,15 +1904,9 @@ export function useSubscriptionCheckout( duration_ms: Date.now() - startedAt }) } - toast.add({ - severity: 'success', - summary: t('subscription.resubscribeSuccess'), - life: 5000 - }) + toast.success(t('subscription.resubscribeSuccess'), { duration: 5000 }) emit('close', true) } catch (error) { - const message = - error instanceof Error ? error.message : 'Failed to resubscribe' telemetry?.trackBillingEvent({ operation: 'resubscribe', stage: 'failed', @@ -1963,10 +1918,9 @@ export function useSubscriptionCheckout( duration_ms: Date.now() - startedAt }) }) - toast.add({ - severity: 'error', - summary: 'Error', - detail: message + toast.error(t('g.error'), { + description: + getErrorMessage(error) ?? t('subscription.resubscribeFailed') }) } finally { isResubscribing.value = false diff --git a/src/platform/workspace/composables/useWorkspaceBilling.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.test.ts index a4acf3c8ab9..237ee78d357 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.test.ts @@ -8,8 +8,8 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import type { @@ -1131,10 +1131,10 @@ describe('useWorkspaceBilling', () => { expect(mockRail.openPaymentPortal).not.toHaveBeenCalled() expect(mockWorkspaceApi.getPaymentPortalUrl).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'warn', - detail: + kind: 'warning', + description: "Couldn't open the billing page. Allow pop-ups for this site and try again." }) ]) diff --git a/src/platform/workspace/composables/useWorkspaceBilling.ts b/src/platform/workspace/composables/useWorkspaceBilling.ts index a3a4c37d128..14f21ef033a 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.ts @@ -13,13 +13,13 @@ import type { PreviewSubscribeInput } from '@comfyorg/account-core/billing' +import { useToast } from '@/components/ui/toast/toastStore' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import { useBillingPlans } from '@/platform/cloud/subscription/composables/useBillingPlans' import { useSubscriptionDialog } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import type { SubscriptionDialogOptions } from '@/platform/cloud/subscription/composables/useSubscriptionDialog' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import { reportError } from '@/platform/telemetry/reportError' import { categorizeBillingApiError } from '@/platform/telemetry/utils/billingFailureCategory' import { createBillingPortalReporter } from '@/platform/telemetry/utils/billingPortalTelemetry' @@ -584,10 +584,8 @@ export function useWorkspaceBilling(): WorkspaceBilling { } function reportBillingTabBlocked(): void { - useToastStore().add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('subscription.billingTabBlocked') + useToast().warning(t('g.warning'), { + description: t('subscription.billingTabBlocked') }) } diff --git a/src/platform/workspace/composables/useWorkspaceUrlLoader.test.ts b/src/platform/workspace/composables/useWorkspaceUrlLoader.test.ts index 5672fca768e..643767cce06 100644 --- a/src/platform/workspace/composables/useWorkspaceUrlLoader.test.ts +++ b/src/platform/workspace/composables/useWorkspaceUrlLoader.test.ts @@ -5,7 +5,7 @@ import { createApp, defineComponent } from 'vue' import type { App } from 'vue' import { createI18n } from 'vue-i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkspaceUrlLoader as createWorkspaceUrlLoader } from './useWorkspaceUrlLoader' @@ -97,7 +97,7 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).not.toHaveBeenCalled() expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('switches into a member workspace named by the link', async () => { @@ -112,7 +112,7 @@ describe('useWorkspaceUrlLoader', () => { expect(useTeamWorkspaceStore().switchWorkspace).toHaveBeenCalledWith( 'workspace-2' ) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('strips the param before switching, so a reload does not re-trigger it', async () => { @@ -157,10 +157,9 @@ describe('useWorkspaceUrlLoader', () => { await loadWorkspaceFromUrl() expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: "Couldn't open that workspace. You're still in Home Base." - }) + expect(useToast().info).toHaveBeenCalledWith( + "Couldn't open that workspace. You're still in Home Base." + ) }) it('stays on the active workspace and shows a toast for an invalid link', async () => { @@ -173,10 +172,9 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: "Couldn't open that workspace. You're still in Home Base." - }) + expect(useToast().info).toHaveBeenCalledWith( + "Couldn't open that workspace. You're still in Home Base." + ) }) it('stays on the active workspace and shows a toast for a bare ?workspace with no value', async () => { @@ -190,10 +188,9 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: "Couldn't open that workspace. You're still in Home Base." - }) + expect(useToast().info).toHaveBeenCalledWith( + "Couldn't open that workspace. You're still in Home Base." + ) }) it('treats a repeated link with one bare entry as invalid', async () => { @@ -206,10 +203,9 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: "Couldn't open that workspace. You're still in Home Base." - }) + expect(useToast().info).toHaveBeenCalledWith( + "Couldn't open that workspace. You're still in Home Base." + ) }) it('treats a joined stash value from a repeated login-redirect link as invalid', async () => { @@ -227,10 +223,9 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: "Couldn't open that workspace. You're still in Home Base." - }) + expect(useToast().info).toHaveBeenCalledWith( + "Couldn't open that workspace. You're still in Home Base." + ) }) it('is a silent no-op when the link already names the active workspace', async () => { @@ -241,7 +236,7 @@ describe('useWorkspaceUrlLoader', () => { expect(mockRouterReplace).toHaveBeenCalledWith({ query: {} }) expect(useTeamWorkspaceStore().switchWorkspace).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('restores the link after a login redirect via the preserved query', async () => { diff --git a/src/platform/workspace/composables/useWorkspaceUrlLoader.ts b/src/platform/workspace/composables/useWorkspaceUrlLoader.ts index b937fa5c195..561f348c32a 100644 --- a/src/platform/workspace/composables/useWorkspaceUrlLoader.ts +++ b/src/platform/workspace/composables/useWorkspaceUrlLoader.ts @@ -5,13 +5,13 @@ import { useI18n } from 'vue-i18n' import type { LocationQueryRaw } from 'vue-router' import { useRoute, useRouter } from 'vue-router' +import { useToast } from '@/components/ui/toast/toastStore' import { clearPreservedQuery, hydratePreservedQuery, mergePreservedQueryIntoQuery } from '@/platform/navigation/preservedQueryManager' import { PRESERVED_QUERY_NAMESPACES } from '@/platform/navigation/preservedQueryNamespaces' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkspaceSwitch } from './useWorkspaceSwitch' import { useTeamWorkspaceStore } from '../stores/teamWorkspaceStore' @@ -58,21 +58,20 @@ export function useWorkspaceUrlLoader() { const route = useRoute() const router = useRouter() const { t } = useI18n() - const toastStore = useToastStore() + const toast = useToast() const { switchWorkspace } = useWorkspaceSwitch() const { activeWorkspace, workspaceName } = storeToRefs( useTeamWorkspaceStore() ) function notifyStayed() { - toastStore.add({ - severity: 'info', - summary: t( + toast.info( + t( 'workspace.deepLinkStayed', { workspaceName: workspaceName.value }, { escapeParameter: false } ) - }) + ) } /** Strips `workspace`, keeping other params, and clears the stash. Must diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index 9165e045816..5b907cea3c7 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -6,7 +6,7 @@ import { getActiveCheckoutJourney, resolveCheckoutJourney } from '@/platform/workspace/utils/checkoutJourney' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -58,8 +58,6 @@ import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import { useBillingOperationStore } from './billingOperationStore' beforeEach(() => { - vi.mocked(useToastStore().add).mockImplementation(() => {}) - vi.mocked(useToastStore().remove).mockImplementation(() => {}) vi.mocked(useDialogStore().closeDialog).mockImplementation(() => {}) sessionStorage.clear() clearCheckoutJourney() @@ -289,14 +287,14 @@ describe('billingOperationStore', () => { it('withdraws the processing toast once the poll finds the checkout parked on a payment method, and stays quiet', async () => { await pollPhase('awaiting_payment_method') - const processing = vi.mocked(useToastStore().add).mock.calls[0][0] + const processing = vi.mocked(useToast().loading).mock.results[0].value await vi.waitFor(() => - expect(useToastStore().remove).toHaveBeenCalledWith(processing) + expect(useToast().dismiss).toHaveBeenCalledWith(processing) ) await vi.advanceTimersByTimeAsync(31_000) - expect(useToastStore().add).toHaveBeenCalledOnce() + expect(useToast().loading).toHaveBeenCalledOnce() }) it('exposes an invoice phase without an action URL as needing the customer', async () => { @@ -420,11 +418,9 @@ describe('billingOperationStore', () => { const store = useBillingOperationStore() void store.startOperation('op-1', 'subscription') - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'billingOperation.subscriptionProcessing', - group: 'billing-operation' - }) + expect(useToast().loading).toHaveBeenCalledWith( + 'billingOperation.subscriptionProcessing' + ) }) it('does not show a processing toast when the checkout owns progress', () => { @@ -439,7 +435,7 @@ describe('billingOperationStore', () => { suppressProcessingToast: true }) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows immediate processing toast for topup operations', () => { @@ -452,11 +448,9 @@ describe('billingOperationStore', () => { const store = useBillingOperationStore() void store.startOperation('op-1', 'topup') - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'billingOperation.topupProcessing', - group: 'billing-operation' - }) + expect(useToast().loading).toHaveBeenCalledWith( + 'billingOperation.topupProcessing' + ) }) describe('a resumed operation', () => { @@ -490,11 +484,11 @@ describe('billingOperationStore', () => { resumed: true }) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) serve('awaiting_payment_method') await vi.advanceTimersByTimeAsync(31_000) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it.for([['in_progress'], [undefined]] as const)( @@ -506,16 +500,14 @@ describe('billingOperationStore', () => { resumed: true }) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) serve(phase) await vi.advanceTimersByTimeAsync(0) - expect(useToastStore().add).toHaveBeenCalledOnce() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'info', - summary: 'billingOperation.subscriptionProcessing', - group: 'billing-operation' - }) + expect(useToast().loading).toHaveBeenCalledOnce() + expect(useToast().loading).toHaveBeenCalledWith( + 'billingOperation.subscriptionProcessing' + ) } ) @@ -529,11 +521,9 @@ describe('billingOperationStore', () => { 'https://invoice.stripe.com/sensitive-token' ) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: 'billingOperation.subscriptionActionRequired', - group: 'billing-operation' - }) + expect(useToast().warning).toHaveBeenCalledWith( + 'billingOperation.subscriptionActionRequired' + ) serve('in_progress') await vi.advanceTimersByTimeAsync(0) }) @@ -762,11 +752,10 @@ describe('billingOperationStore', () => { expect(billing.fetchStatus).not.toHaveBeenCalled() expect(billing.fetchBalance).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'success', - summary: 'billingOperation.subscriptionSuccess', - life: 5000 - }) + expect(useToast().success).toHaveBeenCalledWith( + 'billingOperation.subscriptionSuccess', + { duration: 5000 } + ) }) it('leaves the checkout dialog open on subscription success', async () => { @@ -1066,11 +1055,10 @@ describe('billingOperationStore', () => { await vi.advanceTimersByTimeAsync(0) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'success', - summary: 'billingOperation.topupSuccess', - life: 5000 - }) + expect(useToast().success).toHaveBeenCalledWith( + 'billingOperation.topupSuccess', + { duration: 5000 } + ) }) it('reports duration_ms as the time elapsed since the operation started', async () => { @@ -1145,11 +1133,11 @@ describe('billingOperationStore', () => { const store = useBillingOperationStore() void store.startOperation('op-1', 'subscription') - const receivedToast = vi.mocked(useToastStore().add).mock.calls[0][0] + const receivedToast = vi.mocked(useToast().loading).mock.results[0].value await vi.advanceTimersByTimeAsync(0) - expect(useToastStore().remove).toHaveBeenCalledWith(receivedToast) + expect(useToast().dismiss).toHaveBeenCalledWith(receivedToast) }) it('resolves the terminal promise even if a success side effect throws', async () => { @@ -1159,8 +1147,8 @@ describe('billingOperationStore', () => { started_at: new Date().toISOString() }) const error = new Error('toast rendering failed') - vi.mocked(useToastStore().add).mockImplementation((toast) => { - if (toast.severity === 'success') throw error + vi.mocked(useToast().success).mockImplementation(() => { + throw error }) const store = useBillingOperationStore() @@ -1183,7 +1171,7 @@ describe('billingOperationStore', () => { started_at: new Date().toISOString() }) const error = new Error('toast cleanup failed') - vi.mocked(useToastStore().remove).mockImplementationOnce(() => { + vi.mocked(useToast().dismiss).mockImplementationOnce(() => { throw error }) @@ -1243,12 +1231,13 @@ describe('billingOperationStore', () => { ) expect(store.hasPendingOperations).toBe(false) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.subscriptionFailed', - detail: 'billingOperation.subscriptionFailedDetail', - life: 7000 - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.subscriptionFailed', + { + description: 'billingOperation.subscriptionFailedDetail', + duration: 7000 + } + ) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'operation', billing_client: 'legacy', @@ -1340,9 +1329,7 @@ describe('billingOperationStore', () => { await vi.advanceTimersByTimeAsync(0) expect(store.getOperation('op-1')?.status).toBe('failed') - expect(useToastStore().add).not.toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( expect.objectContaining({ stage: 'failed', @@ -1460,12 +1447,10 @@ describe('billingOperationStore', () => { await vi.advanceTimersByTimeAsync(0) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.topupFailed', - detail: undefined, - life: 7000 - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.topupFailed', + { description: undefined, duration: 7000 } + ) }) // The bank refused to approve the charge without the customer. A failed @@ -1490,12 +1475,13 @@ describe('billingOperationStore', () => { errorMessage: 'billingOperation.authenticatePaymentDetail', actionUrl: null }) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.topupFailed', - detail: 'billingOperation.authenticatePaymentDetail', - life: 7000 - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.topupFailed', + { + description: 'billingOperation.authenticatePaymentDetail', + duration: 7000 + } + ) }) it.for([ @@ -1554,12 +1540,13 @@ describe('billingOperationStore', () => { status: 'failed', errorMessage: 'billingOperation.methodNotChargeableOffSessionDetail' }) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.subscriptionFailed', - detail: 'billingOperation.methodNotChargeableOffSessionDetail', - life: 7000 - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.subscriptionFailed', + { + description: 'billingOperation.methodNotChargeableOffSessionDetail', + duration: 7000 + } + ) }) it('does not name a payment method for a downgrade to personal', async () => { @@ -1803,11 +1790,9 @@ describe('billingOperationStore', () => { await vi.advanceTimersByTimeAsync(0) expect(store.getOperation('op-1')?.errorMessage).toBe(detail) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary, - detail, - life: 7000 + expect(useToast().error).toHaveBeenCalledWith(summary, { + description: detail, + duration: 7000 }) } ) @@ -2961,10 +2946,9 @@ describe('billingOperationStore', () => { expect(operation?.status).toBe('timeout') expect(store.hasPendingOperations).toBe(false) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.subscriptionTimeout' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.subscriptionTimeout' + ) }) it('reports duration_ms of at least the timeout threshold', async () => { @@ -3036,7 +3020,13 @@ describe('billingOperationStore', () => { expect((await terminal).status).toBe('succeeded') expect(store.getOperation('op-1')?.actionUrl).toBeNull() expect( - JSON.stringify(vi.mocked(useToastStore().add).mock.calls) + JSON.stringify([ + vi.mocked(useToast().error).mock.calls, + vi.mocked(useToast().info).mock.calls, + vi.mocked(useToast().loading).mock.calls, + vi.mocked(useToast().success).mock.calls, + vi.mocked(useToast().warning).mock.calls + ]) ).not.toContain(actionUrl) expect( JSON.stringify(vi.mocked(useTelemetry()?.trackBillingEvent)?.mock.calls) @@ -3054,21 +3044,18 @@ describe('billingOperationStore', () => { const store = useBillingOperationStore() void store.startOperation('op-1', 'subscription') - const processingToast = { - severity: 'info', - summary: 'billingOperation.subscriptionProcessing', - group: 'billing-operation' - } - expect(useToastStore().add).toHaveBeenCalledWith(processingToast) + expect(useToast().loading).toHaveBeenCalledWith( + 'billingOperation.subscriptionProcessing' + ) await vi.advanceTimersByTimeAsync(0) - expect(useToastStore().remove).toHaveBeenCalledWith(processingToast) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: 'billingOperation.subscriptionActionRequired', - group: 'billing-operation' - }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'billingOperation.subscriptionActionRequired' + }) + ]) }) it('announces verification immediately when the action URL is known at start', () => { @@ -3086,15 +3073,11 @@ describe('billingOperationStore', () => { 'https://verify.example/sensitive-token' ) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: 'billingOperation.topupActionRequired', - group: 'billing-operation' - }) - expect(useToastStore().add).not.toHaveBeenCalledWith( - expect.objectContaining({ - summary: 'billingOperation.topupProcessing' - }) + expect(useToast().warning).toHaveBeenCalledWith( + 'billingOperation.topupActionRequired' + ) + expect(useToast().loading).not.toHaveBeenCalledWith( + 'billingOperation.topupProcessing' ) }) @@ -3116,23 +3099,20 @@ describe('billingOperationStore', () => { void store.startOperation('op-1', 'subscription') await vi.advanceTimersByTimeAsync(0) - const actionRequiredToast = { - severity: 'warn', - summary: 'billingOperation.subscriptionActionRequired', - group: 'billing-operation' - } - expect(useToastStore().add).toHaveBeenCalledWith(actionRequiredToast) + expect(useToast().warning).toHaveBeenCalledWith( + 'billingOperation.subscriptionActionRequired' + ) // The verification action is gone, so the prompt pointing at it must go // too rather than asking for something the customer can no longer do. await vi.advanceTimersByTimeAsync(30_000) - expect(useToastStore().remove).toHaveBeenCalledWith(actionRequiredToast) - expect(useToastStore().add).toHaveBeenLastCalledWith({ - severity: 'info', - summary: 'billingOperation.subscriptionProcessing', - group: 'billing-operation' - }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'loading', + title: 'billingOperation.subscriptionProcessing' + }) + ]) }) it('does not re-announce verification on later polls', async () => { @@ -3149,10 +3129,9 @@ describe('billingOperationStore', () => { const actionRequiredAdds = () => vi - .mocked(useToastStore().add) + .mocked(useToast().warning) .mock.calls.filter( - (call) => - call[0].summary === 'billingOperation.subscriptionActionRequired' + ([title]) => title === 'billingOperation.subscriptionActionRequired' ).length expect(actionRequiredAdds()).toBe(1) @@ -3362,10 +3341,9 @@ describe('billingOperationStore', () => { await vi.advanceTimersByTimeAsync(121_000) await vi.runAllTimersAsync() - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.topupTimeout' - }) + expect(useToast().error).toHaveBeenCalledWith( + 'billingOperation.topupTimeout' + ) }) it('keeps polling a topup while authentication is required', async () => { @@ -3387,10 +3365,9 @@ describe('billingOperationStore', () => { actionUrl, authenticationRequiredSeen: true }) - expect(useToastStore().add).not.toHaveBeenCalledWith({ - severity: 'error', - summary: 'billingOperation.topupTimeout' - }) + expect( + vi.mocked(useToast().error).mock.calls.map(([title]) => title) + ).not.toContain('billingOperation.topupTimeout') }) }) @@ -3415,7 +3392,7 @@ describe('billingOperationStore', () => { useTeamWorkspaceStore().updateActiveWorkspace ).not.toHaveBeenCalled() expect(useSettingsDialog().show).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it.for(['failed', 'reconciliation_needed'] as const)( @@ -3434,7 +3411,7 @@ describe('billingOperationStore', () => { const operation = await terminal expect(operation.status).toBe(status) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) } ) @@ -3473,7 +3450,7 @@ describe('billingOperationStore', () => { const store = useBillingOperationStore() void store.startOperation('op-1', 'cancel') - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('resolves with the succeeded operation and refreshes status', async () => { @@ -3542,7 +3519,7 @@ describe('billingOperationStore', () => { await terminal expect(useSettingsDialog().show).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('resolves with a failed operation and default message, no toast', async () => { @@ -3563,7 +3540,7 @@ describe('billingOperationStore', () => { expect( useTeamWorkspaceStore().updateActiveWorkspace ).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( expect.objectContaining({ operation: 'operation', @@ -3599,7 +3576,7 @@ describe('billingOperationStore', () => { expect( useTeamWorkspaceStore().updateActiveWorkspace ).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith( expect.objectContaining({ operation: 'operation', @@ -3696,9 +3673,7 @@ describe('billingOperationStore', () => { expect(store.getOperation('op-1')?.status).toBe('pending') expect(store.hasPendingOperations).toBe(true) expect(resolved).toBe(false) - expect(useToastStore().add).not.toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().error).not.toHaveBeenCalled() }) it('polls pending operations immediately when the page becomes visible', async () => { diff --git a/src/platform/workspace/stores/billingOperationStore.ts b/src/platform/workspace/stores/billingOperationStore.ts index fddf19932cb..7570259f4b6 100644 --- a/src/platform/workspace/stores/billingOperationStore.ts +++ b/src/platform/workspace/stores/billingOperationStore.ts @@ -4,7 +4,6 @@ import type { SubscriptionCheckoutTier, SubscriptionCheckoutType } from '@comfyorg/account-core/billing' -import type { ToastMessageOptions } from 'primevue/toast' import type { PaymentIntent } from '@stripe/stripe-js' import { loadStripe } from '@stripe/stripe-js/pure' import { customerCanActHere } from '@comfyorg/account-core/billing' @@ -13,6 +12,7 @@ import { defineStore } from 'pinia' import { computed, ref } from 'vue' import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useToast } from '@/components/ui/toast/toastStore' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import type { TierKey } from '@/platform/cloud/subscription/constants/tierPricing' @@ -22,7 +22,6 @@ import { isCloud } from '@/platform/distribution/types' import { useTelemetry } from '@/platform/telemetry' import { reportError } from '@/platform/telemetry/reportError' import type { PaymentIntentSource } from '@/platform/telemetry/types' -import { useToastStore } from '@/platform/updates/common/toastStore' import { workspaceApi } from '@/platform/workspace/api/workspaceApi' import type { BillingAuthenticationState, @@ -30,7 +29,10 @@ import type { BillingDeclineReason, BillingRecoveryAction } from '@/platform/workspace/api/workspaceApi' -import type { ProgressToastKind } from '@/platform/workspace/billing/customerAttention' +import type { + ProgressToast, + ProgressToastKind +} from '@/platform/workspace/billing/customerAttention' import { isBlockedOnCustomerPhase, isParkedCheckout, @@ -172,14 +174,12 @@ interface FailureRecovery { export const useBillingOperationStore = defineStore('billingOperation', () => { const workspaceStore = useTeamWorkspaceStore() const { flags } = useFeatureFlags() + const toast = useToast() const operations = ref>(new Map()) const timeouts = new Map>() const intervals = new Map() const waitingWithoutActionSince = new Map() - const progressToasts = new Map< - string, - { kind: ProgressToastKind; message: ToastMessageOptions } - >() + const progressToasts = new Map() const progressToastsAwaitingFirstRead = new Set() const terminalResolvers = new Map() const terminalPromises = new Map>() @@ -249,11 +249,10 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { type: PaymentOperationType, kind: ProgressToastKind | undefined ) { - const toastStore = useToastStore() const previous = progressToasts.get(opId) if (previous?.kind === kind) return if (previous) { - toastStore.remove(previous.message) + toast.dismiss(previous.id) progressToasts.delete(opId) } if (kind === undefined) return @@ -267,14 +266,11 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { ? 'billingOperation.topupActionRequired' : 'billingOperation.topupProcessing' - const message: ToastMessageOptions = { - // 'warn' selects the prompt icon over the spinner in GlobalToast. - severity: kind === 'action' ? 'warn' : 'info', - summary: t(messageKey), - group: 'billing-operation' - } - progressToasts.set(opId, { kind, message }) - toastStore.add(message) + const id = + kind === 'action' + ? toast.warning(t(messageKey)) + : toast.loading(t(messageKey)) + progressToasts.set(opId, { kind, id }) } function announceStart( @@ -932,17 +928,12 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { useSettingsDialog().show(isCloud ? 'workspace' : 'credits') } - const toastStore = useToastStore() const messageKey = operation.type === 'subscription' ? 'billingOperation.subscriptionSuccess' : 'billingOperation.topupSuccess' - toastStore.add({ - severity: 'success', - summary: t(messageKey), - life: 5000 - }) + toast.success(t(messageKey), { duration: 5000 }) } catch (error) { reportError(error, { surface: 'billing', @@ -1045,11 +1036,9 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { } if (isPaymentOperation(operation.type) && !superseded) { - useToastStore().add({ - severity: 'error', - summary: defaultMessage, - detail: detail ?? undefined, - life: 7000 + toast.error(defaultMessage, { + description: detail ?? undefined, + duration: 7000 }) } @@ -1197,10 +1186,7 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { } if (isPaymentOperation(operation.type)) { - useToastStore().add({ - severity: 'error', - summary: message - }) + toast.error(message) } resolveTerminal(opId) @@ -1358,7 +1344,7 @@ export const useBillingOperationStore = defineStore('billingOperation', () => { const progressToast = progressToasts.get(opId) if (progressToast) { - useToastStore().remove(progressToast.message) + toast.dismiss(progressToast.id) progressToasts.delete(opId) } } diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index e88282e9064..796f15a8d4a 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -4,7 +4,7 @@ import { useAuthStore } from '@/stores/authStore' import { useDialogStore } from '@/stores/dialogStore' import { SSO_REQUIRED_DIALOG_KEY } from '@/platform/auth/sso/ssoRequiredDialogKey' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { User } from 'firebase/auth' import { storeToRefs } from 'pinia' @@ -133,8 +133,6 @@ beforeEach(() => { return error ? `${String(key)}: ${String(error)}` : String(key) }) stubFirebaseAuthHarness() - - vi.mocked(useToastStore().add).mockImplementation(() => {}) }) describe('useWorkspaceAuthStore', () => { @@ -959,7 +957,9 @@ describe('useWorkspaceAuthStore', () => { expect(token).toBeNull() expect(currentWorkspace.value).toBeNull() - expect(useToastStore().add).toHaveBeenCalledTimes(1) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) }) it.for([ @@ -995,11 +995,9 @@ describe('useWorkspaceAuthStore', () => { expect(token).toBeNull() expect(currentWorkspace.value).toBeNull() - expect( - vi - .mocked(useToastStore().add) - .mock.calls.map(([toast]) => toast.detail) - ).toEqual(toasts) + expect(useToast().toasts.map(({ description }) => description)).toEqual( + toasts + ) expect(useDialogStore().isDialogOpen(SSO_REQUIRED_DIALOG_KEY)).toBe( shown ) @@ -1108,7 +1106,7 @@ describe('useWorkspaceAuthStore', () => { expect(token).toBeNull() expect(currentWorkspace.value?.id).toBe('workspace-123') - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect( useTeamWorkspaceStore().forgetRevokedActiveWorkspace ).not.toHaveBeenCalled() @@ -2428,10 +2426,10 @@ describe('useWorkspaceAuthStore', () => { // A permanent failure resolves to null (the caller surfaces its 401), // fires the error toast keyed to the 401 code, and clears the dead session. expect(result).toBeNull() - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), expect.objectContaining({ - severity: 'error', - detail: 'workspaceAuth.errors.invalidFirebaseToken' + description: 'workspaceAuth.errors.invalidFirebaseToken' }) ) expect(unifiedToken.value).toBeNull() @@ -2468,7 +2466,7 @@ describe('useWorkspaceAuthStore', () => { const result = await store.remintUnifiedOnce('unified-token-1') expect(result).toBeNull() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(unifiedToken.value).toBe('unified-token-1') }) @@ -2567,7 +2565,7 @@ describe('useWorkspaceAuthStore', () => { await expect(mintPromise).resolves.toBe(false) expect(store.unifiedToken).toBeNull() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('coalesces concurrent re-mints and returns the winning token to every caller', async () => { @@ -2902,8 +2900,9 @@ describe('useWorkspaceAuthStore', () => { await vi.advanceTimersByTimeAsync(expiresInMs - 5 * 60 * 1000) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error', detail: detailKey }) + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: detailKey }) ) expect( useTelemetry()?.trackUnifiedAuthRefresh @@ -2969,11 +2968,9 @@ describe('useWorkspaceAuthStore', () => { tags: { failure_code: 'SSO_REQUIRED', retry_count: 0 } }) ) - expect( - vi - .mocked(useToastStore().add) - .mock.calls.map(([toast]) => toast.detail) - ).toEqual(toasts) + expect(useToast().toasts.map(({ description }) => description)).toEqual( + toasts + ) expect(useDialogStore().isDialogOpen(SSO_REQUIRED_DIALOG_KEY)).toBe( shown ) @@ -3006,7 +3003,7 @@ describe('useWorkspaceAuthStore', () => { await vi.advanceTimersByTimeAsync(expiresInMs - 5 * 60 * 1000) expect(fetch).toHaveBeenCalledTimes(1) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('does not toast on a successful refresh re-mint', async () => { @@ -3025,7 +3022,7 @@ describe('useWorkspaceAuthStore', () => { await store.mintAtLogin() await vi.advanceTimersByTimeAsync(expiresInMs - 5 * 60 * 1000) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('does not toast on a transient refresh failure and keeps the slot', async () => { @@ -3057,7 +3054,7 @@ describe('useWorkspaceAuthStore', () => { const refreshDelay = expiresInMs - 5 * 60 * 1000 await vi.advanceTimersByTimeAsync(refreshDelay) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(unifiedToken.value).toBe('unified-token-1') }) @@ -3208,7 +3205,7 @@ describe('useWorkspaceAuthStore', () => { await vi.advanceTimersByTimeAsync(60 * 60 * 1000) expect(fetch).toHaveBeenCalledTimes(5) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(useTelemetry()?.trackUnifiedAuthRefresh).toHaveBeenLastCalledWith({ outcome: 'expired', retry_count: 3 @@ -3265,7 +3262,7 @@ describe('useWorkspaceAuthStore', () => { retry_count: 3 }) expect(fetch).toHaveBeenCalledTimes(1) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect( unifiedToken.value, 'a token read failure is not a revocation; the token serves until it expires' @@ -3310,7 +3307,7 @@ describe('useWorkspaceAuthStore', () => { await vi.advanceTimersByTimeAsync(expiresInMs - 5 * 60 * 1000) expect(fetch).toHaveBeenCalledTimes(1) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) await vi.advanceTimersByTimeAsync(5000) @@ -3391,10 +3388,10 @@ describe('useWorkspaceAuthStore', () => { expect(result).toBe(false) expect(unifiedToken.value).toBeNull() - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + expect.any(String), expect.objectContaining({ - severity: 'error', - detail: 'workspaceAuth.errors.invalidFirebaseToken' + description: 'workspaceAuth.errors.invalidFirebaseToken' }) ) }) @@ -3418,7 +3415,7 @@ describe('useWorkspaceAuthStore', () => { await store.remintUnifiedOnce('unified-token-1') await vi.advanceTimersByTimeAsync(60 * 60 * 1000) - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) }) diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index 57604675748..78c852c6c75 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -37,7 +37,7 @@ import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/legacyW import { WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthError' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useAuthStore } from '@/stores/authStore' import type { AuthHeader } from '@/types/authTypes' import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes' @@ -99,10 +99,8 @@ function surfacePermanentAuthError(err: WorkspaceAuthError): void { return } console.error('Unified workspace auth revoked or invalid:', err) - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t( + useToast().error(t('g.error'), { + description: t( sessionErrorMessageKey( isSessionErrorCode(err.code) ? err.code : 'TOKEN_EXCHANGE_FAILED' ) diff --git a/src/renderer/core/canvas/canvasStore.nodePicking.test.ts b/src/renderer/core/canvas/canvasStore.nodePicking.test.ts index 3dd660e676b..d909912773c 100644 --- a/src/renderer/core/canvas/canvasStore.nodePicking.test.ts +++ b/src/renderer/core/canvas/canvasStore.nodePicking.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest' import { nextTick, watch } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import { useSettingStore } from '@/platform/settings/settingStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' @@ -48,6 +49,18 @@ describe('canvas node picking', () => { } ) + it('holds notifications for the duration of node picking', async () => { + const { store } = setup() + + store.startNodePicking() + await nextTick() + expect(useToast().held).toBe(true) + + store.stopNodePicking() + await nextTick() + expect(useToast().held).toBe(false) + }) + it('does not animate an empty graph', () => { const { store, canvas, animate } = setup() canvas.graph?.clear() diff --git a/src/renderer/core/canvas/canvasStore.ts b/src/renderer/core/canvas/canvasStore.ts index 3a276a91327..3632c84dc7e 100644 --- a/src/renderer/core/canvas/canvasStore.ts +++ b/src/renderer/core/canvas/canvasStore.ts @@ -2,6 +2,7 @@ import { useEventListener, whenever } from '@vueuse/core' import { defineStore } from 'pinia' import { computed, ref, shallowRef } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { useAppMode } from '@/composables/useAppMode' import { visibleCanvasViewport } from '@/composables/canvas/visibleCanvasViewport' @@ -110,11 +111,13 @@ export const useCanvasStore = defineStore('canvas', () => { const isInSubgraph = ref(false) const isGhostPlacing = ref(false) const isPickingNodes = ref(false) + const toast = useToast() function startNodePicking(): void { const currentCanvas = canvas.value if (!currentCanvas || isPickingNodes.value) return isPickingNodes.value = true + toast.held = true const selected = [...currentCanvas.selectedItems] const bounds = createPositionBounds( selected.length ? selected : (currentCanvas.graph?.nodes ?? []), @@ -130,6 +133,7 @@ export const useCanvasStore = defineStore('canvas', () => { function stopNodePicking(): undefined { if (!isPickingNodes.value) return isPickingNodes.value = false + toast.held = false canvas.value?.deselectAll() } diff --git a/src/renderer/extensions/compositor/composables/useCompositorEditor.test.ts b/src/renderer/extensions/compositor/composables/useCompositorEditor.test.ts index 379566d5b89..fa7ccab67aa 100644 --- a/src/renderer/extensions/compositor/composables/useCompositorEditor.test.ts +++ b/src/renderer/extensions/compositor/composables/useCompositorEditor.test.ts @@ -1,7 +1,7 @@ import { render } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useDialogStore } from '@/stores/dialogStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { createI18n } from 'vue-i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' @@ -38,10 +38,6 @@ function mountComposable(): ReturnType { return composable } -beforeEach(() => { - vi.mocked(useToastStore().add).mockImplementation(() => undefined) -}) - describe('useCompositorEditor', () => { const node = { id: toNodeId(1) } as unknown as LGraphNode @@ -52,12 +48,9 @@ describe('useCompositorEditor', () => { it('shows a toast and keeps the dialog closed without cached layers', () => { mountComposable().openCompositorEditor(node) - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'info', - summary: 'Layer editor', - detail: 'Run the workflow first' - }) + expect(useToast().info).toHaveBeenCalledWith( + 'Layer editor', + expect.objectContaining({ description: 'Run the workflow first' }) ) expect(vi.mocked(useDialogStore().showDialog)).not.toHaveBeenCalled() }) @@ -69,12 +62,9 @@ describe('useCompositorEditor', () => { mountComposable().openCompositorEditor(node) - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'info', - summary: 'Layer editor', - detail: 'Run the workflow first' - }) + expect(useToast().info).toHaveBeenCalledWith( + 'Layer editor', + expect.objectContaining({ description: 'Run the workflow first' }) ) expect(vi.mocked(useDialogStore().showDialog)).not.toHaveBeenCalled() }) @@ -88,7 +78,7 @@ describe('useCompositorEditor', () => { mountComposable().openCompositorEditor(node) - expect(vi.mocked(useToastStore().add)).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) expect(vi.mocked(useDialogStore().showDialog)).toHaveBeenCalledWith( expect.objectContaining({ key: 'global-layer-editor', diff --git a/src/renderer/extensions/compositor/composables/useCompositorEditor.ts b/src/renderer/extensions/compositor/composables/useCompositorEditor.ts index 9318f3d7f61..a7437780971 100644 --- a/src/renderer/extensions/compositor/composables/useCompositorEditor.ts +++ b/src/renderer/extensions/compositor/composables/useCompositorEditor.ts @@ -11,7 +11,7 @@ import { } from '@/renderer/extensions/layerEditor/composables/layerEditorDialog' import { LAYER_EDITOR_DIALOG_KEY } from '@/renderer/extensions/layerEditor/layerEditorDialogKey' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' export function useCompositorEditor() { @@ -22,10 +22,8 @@ export function useCompositorEditor() { !hasCompositorLayers(node) || !getCompositorInputsFingerprint(node)?.length ) { - useToastStore().add({ - severity: 'info', - summary: t('layerEditor.title'), - detail: t('compositor.runWorkflowFirst') + useToast().info(t('layerEditor.title'), { + description: t('compositor.runWorkflowFirst') }) return } diff --git a/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.test.ts b/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.test.ts index 059521a87bf..7cb21711917 100644 --- a/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.test.ts +++ b/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.test.ts @@ -1,4 +1,4 @@ -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { App } from 'vue' import { createApp, defineComponent, ref } from 'vue' @@ -32,7 +32,6 @@ vi.mock( }) ) vi.mock(import('@/base/common/downloadUtil'), () => ({ downloadBlob })) - const i18n = createI18n({ legacy: false, locale: 'en', @@ -74,10 +73,6 @@ function makeSession(glOk = true) { const node = { id: toNodeId(5) } as unknown as LGraphNode -beforeEach(() => { - vi.mocked(useToastStore().add).mockImplementation(() => undefined) -}) - describe('useCompositorPsdDownload', () => { beforeEach(() => { loadCompositorSession.mockResolvedValue(0) @@ -103,7 +98,7 @@ describe('useCompositorPsdDownload', () => { ) expect(session.dispose).toHaveBeenCalledTimes(1) expect(exporting.value).toBe(false) - expect(vi.mocked(useToastStore().add)).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('reports an error and still disposes when WebGL is unavailable', async () => { @@ -115,12 +110,12 @@ describe('useCompositorPsdDownload', () => { await downloadPsd(node) expect(downloadBlob).not.toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'layerEditor.webglUnavailable' + description: 'layerEditor.webglUnavailable', + kind: 'error' }) - ) + ]) expect(session.dispose).toHaveBeenCalledTimes(1) }) @@ -135,7 +130,12 @@ describe('useCompositorPsdDownload', () => { expect(buildSessionPsdBlob).not.toHaveBeenCalled() expect(downloadBlob).not.toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledTimes(1) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'layerEditor.exportPsdFailed', + kind: 'error' + }) + ]) expect(session.dispose).toHaveBeenCalledTimes(1) }) @@ -149,7 +149,12 @@ describe('useCompositorPsdDownload', () => { await downloadPsd(node) expect(downloadBlob).not.toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledTimes(1) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'layerEditor.exportPsdFailed', + kind: 'error' + }) + ]) expect(session.dispose).toHaveBeenCalledTimes(1) expect(exporting.value).toBe(false) }) @@ -162,7 +167,12 @@ describe('useCompositorPsdDownload', () => { await downloadPsd(node) expect(downloadBlob).not.toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledTimes(1) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'layerEditor.exportPsdFailed', + kind: 'error' + }) + ]) expect(exporting.value).toBe(false) }) diff --git a/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.ts b/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.ts index 56f64715ce2..0eb8e5aa086 100644 --- a/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.ts +++ b/src/renderer/extensions/compositor/composables/useCompositorPsdDownload.ts @@ -10,13 +10,13 @@ import { import type { LayerEditorSession } from '@/renderer/extensions/layerEditor/composables/useLayerEditorSession' import { useLayerEditorSession } from '@/renderer/extensions/layerEditor/composables/useLayerEditorSession' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' export function useCompositorPsdDownload( createSession: () => LayerEditorSession = () => useLayerEditorSession() ) { const { t } = useI18n() - const toastStore = useToastStore() + const toast = useToast() const exporting = ref(false) async function downloadPsd(node: LGraphNode): Promise { @@ -27,10 +27,8 @@ export function useCompositorPsdDownload( session = createSession() if (!session.glOk.value) { console.error('[Compositor] WebGL compositor unavailable') - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('layerEditor.webglUnavailable') + toast.error(t('g.error'), { + description: t('layerEditor.webglUnavailable') }) return } @@ -39,10 +37,8 @@ export function useCompositorPsdDownload( ) if (failed > 0) { console.error(`[Compositor] ${failed} layer(s) failed to load`) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('layerEditor.exportPsdFailed') + toast.error(t('g.error'), { + description: t('layerEditor.exportPsdFailed') }) return } @@ -50,10 +46,8 @@ export function useCompositorPsdDownload( downloadBlob(psdExportFilename(new Date()), blob) } catch (err) { console.warn('[Compositor] PSD export failed', err) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: + toast.error(t('g.error'), { + description: session && !session.glOk.value ? t('layerEditor.webglUnavailable') : t('layerEditor.exportPsdFailed') diff --git a/src/renderer/extensions/layerEditor/components/LayerEditorContent.test.ts b/src/renderer/extensions/layerEditor/components/LayerEditorContent.test.ts index 8203d5a5cd2..6733819881e 100644 --- a/src/renderer/extensions/layerEditor/components/LayerEditorContent.test.ts +++ b/src/renderer/extensions/layerEditor/components/LayerEditorContent.test.ts @@ -1,5 +1,6 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' -import { useToastStore } from '@/platform/updates/common/toastStore' + import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { fromPartial } from '@total-typescript/shoehorn' import userEvent from '@testing-library/user-event' @@ -26,7 +27,6 @@ const { autoSaveStop: vi.fn(), beforeChange: vi.fn(), loadCompositorSession: vi.fn().mockResolvedValue(0), - saveLayerState: vi.fn(() => true), savePreview: vi.fn().mockResolvedValue(undefined), session: { @@ -77,7 +77,6 @@ vi.mock( useCompositorAutoSave: vi.fn(() => ({ stop: autoSaveStop })) }) ) - vi.mock( import('@/renderer/extensions/compositor/composables/compositorSession'), () => ({ @@ -133,7 +132,7 @@ beforeEach(() => { useWorkflowStore().activeWorkflow = fromPartial({ changeTracker: { afterChange, beforeChange } }) - vi.mocked(useToastStore().add).mockImplementation(() => undefined) + vi.mocked(useNodeOutputStore().getNodeImageUrls).mockReturnValue([]) }) @@ -222,12 +221,13 @@ describe('LayerEditorContent', () => { renderEditor('compositor') await vi.waitFor(() => - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'warn', - detail: '2 layers failed to load' + description: '2 layers failed to load', + kind: 'warning', + title: 'Layer Editor' }) - ) + ]) ) expect(useCompositorAutoSave).not.toHaveBeenCalled() }) @@ -235,14 +235,18 @@ describe('LayerEditorContent', () => { it('warns on close when edits could not be auto-saved', async () => { loadCompositorSession.mockResolvedValueOnce(2) const { unmount } = renderEditor('compositor') - await vi.waitFor(() => expect(useToastStore().add).toHaveBeenCalled()) + await vi.waitFor(() => expect(useToast().toasts).toHaveLength(1)) session.editor.history.canUndo.mockReturnValue(true) unmount() expect(saveLayerState).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ detail: 'Failed to save composite' }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + description: 'Failed to save composite', + kind: 'error', + title: 'Error' + }) ) }) @@ -251,9 +255,13 @@ describe('LayerEditorContent', () => { renderEditor('compositor') await vi.waitFor(() => - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'Failed to load layers', + kind: 'error', + title: 'Error' + }) + ]) ) expect(useCompositorAutoSave).not.toHaveBeenCalled() }) diff --git a/src/renderer/extensions/layerEditor/components/LayerEditorContent.vue b/src/renderer/extensions/layerEditor/components/LayerEditorContent.vue index 6f4e047a4ec..0acc18bfa5c 100644 --- a/src/renderer/extensions/layerEditor/components/LayerEditorContent.vue +++ b/src/renderer/extensions/layerEditor/components/LayerEditorContent.vue @@ -44,7 +44,7 @@ import { useLayerEditorSession } from '@/renderer/extensions/layerEditor/composables/useLayerEditorSession' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' @@ -116,17 +116,13 @@ function finalizeCompositorSession(): void { void saveCompositorPreview(session, node) node.graph?.setDirtyCanvas(true) } else { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('compositor.saveFailed') + useToast().error(t('g.error'), { + description: t('compositor.saveFailed') }) } } else if (sessionHasEdits()) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('compositor.saveFailed') + useToast().error(t('g.error'), { + description: t('compositor.saveFailed') }) } } finally { @@ -141,10 +137,8 @@ onMounted(() => { .then((failed) => { if (closed) return if (failed > 0) { - useToastStore().add({ - severity: 'warn', - summary: t('layerEditor.title'), - detail: t('layerEditor.layersFailedToLoad', { count: failed }) + useToast().warning(t('layerEditor.title'), { + description: t('layerEditor.layersFailedToLoad', { count: failed }) }) return } @@ -153,10 +147,8 @@ onMounted(() => { .catch((err) => { console.error('[Compositor] Loading layers failed:', err) if (closed) return - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('layerEditor.loadFailed') + useToast().error(t('g.error'), { + description: t('layerEditor.loadFailed') }) }) return @@ -167,10 +159,8 @@ onMounted(() => { .loadImages(urls, names) .then((failed) => { if (closed || failed === 0) return - useToastStore().add({ - severity: 'warn', - summary: t('layerEditor.title'), - detail: t('layerEditor.layersFailedToLoad', { count: failed }) + useToast().warning(t('layerEditor.title'), { + description: t('layerEditor.layersFailedToLoad', { count: failed }) }) }) .catch((err) => console.error('[LayerEditor] Loading images failed:', err)) diff --git a/src/renderer/extensions/layerEditor/composables/useLayerEditor.test.ts b/src/renderer/extensions/layerEditor/composables/useLayerEditor.test.ts index 1b1dadb9fda..955a248ec30 100644 --- a/src/renderer/extensions/layerEditor/composables/useLayerEditor.test.ts +++ b/src/renderer/extensions/layerEditor/composables/useLayerEditor.test.ts @@ -1,5 +1,6 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' -import { useToastStore } from '@/platform/updates/common/toastStore' + import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -10,7 +11,6 @@ import { useLayerEditor } from './useLayerEditor' vi.mock(import('@/i18n')) beforeEach(() => { - vi.mocked(useToastStore().add).mockImplementation(() => undefined) vi.mocked(useNodeOutputStore().getNodeImageUrls).mockImplementation( () => undefined ) @@ -29,11 +29,9 @@ describe('useLayerEditor', () => { ]) useLayerEditor().openLayerEditor(node) expect(useDialogStore().showDialog).not.toHaveBeenCalled() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'info', - detail: 'layerEditor.needsTwoImages' - }) + expect(useToast().info).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ description: 'layerEditor.needsTwoImages' }) ) }) diff --git a/src/renderer/extensions/layerEditor/composables/useLayerEditor.ts b/src/renderer/extensions/layerEditor/composables/useLayerEditor.ts index 69616ae0704..2801b8497f1 100644 --- a/src/renderer/extensions/layerEditor/composables/useLayerEditor.ts +++ b/src/renderer/extensions/layerEditor/composables/useLayerEditor.ts @@ -6,7 +6,7 @@ import { } from '@/renderer/extensions/layerEditor/composables/layerEditorDialog' import { t } from '@/i18n' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' @@ -19,10 +19,8 @@ export function useLayerEditor() { const imageUrls = useNodeOutputStore().getNodeImageUrls(node) if (!imageUrls || imageUrls.length < 2) { - useToastStore().add({ - severity: 'info', - summary: t('layerEditor.title'), - detail: t('layerEditor.needsTwoImages') + useToast().info(t('layerEditor.title'), { + description: t('layerEditor.needsTwoImages') }) return } diff --git a/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.test.ts b/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.test.ts index dd773932854..c6b137e711f 100644 --- a/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.test.ts +++ b/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.test.ts @@ -1,4 +1,4 @@ -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { App } from 'vue' import { createApp, defineComponent, ref } from 'vue' @@ -25,7 +25,6 @@ const { writePsd, downloadBlob } = vi.hoisted(() => ({ vi.mock(import('ag-psd'), () => ({ writePsd })) vi.mock(import('@/base/common/downloadUtil'), () => ({ downloadBlob })) - const i18n = createI18n({ legacy: false, locale: 'en', @@ -171,10 +170,6 @@ function makeSession(nodes: RasterData[], glOk = true): LayerEditorSession { } as unknown as LayerEditorSession } -beforeEach(() => { - vi.mocked(useToastStore().add).mockImplementation(() => undefined) -}) - describe('useLayerEditorExport', () => { it('writes a psd matching the layer tree and triggers a download', async () => { const session = makeSession([ @@ -208,7 +203,7 @@ describe('useLayerEditorExport', () => { expect(blob).toBeInstanceOf(Blob) expect(exporting.value).toBe(false) expect(session.requestRender).toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) it('shows an error toast when writing fails', async () => { @@ -221,12 +216,12 @@ describe('useLayerEditorExport', () => { await exportPsd() expect(downloadBlob).not.toHaveBeenCalled() - expect(vi.mocked(useToastStore().add)).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'layerEditor.exportPsdFailed' + description: 'layerEditor.exportPsdFailed', + kind: 'error' }) - ) + ]) expect(exporting.value).toBe(false) expect(session.requestRender).toHaveBeenCalled() }) diff --git a/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.ts b/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.ts index eee573e6570..d1fac174d23 100644 --- a/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.ts +++ b/src/renderer/extensions/layerEditor/composables/useLayerEditorExport.ts @@ -4,7 +4,7 @@ import { useI18n } from 'vue-i18n' import { downloadBlob } from '@/base/common/downloadUtil' import type { LayerEditorSession } from '@/renderer/extensions/layerEditor/composables/useLayerEditorSession' import { buildPsdFromEditor } from '@/renderer/extensions/layerEditor/psdExport' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' const PSD_MIME = 'image/vnd.adobe.photoshop' @@ -56,7 +56,7 @@ export async function buildSessionPsdBlob( export function useLayerEditorExport(session: LayerEditorSession) { const { t } = useI18n() - const toastStore = useToastStore() + const toast = useToast() const exporting = ref(false) async function exportPsd(): Promise { @@ -67,10 +67,8 @@ export function useLayerEditorExport(session: LayerEditorSession) { downloadBlob(psdExportFilename(new Date()), blob) } catch (err) { console.warn('[LayerEditor] PSD export failed', err) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('layerEditor.exportPsdFailed') + toast.error(t('g.error'), { + description: t('layerEditor.exportPsdFailed') }) } finally { exporting.value = false diff --git a/src/renderer/extensions/linearMode/DropZone.test.ts b/src/renderer/extensions/linearMode/DropZone.test.ts index dd6df2e6aba..c24e6d4b3d3 100644 --- a/src/renderer/extensions/linearMode/DropZone.test.ts +++ b/src/renderer/extensions/linearMode/DropZone.test.ts @@ -7,13 +7,6 @@ import Button from '@/components/ui/button/Button.vue' import DropZone from './DropZone.vue' -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - () => ({ - useToast: () => ({ add: vi.fn() }) - }) -) - const i18n = createI18n({ legacy: false, locale: 'en', diff --git a/src/renderer/extensions/vueNodes/VideoPreview.vue b/src/renderer/extensions/vueNodes/VideoPreview.vue index 1ffad6fd359..d3e5083d287 100644 --- a/src/renderer/extensions/vueNodes/VideoPreview.vue +++ b/src/renderer/extensions/vueNodes/VideoPreview.vue @@ -125,7 +125,7 @@ diff --git a/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.test.ts b/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.test.ts index 21f854b8830..5b5a2c5e68a 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.test.ts @@ -3,18 +3,9 @@ import userEvent from '@testing-library/user-event' import { describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' import AudioPreviewPlayer from '@/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue' -const mockToastAdd = vi.fn() - -vi.mock( - import('primevue/usetoast'), // oxlint-disable-line comfy/no-primevue-imports - - () => ({ - useToast: () => ({ add: mockToastAdd }) - }) -) - vi.mock(import('@/base/common/downloadUtil'), () => ({ downloadFile: vi.fn() })) @@ -103,9 +94,9 @@ describe('AudioPreviewPlayer', () => { renderPlayer('http://example.com/audio.mp3') await user.click(screen.getByRole('button', { name: 'g.downloadAudio' })) - expect(mockToastAdd).toHaveBeenCalledWith( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'error' + kind: 'error' }) ) }) diff --git a/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue b/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue index feb08a83ae5..6b3e3f99ce3 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue +++ b/src/renderer/extensions/vueNodes/widgets/components/audio/AudioPreviewPlayer.vue @@ -132,7 +132,7 @@ import { computed, ref, useTemplateRef } from 'vue' import { useI18n } from 'vue-i18n' import { whenever } from '@vueuse/core' -import { useToast } from 'primevue/usetoast' +import { useToast } from '@/components/ui/toast/toastStore' import { downloadFile } from '@/base/common/downloadUtil' import Button from '@/components/ui/button/Button.vue' @@ -188,11 +188,7 @@ const handleDownload = () => { try { downloadFile(modelValue.value) } catch { - toast.add({ - severity: 'error', - summary: t('g.error'), - detail: t('g.failedToDownloadFile') - }) + toast.error(t('g.error'), { description: t('g.failedToDownloadFile') }) } } diff --git a/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.test.ts b/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.test.ts index a43ad5cc0fd..cc9390989bb 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.test.ts @@ -1,12 +1,12 @@ import { getActivePinia } from 'pinia' -import { useToastStore } from '@/platform/updates/common/toastStore' + import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import PrimeVue from 'primevue/config' import { reactive, ref } from 'vue' import { createI18n } from 'vue-i18n' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { useTransformState } from '@/renderer/core/layout/transform/useTransformState' @@ -130,10 +130,6 @@ async function openDropdown(user: ReturnType) { await screen.findByTestId('dropdown-menu') } -beforeEach(() => { - vi.mocked(useToastStore().addAlert).mockImplementation(() => undefined) -}) - describe('FormDropdown', () => { describe('filteredItems updates when items prop changes', () => { it('updates displayed items when items prop changes', async () => { diff --git a/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.vue b/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.vue index efffad7be7b..bd9e39c8cb8 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.vue +++ b/src/renderer/extensions/vueNodes/widgets/components/form/dropdown/FormDropdown.vue @@ -10,7 +10,7 @@ import type { ComponentPublicInstance } from 'vue' import { computed, ref, useTemplateRef } from 'vue' import { useI18n } from 'vue-i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDismissOnCanvasGesture } from '@/renderer/extensions/vueNodes/widgets/composables/useDismissOnCanvasGesture' import type { @@ -108,7 +108,7 @@ const baseModelSelected = defineModel>('baseModelSelected', { }) const isOpen = defineModel('isOpen', { default: false }) -const toastStore = useToastStore() +const toast = useToast() const popoverRef = ref>() const triggerAnchorRef = useTemplateRef('triggerAnchorRef') const menuRef = useTemplateRef('menuRef') @@ -267,7 +267,7 @@ function handleSelection(item: FormDropdownItem, index: number) { sel.clear() sel.add(item.id) } else { - toastStore.addAlert(t('widgets.uploadSelect.maxSelectionReached')) + toast.warning(t('widgets.uploadSelect.maxSelectionReached')) return } } diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.test.ts index b794df5c3b3..3b377a02584 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.test.ts @@ -7,7 +7,7 @@ import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/com import { LGraphNode } from '@/lib/litegraph/src/litegraph' import type { IComboWidget } from '@/lib/litegraph/src/types/widgets' import type { ResultItem } from '@/platform/remote/comfyui/execution/types' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { InputSpec } from '@/schemas/nodeDefSchema' import type { useNodeImageUpload } from '@/composables/node/useNodeImageUpload' @@ -164,18 +164,18 @@ describe('useImageUploadWidget', () => { ]) ).toBe(true) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'g.videoFilenameExtensionRequired' ) - vi.mocked(useToastStore().addAlert).mockClear() + vi.mocked(useToast().warning).mockClear() expect( mocks.capturedUploadOptions?.onReject?.([ new File([], 'image.png', { type: 'image/png' }) ]) ).toBe(false) - expect(useToastStore().addAlert).not.toHaveBeenCalled() + expect(useToast().warning).not.toHaveBeenCalled() }) it('previews the combo value once the initial frame runs', () => { diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts b/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts index a440fbdf5d8..89df25be530 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts @@ -7,7 +7,7 @@ import type { ResultItem } from '@/platform/remote/comfyui/execution/types' import type { ResultItemType } from '@/schemas/resultItemTypeSchema' import type { InputSpec } from '@/schemas/nodeDefSchema' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { ComfyWidgetConstructor } from '@/scripts/widgets' import { useNodeOutputStore } from '@/stores/nodeOutputStore' import { isImageUploadInput } from '@/types/nodeDefAugmentation' @@ -61,7 +61,7 @@ export const useImageUploadWidget = () => { const fileFilter = isVideo ? isUploadableVideo : isImageFile function alertExtensionlessVideo(files: File[]) { if (!files.some(isExtensionlessVideo)) return false - useToastStore().addAlert(t('g.videoFilenameExtensionRequired')) + useToast().warning(t('g.videoFilenameExtensionRequired')) return true } const fileComboWidget = findFileComboWidget(node, imageInputName) diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.test.ts index db4a65f80e8..a42573b2ea1 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.test.ts @@ -6,7 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { FormDropdownItem } from '@/renderer/extensions/vueNodes/widgets/components/form/dropdown/types' import { useWidgetSelectActions } from '@/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions' import { api } from '@/scripts/api' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { SimplifiedWidget } from '@/types/simplifiedWidget' import enMessages from '@/locales/en/main.json' @@ -98,7 +98,7 @@ describe('useWidgetSelectActions', () => { expect(api.fetchApi).not.toHaveBeenCalled() expect(modelValue.value).toBe('existing.mp4') - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( enMessages.g.videoFilenameExtensionRequired ) }) @@ -221,8 +221,7 @@ describe('useWidgetSelectActions', () => { expect(modelValue.value).toBe('original.png') - const toastStore = useToastStore() - expect(toastStore.addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'Upload failed: Internal Server Error' ) }) @@ -250,9 +249,7 @@ describe('useWidgetSelectActions', () => { await handleFilesUpdate([new File(['test'], 'fail.png')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'Upload failed: HTTP 502' - ) + expect(useToast().warning).toHaveBeenCalledWith('Upload failed: HTTP 502') }) it('shows a file-too-large toast on a 413 with no known upload limit', async () => { @@ -279,7 +276,7 @@ describe('useWidgetSelectActions', () => { await handleFilesUpdate([new File(['test'], 'huge.png')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'File is too large to upload.' ) }) @@ -308,7 +305,7 @@ describe('useWidgetSelectActions', () => { await handleFilesUpdate([new File(['test'], 'huge.png')]) - expect(useToastStore().addAlert).toHaveBeenCalledWith( + expect(useToast().warning).toHaveBeenCalledWith( 'File is too large to upload (limit: 100 MB).' ) }) diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.ts b/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.ts index e3b3459be86..bff188bb164 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useWidgetSelectActions.ts @@ -2,9 +2,9 @@ import { toValue } from 'vue' import type { ComputedRef, MaybeRefOrGetter, Ref } from 'vue' import { useErrorHandling } from '@/composables/useErrorHandling' +import { useToast } from '@/components/ui/toast/toastStore' import { t } from '@/i18n' import { ServerFeatureFlag } from '@/platform/remoteConfig/serverFeatureFlag' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { FormDropdownItem } from '@/renderer/extensions/vueNodes/widgets/components/form/dropdown/types' import type { ResultItemType } from '@/schemas/resultItemTypeSchema' @@ -42,7 +42,7 @@ interface UseWidgetSelectActionsOptions { export function useWidgetSelectActions(options: UseWidgetSelectActionsOptions) { const { modelValue, dropdownItems } = options - const toastStore = useToastStore() + const toast = useToast() const { wrapWithErrorHandlingAsync } = useErrorHandling() function updateSelectedItems(selectedItems: Set) { @@ -77,7 +77,7 @@ export function useWidgetSelectActions(options: UseWidgetSelectActionsOptions) { }) if (resp.status !== 200) { - toastStore.addAlert(buildUploadErrorMessage(resp)) + toast.warning(buildUploadErrorMessage(resp)) return null } @@ -103,14 +103,14 @@ export function useWidgetSelectActions(options: UseWidgetSelectActionsOptions) { async (files: File[]) => { if (files.length === 0) return if (files.some(isExtensionlessVideo)) { - toastStore.addAlert(t('g.videoFilenameExtensionRequired')) + toast.warning(t('g.videoFilenameExtensionRequired')) return } const uploadedPaths = await uploadFiles(files) if (uploadedPaths.length === 0) { - toastStore.addAlert('File upload failed') + toast.warning(t('toastMessages.fileUploadFailed')) return } diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 9946c51b24d..43a438ead68 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -33,10 +33,11 @@ import type { ModelFile, ModelFolderInfo } from '@/platform/assets/schemas/assetSchema' +import { useToast } from '@/components/ui/toast/toastStore' +import { t } from '@/i18n' import { isCloud } from '@/platform/distribution/types' import { addBreadcrumb } from '@sentry/vue' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { components as ManagerComponents } from '@/workbench/extensions/manager/types/generatedManagerTypes' import type { AssetDownloadWsMessage, @@ -1871,6 +1872,7 @@ export class ComfyApi extends EventTarget { * @param {boolean} options.freeExecutionCache - If true, also frees execution cache */ async freeMemory(options: { freeExecutionCache: boolean }) { + const toast = useToast() try { let mode = '' if (options.freeExecutionCache) { @@ -1886,31 +1888,19 @@ export class ComfyApi extends EventTarget { }) if (res.status === 200) { - if (options.freeExecutionCache) { - useToastStore().add({ - severity: 'success', - summary: 'Models and Execution Cache have been cleared.', - life: 3000 - }) - } else { - useToastStore().add({ - severity: 'success', - summary: 'Models have been unloaded.', - life: 3000 - }) - } + toast.success( + t( + options.freeExecutionCache + ? 'toastMessages.modelsAndCacheCleared' + : 'toastMessages.modelsUnloaded' + ), + { duration: 3000 } + ) } else { - useToastStore().add({ - severity: 'error', - summary: - 'Unloading of models failed. Installed ComfyUI may be an outdated version.' - }) + toast.error(t('toastMessages.unloadModelsFailed')) } } catch { - useToastStore().add({ - severity: 'error', - summary: 'An error occurred while trying to unload models.' - }) + toast.error(t('toastMessages.unloadModelsError')) } } diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index 3f82f7588b2..62e9c269822 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -1,9 +1,10 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn' import { ComfyApp, app as singletonApp } from './app' +import { useToast } from '@/components/ui/toast/toastStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useSubgraphNavigationStore } from '@/stores/subgraphNavigationStore' import { useNodeOutputStore } from '@/stores/nodeOutputStore' -import { useToastStore } from '@/platform/updates/common/toastStore' + import { useSettingStore } from '@/platform/settings/settingStore' import { useAuthStore } from '@/stores/authStore' import { @@ -447,11 +448,9 @@ describe('ComfyApp', () => { await app.loadGraphData(createWorkflowGraphData(), false, true, null) await vi.waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'warn', - summary: t('toastMessages.missingMediaVerificationFailed') - }) + expect(useToast().warning).toHaveBeenCalledWith( + t('toastMessages.missingMediaVerificationFailed'), + { duration: 5000 } ) }) expect(store.lastNodeErrors).toEqual({ @@ -460,6 +459,45 @@ describe('ComfyApp', () => { }) }) + it('offers to migrate legacy reroutes and dismisses the offer once migrated', async () => { + app.canvasElRef.value = document.createElement('canvas') + Reflect.set(app, 'rootGraphInternal', new LGraph()) + const legacyReroute = { + ...createWorkflowGraphData(), + nodes: [ + { + id: 1, + type: 'Reroute', + pos: [0, 0], + size: [75, 26], + flags: {}, + order: 0, + mode: 0, + properties: {} + } + ] + } satisfies ComfyWorkflowJSON + + await app.loadGraphData(legacyReroute, false, true, null, { + checkForRerouteMigration: true + }) + const [offer] = useToast().toasts + expect(offer).toEqual( + expect.objectContaining({ + action: expect.objectContaining({ label: t('g.migrate') }), + kind: 'warning', + title: t('toastMessages.migrateToLitegraphReroute') + }) + ) + const reload = vi.spyOn(app, 'loadGraphData').mockResolvedValue(true) + + await offer.action?.onClick() + + const [migrated] = reload.mock.calls[0] + expect(migrated?.nodes.map((node) => node.type)).not.toContain('Reroute') + expect(useToast().toasts).toEqual([]) + }) + it('forwards clean and navigation intent to workflow navigation', async () => { app.canvasElRef.value = document.createElement('canvas') Reflect.set(app, 'rootGraphInternal', new LGraph()) @@ -3164,15 +3202,12 @@ describe('ComfyApp', () => { await app.refreshComboInNodes() - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'info' }) - ) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'success' }) - ) - expect(useToastStore().remove).toHaveBeenCalledWith( - vi.mocked(useToastStore().add).mock.calls[0][0] - ) + expect(useToast().info).toHaveBeenCalledWith(t('g.update'), { + description: t('toastMessages.updateRequested') + }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'success' }) + ]) }) it('shows failure toast, removes the pending toast, and rethrows reload failures', async () => { @@ -3182,12 +3217,9 @@ describe('ComfyApp', () => { await expect(app.refreshComboInNodes()).rejects.toThrow(error) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error' }) - ) - expect(useToastStore().remove).toHaveBeenCalledWith( - vi.mocked(useToastStore().add).mock.calls[0][0] - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'error' }) + ]) }) }) @@ -3583,7 +3615,7 @@ describe('ComfyApp', () => { await expect(app.handleFile(imageFile)).resolves.toBeUndefined() expect(loadApiJson).toHaveBeenCalled() - expect(useToastStore().addAlert).toHaveBeenCalledTimes(1) + expect(useToast().warning).toHaveBeenCalledTimes(1) expect(mockImportA1111).not.toHaveBeenCalled() expect(createNode).not.toHaveBeenCalled() }) @@ -3692,36 +3724,35 @@ describe('ComfyApp', () => { await app.handleFile(createTestFile('broken.json', 'application/json')) - expect(useToastStore().addAlert).toHaveBeenCalledTimes(1) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'Unable to find workflow in broken.json' - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Unable to find workflow in broken.json' + }) + ]) }) it.for([ { - outcome: 'core-nodes-unavailable' as const, + description: undefined, fileName: 'a1111.png', - toastMethod: 'addAlert' as const, - expectedToast: t('toastMessages.a1111CoreNodesUnavailable') + loadsGraph: false, + outcome: 'core-nodes-unavailable' as const, + title: t('toastMessages.a1111CoreNodesUnavailable') }, { - outcome: 'not-a1111' as const, + description: undefined, fileName: 'parameters.png', - toastMethod: 'addAlert' as const, - expectedToast: t('toastMessages.fileLoadError', { - fileName: 'parameters.png' - }) + loadsGraph: false, + outcome: 'not-a1111' as const, + title: t('toastMessages.fileLoadError', { fileName: 'parameters.png' }) }, { - outcome: 'imported-without-embeddings' as const, + description: t('toastMessages.a1111EmbeddingsUnavailable'), fileName: 'a1111.png', - toastMethod: 'add' as const, - expectedToast: { - severity: 'warn', - summary: t('g.warning'), - detail: t('toastMessages.a1111EmbeddingsUnavailable') - } + loadsGraph: true, + outcome: 'imported-without-embeddings' as const, + title: t('g.warning') } ])('maps $outcome to its message', async (testCase) => { const graph = new LGraph() @@ -3737,15 +3768,16 @@ describe('ComfyApp', () => { parameters, expect.any(Function) ) - expect(useToastStore()[testCase.toastMethod]).toHaveBeenCalledOnce() - expect(useToastStore()[testCase.toastMethod]).toHaveBeenCalledWith( - testCase.expectedToast + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: testCase.description, + kind: 'warning', + title: testCase.title + }) + ]) + expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledTimes( + testCase.loadsGraph ? 1 : 0 ) - if (testCase.outcome === 'imported-without-embeddings') { - expect(mockWorkflowService.afterLoadNewGraph).toHaveBeenCalledOnce() - } else { - expect(mockWorkflowService.afterLoadNewGraph).not.toHaveBeenCalled() - } }) it('awaits persistence and orders its clear callback before setGraph', async () => { @@ -3941,7 +3973,7 @@ describe('ComfyApp', () => { await noFiles expect( - vi.mocked(useToastStore().addAlert).mock.calls.map(([msg]) => msg) + vi.mocked(useToast().warning).mock.calls.map(([title]) => title) ).toEqual(alerts) expect( vi.mocked(reportError).mock.calls.map(([, opts]) => opts.errorType) diff --git a/src/scripts/app.ts b/src/scripts/app.ts index 7b7d220dbcc..f0c38daa54d 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -2,6 +2,7 @@ import { useEventListener, useResizeObserver } from '@vueuse/core' import _ from 'es-toolkit/compat' import { reactive, unref, shallowRef } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { partnerRunGateBlocksAutoQueue } from '@/composables/billing/usePartnerNodesRunGate' import { useCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion' import { normalizeCameraState } from '@/renderer/core/canvas/cameraState' @@ -53,7 +54,6 @@ import type { WorkflowOpenSource, WorkflowQueueIntent } from '@/platform/telemetry/types' -import { useToastStore } from '@/platform/updates/common/toastStore' import { MIME_ASSET_INFO } from '@/platform/assets/schemas/mediaAssetSchema' import { restoreDynamicGroupInputs } from '@/platform/workflow/core/utils/restoreDynamicGroupInputs' import { updatePendingWarnings } from '@/platform/workflow/core/utils/pendingWarnings' @@ -66,7 +66,8 @@ import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/ import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation' import type { ComfyApiWorkflow, - ComfyWorkflowJSON + ComfyWorkflowJSON, + WorkflowJSON04 } from '@/platform/workflow/validation/schemas/workflowSchema' import { toNodeId } from '@/types/nodeId' import { zNodePackMetadata } from '@/platform/workflow/validation/schemas/workflowSchema' @@ -119,11 +120,9 @@ import { useWidgetStore } from '@/stores/widgetStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { useWorkspaceStore } from '@/stores/workspaceStore' import type { ComfyExtension } from '@/types/comfy' -import type { - ExtensionManager, - ToastMessageOptions -} from '@/types/extensionTypes' +import type { ExtensionManager } from '@/types/extensionTypes' import type { NodeExecutionId } from '@/types/nodeIdentification' +import { getErrorMessage } from '@/utils/errorUtil' import { normalizePromptError } from '@/utils/executionErrorUtil' import { graphToPrompt, unwrapExportedWidgetValue } from '@/utils/executionUtil' import { parseJsonWithNonFinite } from '@/utils/jsonUtil' @@ -164,6 +163,7 @@ import { } from '@/utils/objectUrlUtil' import { findLegacyRerouteNodes, + migrateLegacyRerouteNodes, noNativeReroutes } from '@/utils/migration/migrateReroute' import { deserialiseAndCreate } from '@/utils/vintageClipboard' @@ -777,7 +777,7 @@ export class ComfyApp { surface: 'graph', errorType: 'asset_drop_load_failure' }) - useToastStore().addAlert(t('toastMessages.assetDropFailed')) + useToast().warning(t('toastMessages.assetDropFailed')) } return } @@ -823,7 +823,11 @@ export class ComfyApp { } useWorkflowService().showPendingWarnings() } catch (error: unknown) { - useToastStore().addAlert(t('toastMessages.dropFileError', { error })) + useToast().warning( + t('toastMessages.dropFileError', { + error: getErrorMessage(error) ?? t('g.unknownError') + }) + ) } }) @@ -1018,10 +1022,8 @@ export class ComfyApp { useSubgraphService().registerNewSubgraph(subgraph, data) } catch (err) { console.error('Failed to register subgraph', err) - useToastStore().add({ - severity: 'error', - summary: 'Failed to register subgraph', - detail: err instanceof Error ? err.message : String(err) + useToast().error(t('toastMessages.failedToRegisterSubgraph'), { + description: getErrorMessage(err) ?? t('g.unknownError') }) } }) @@ -1392,10 +1394,26 @@ export class ComfyApp { findLegacyRerouteNodes(graphData).length && noNativeReroutes(graphData) ) { - useToastStore().add({ - group: 'reroute-migration', - severity: 'warn' - }) + const toast = useToast() + const migrationToastId = toast.warning( + t('toastMessages.migrateToLitegraphReroute'), + { + action: { + label: t('g.migrate'), + onClick: async () => { + await this.loadGraphData( + migrateLegacyRerouteNodes( + this.rootGraph.serialize() as unknown as WorkflowJSON04 + ), + false, + false, + useWorkflowStore().activeWorkflow + ) + toast.dismiss(migrationToastId) + } + } + } + ) } useSubgraphService().loadSubgraphs(graphData) @@ -2161,7 +2179,7 @@ export class ComfyApp { } showErrorOnFileLoad(file: File) { - useToastStore().addAlert( + useToast().warning( t('toastMessages.fileLoadError', { fileName: file.name }) ) } @@ -2299,16 +2317,14 @@ export class ComfyApp { ) switch (outcome) { case 'core-nodes-unavailable': - useToastStore().addAlert(t('toastMessages.a1111CoreNodesUnavailable')) + useToast().warning(t('toastMessages.a1111CoreNodesUnavailable')) return case 'not-a1111': this.showErrorOnFileLoad(file) return case 'imported-without-embeddings': - useToastStore().add({ - severity: 'warn', - summary: t('g.warning'), - detail: t('toastMessages.a1111EmbeddingsUnavailable') + useToast().warning(t('g.warning'), { + description: t('toastMessages.a1111EmbeddingsUnavailable') }) break case 'imported': @@ -2770,38 +2786,31 @@ export class ComfyApp { * Refresh combo list on whole nodes */ async refreshComboInNodes() { - const requestToastMessage: ToastMessageOptions = { - severity: 'info', - summary: t('g.update'), - detail: t('toastMessages.updateRequested') - } - if (this.vueAppReady) { - useToastStore().add(requestToastMessage) - } + const requestToastId = this.vueAppReady + ? useToast().info(t('g.update'), { + description: t('toastMessages.updateRequested') + }) + : undefined try { await this.reloadNodeDefs() if (this.vueAppReady) { - useToastStore().add({ - severity: 'success', - summary: t('g.updated'), - detail: t('toastMessages.nodeDefinitionsUpdated'), - life: 1000 + useToast().success(t('g.updated'), { + description: t('toastMessages.nodeDefinitionsUpdated'), + duration: 1000 }) } } catch (error) { if (this.vueAppReady) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('toastMessages.nodeDefinitionsUpdateFailed') + useToast().error(t('g.error'), { + description: t('toastMessages.nodeDefinitionsUpdateFailed') }) } throw error } finally { - if (this.vueAppReady) { - useToastStore().remove(requestToastMessage) + if (requestToastId !== undefined) { + useToast().dismiss(requestToastId) } } } diff --git a/src/scripts/ui/settings.test.ts b/src/scripts/ui/settings.test.ts index 93f7abfa3b3..3af7315e05a 100644 --- a/src/scripts/ui/settings.test.ts +++ b/src/scripts/ui/settings.test.ts @@ -1,8 +1,8 @@ import { fromPartial } from '@total-typescript/shoehorn' import { describe, expect, expectTypeOf, it, vi } from 'vitest' +import { useToast } from '@/components/ui/toast/toastStore' import { useSettingStore } from '@/platform/settings/settingStore' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { ComfyApp } from '@/scripts/app' import { ComfySettingsDialog } from './settings' @@ -51,12 +51,10 @@ describe('saving a setting that fails to persist', () => { save(dialog, accessor) await vi.waitFor(() => { - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: expect.stringContaining( - 'Error saving setting Comfy.EditAttention.Delta' - ) + kind: 'warning', + title: 'Error saving setting Comfy.EditAttention.Delta: offline' }) ) }) diff --git a/src/scripts/ui/settings.ts b/src/scripts/ui/settings.ts index 25488261fcc..a4d06fa8beb 100644 --- a/src/scripts/ui/settings.ts +++ b/src/scripts/ui/settings.ts @@ -1,8 +1,9 @@ import { t } from '@/i18n' import { useSettingStore } from '@/platform/settings/settingStore' import type { SettingParams, Settings } from '@/platform/settings/types' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { ComfyApp } from '@/scripts/app' +import { getErrorMessage } from '@/utils/errorUtil' import { ComfyDialog } from './dialog' @@ -10,7 +11,12 @@ function saveSetting(id: K, value: Settings[K]) { useSettingStore() .set(id, value) .catch((err) => { - useToastStore().addAlert(t('toastMessages.errorSaveSetting', { id, err })) + useToast().warning( + t('toastMessages.errorSaveSetting', { + err: getErrorMessage(err) ?? t('g.unknownError'), + id + }) + ) }) } diff --git a/src/services/README.md b/src/services/README.md index 6ff783cb102..ce88187a9be 100644 --- a/src/services/README.md +++ b/src/services/README.md @@ -406,12 +406,6 @@ describe('useWorkflowService', () => { set: vi.fn() }) })) - - vi.mock('@/platform/updates/common/toastStore', () => ({ - useToastStore: () => ({ - add: vi.fn() - }) - })) }) test('should save workflow with prompt', async () => { diff --git a/src/services/audioService.test.ts b/src/services/audioService.test.ts index 3141d273c85..96d4ac867f8 100644 --- a/src/services/audioService.test.ts +++ b/src/services/audioService.test.ts @@ -1,4 +1,4 @@ -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { api } from '@/scripts/api' @@ -193,9 +193,12 @@ describe('useAudioService', () => { 'Error uploading temp file: 500 - Internal Server Error' ) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - 'Error uploading temp file: 500 - Internal Server Error' - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'warning', + title: 'Upload failed: 500 - Internal Server Error' + }) + ]) }) it('should handle network errors', async () => { @@ -226,11 +229,12 @@ describe('useAudioService', () => { `Error uploading temp file: ${testCase.status} - ${testCase.statusText}` ) - expect(useToastStore().addAlert).toHaveBeenCalledWith( - `Error uploading temp file: ${testCase.status} - ${testCase.statusText}` + expect(useToast().toasts.at(-1)).toEqual( + expect.objectContaining({ + kind: 'warning', + title: `Upload failed: ${testCase.status} - ${testCase.statusText}` + }) ) - - vi.mocked(useToastStore().addAlert).mockClear() } }) diff --git a/src/services/audioService.ts b/src/services/audioService.ts index 9fc67616aea..3f2c298bdbf 100644 --- a/src/services/audioService.ts +++ b/src/services/audioService.ts @@ -1,8 +1,7 @@ import { register } from 'extendable-media-recorder' import { connect } from 'extendable-media-recorder-wav-encoder' -import { useToastStore } from '@/platform/updates/common/toastStore' -import { api } from '@/scripts/api' +import { uploadTempFile } from '@/services/uploadTempFile' export interface AudioRecordingError { type: 'permission' | 'not_supported' | 'encoder' | 'recording' | 'unknown' @@ -53,23 +52,10 @@ export const useAudioService = () => { const name = `recording-${Date.now()}.wav` const file = new File([blob], name, { type: blob.type || 'audio/wav' }) - const body = new FormData() - body.append('image', file) - body.append('subfolder', 'audio') - body.append('type', 'temp') - - const resp = await api.fetchApi('/upload/image', { - method: 'POST', - body - }) - - if (resp.status !== 200) { - const err = `Error uploading temp file: ${resp.status} - ${resp.statusText}` - useToastStore().addAlert(err) - throw new Error(err) - } - - const tempAudio = await resp.json() + const upload = await uploadTempFile(file, 'audio') + if (!upload.ok) + throw new Error(`Error uploading temp file: ${upload.reason}`) + const tempAudio = upload.file return `audio/${tempAudio.name} [temp]` } diff --git a/src/services/dialogService.downgrade.test.ts b/src/services/dialogService.downgrade.test.ts index 0fdc092c660..b5494209f20 100644 --- a/src/services/dialogService.downgrade.test.ts +++ b/src/services/dialogService.downgrade.test.ts @@ -1,9 +1,10 @@ import { computed } from 'vue' import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useToast } from '@/components/ui/toast/toastStore' import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import type { Component } from 'vue' import type DowngradeContent from '@/platform/workspace/components/dialogs/DowngradeRemoveMembersDialogContent.vue' -import { useToastStore } from '@/platform/updates/common/toastStore' + import { useDialogStore } from '@/stores/dialogStore' /** * showDowngradeToPersonalDialog must refresh members before the no-members @@ -393,12 +394,13 @@ describe('showDowngradeToPersonalDialog', () => { await useDialogService().showDowngradeToPersonalDialog(options) - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'Outstanding balance' + description: 'Outstanding balance', + kind: 'error', + title: 'subscription.downgrade.failed' }) - ) + ]) expect(useDialogStore().showDialog).not.toHaveBeenCalled() }) @@ -408,9 +410,13 @@ describe('showDowngradeToPersonalDialog', () => { await useDialogService().showDowngradeToPersonalDialog(options) - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'error', detail: 'network' }) - ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'network', + kind: 'error', + title: 'subscription.downgrade.failed' + }) + ]) expect(useDialogStore().showDialog).not.toHaveBeenCalled() expect(downgradeToPersonal).not.toHaveBeenCalled() }) @@ -420,12 +426,13 @@ describe('showDowngradeToPersonalDialog', () => { await useDialogService().showDowngradeToPersonalDialog(options) - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'Outstanding balance' + description: 'Outstanding balance', + kind: 'error', + title: 'subscription.downgrade.failed' }) - ) + ]) expect(useDialogStore().showDialog).not.toHaveBeenCalled() expect(downgradeToPersonal).not.toHaveBeenCalled() }) diff --git a/src/services/dialogService.errorCatalog.test.ts b/src/services/dialogService.errorCatalog.test.ts index 43f8bc3ec64..79b5d306d0f 100644 --- a/src/services/dialogService.errorCatalog.test.ts +++ b/src/services/dialogService.errorCatalog.test.ts @@ -22,15 +22,6 @@ import { nodeError, validationError } from '@/utils/__tests__/nodeErrorHelpers' import { useDialogService } from './dialogService' vi.mock(import('@/platform/telemetry')) -// oxlint-disable-next-line comfy/no-primevue-imports -vi.mock(import('primevue/usetoast'), () => ({ - useToast: () => ({ - add: vi.fn(), - remove: vi.fn(), - removeGroup: vi.fn(), - removeAllGroups: vi.fn() - }) -})) vi.mock(import('@/composables/useCopyToClipboard'), () => ({ useCopyToClipboard: () => ({ copyToClipboard: vi.fn(async () => true) }) })) diff --git a/src/services/dialogService.ts b/src/services/dialogService.ts index 83a693989c2..d1a63608eed 100644 --- a/src/services/dialogService.ts +++ b/src/services/dialogService.ts @@ -20,12 +20,13 @@ import { t } from '@/i18n' import { useTelemetry } from '@/platform/telemetry' import { isCloud } from '@/platform/distribution/types' import { useBillingContext } from '@/composables/billing/useBillingContext' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogStore } from '@/stores/dialogStore' import type { RunErrorMessageSource } from '@/platform/errorCatalog/types' import type { PromptError } from '@/platform/remote/comfyui/types' import { PromptExecutionError } from '@/scripts/api' import { tryExtractValidationError } from '@/utils/executionErrorUtil' +import { getErrorMessage } from '@/utils/errorUtil' import type { DialogComponentProps, ShowDialogOptions @@ -955,10 +956,8 @@ export const useDialogService = () => { return await downgradeToPersonal(options.planSlug) } } catch (error) { - useToastStore().add({ - severity: 'error', - summary: t('subscription.downgrade.failed'), - detail: error instanceof Error ? error.message : t('g.unknownError') + useToast().error(t('subscription.downgrade.failed'), { + description: getErrorMessage(error) ?? t('g.unknownError') }) return null } diff --git a/src/services/litegraphService.ts b/src/services/litegraphService.ts index 36110c80f59..2b45243d548 100644 --- a/src/services/litegraphService.ts +++ b/src/services/litegraphService.ts @@ -40,7 +40,7 @@ import type { import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { toConcreteWidget } from '@/lib/litegraph/src/widgets/widgetMap' import { useSettingStore } from '@/platform/settings/settingStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { createPromotedMultilineWidget } from '@/renderer/extensions/vueNodes/widgets/utils/multilineTextarea' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' @@ -78,6 +78,7 @@ import { parseNodeId } from '@/types/nodeId' import type { SerializedNodeId } from '@/types/nodeId' import { isBlueprintType } from '@/utils/blueprintUtils' import { markCoreMediaMenuCallback } from '@/utils/coreMediaMenuActionUtils' +import { getErrorMessage } from '@/utils/errorUtil' import type { WidgetId } from '@/types/widgetId' import { normalizeI18nKey } from '@/utils/formatUtil' import { @@ -189,7 +190,7 @@ function getMinSize(node: LGraphNode) { */ export const useLitegraphService = () => { const extensionService = useExtensionService() - const toastStore = useToastStore() + const toast = useToast() const widgetStore = useWidgetStore() const canvasStore = useCanvasStore() const { toggleSelectedNodesMode } = useSelectedLiteGraphItems() @@ -697,9 +698,9 @@ export const useLitegraphService = () => { throw error } } catch (error) { - toastStore.addAlert( + toast.warning( t('toastMessages.errorCopyImage', { - error: error instanceof Error ? error.message : error + error: getErrorMessage(error) ?? t('g.unknownError') }) ) } diff --git a/src/services/uploadTempFile.ts b/src/services/uploadTempFile.ts new file mode 100644 index 00000000000..446abdeedb3 --- /dev/null +++ b/src/services/uploadTempFile.ts @@ -0,0 +1,27 @@ +import type { UploadImageResponse } from '@comfyorg/ingest-types' + +import { useToast } from '@/components/ui/toast/toastStore' +import { t } from '@/i18n' +import { api } from '@/scripts/api' + +type TempFileUpload = + | { ok: true; file: UploadImageResponse } + | { ok: false; reason: string } + +export async function uploadTempFile( + file: File, + subfolder: string +): Promise { + const body = new FormData() + body.append('image', file) + body.append('subfolder', subfolder) + body.append('type', 'temp') + + const resp = await api.fetchApi('/upload/image', { method: 'POST', body }) + if (resp.status !== 200) { + const reason = `${resp.status} - ${resp.statusText}` + useToast().warning(t('g.uploadFailed', { reason })) + return { ok: false, reason } + } + return { file: await resp.json(), ok: true } +} diff --git a/src/stores/README.md b/src/stores/README.md index 1fd3dc9045f..123023027b7 100644 --- a/src/stores/README.md +++ b/src/stores/README.md @@ -138,7 +138,7 @@ The following table lists ALL 46 store instances in the system as of 2026-01-29: | settingStore.ts | useSettingStore | Manages application settings | Config | | subgraphNavigationStore.ts | useSubgraphNavigationStore | Handles subgraph navigation state | Navigation | | systemStatsStore.ts | useSystemStatsStore | Tracks system performance statistics | System | -| toastStore.ts | useToastStore | Manages toast notifications | UI | +| toastStore.ts | useToast | Manages toast notifications | UI | | userFileStore.ts | useUserFileStore | Manages user file operations | Files | | userStore.ts | useUserStore | Manages user data and preferences | User | | versionCompatibilityStore.ts | useVersionCompatibilityStore | Manages frontend/backend version compatibility warnings | Core | diff --git a/src/stores/apiKeyAuthStore.ts b/src/stores/apiKeyAuthStore.ts index 4f6989460a7..e8e600a648b 100644 --- a/src/stores/apiKeyAuthStore.ts +++ b/src/stores/apiKeyAuthStore.ts @@ -4,7 +4,7 @@ import { computed, nextTick, ref, watch } from 'vue' import { useErrorHandling } from '@/composables/useErrorHandling' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useAuthStore } from '@/stores/authStore' import type { ApiKeyAuthHeader } from '@/types/authTypes' import type { operations } from '@/types/comfyRegistryTypes' @@ -17,7 +17,7 @@ const STORAGE_KEY = 'comfy_api_key' export const useApiKeyAuthStore = defineStore('apiKeyAuth', () => { const authStore = useAuthStore() const apiKey = useLocalStorage(STORAGE_KEY, null) - const toastStore = useToastStore() + const toast = useToast() const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling() const currentUser = ref(null) @@ -56,10 +56,8 @@ export const useApiKeyAuthStore = defineStore('apiKeyAuth', () => { const reportError = (error: unknown) => { if (error instanceof Error && error.message === 'STORAGE_FAILED') { - toastStore.add({ - severity: 'error', - summary: t('auth.apiKey.storageFailed'), - detail: t('auth.apiKey.storageFailedDetail') + toast.error(t('auth.apiKey.storageFailed'), { + description: t('auth.apiKey.storageFailedDetail') }) } else { toastErrorHandler(error) @@ -68,22 +66,18 @@ export const useApiKeyAuthStore = defineStore('apiKeyAuth', () => { const storeApiKey = wrapWithErrorHandlingAsync(async (newApiKey: string) => { apiKey.value = newApiKey - toastStore.add({ - severity: 'success', - summary: t('auth.apiKey.stored'), - detail: t('auth.apiKey.storedDetail'), - life: 5000 + toast.success(t('auth.apiKey.stored'), { + description: t('auth.apiKey.storedDetail'), + duration: 5000 }) return true }, reportError) const clearStoredApiKey = wrapWithErrorHandlingAsync(async () => { apiKey.value = null - toastStore.add({ - severity: 'success', - summary: t('auth.apiKey.cleared'), - detail: t('auth.apiKey.clearedDetail'), - life: 5000 + toast.success(t('auth.apiKey.cleared'), { + description: t('auth.apiKey.clearedDetail'), + duration: 5000 }) return true }, reportError) diff --git a/src/stores/assetExportStore.ts b/src/stores/assetExportStore.ts index 48f05e4cab5..0da8f906893 100644 --- a/src/stores/assetExportStore.ts +++ b/src/stores/assetExportStore.ts @@ -3,7 +3,7 @@ import { defineStore } from 'pinia' import { computed, ref, watch } from 'vue' import { assetService } from '@/platform/assets/services/assetService' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import type { TaskId, TaskResponse, @@ -167,11 +167,10 @@ export const useAssetExportStore = defineStore('assetExport', () => { if (!resolvedUrl.ok) { exp.downloadError = resolvedUrl.error exp.downloadTriggered = false - useToastStore().add({ - severity: 'error', - summary: t('exportToast.downloadFailed', { name: exp.exportName }), - detail: resolvedUrl.error - }) + useToast().error( + t('exportToast.downloadFailed', { name: exp.exportName }), + { description: resolvedUrl.error } + ) return } const link = document.createElement('a') @@ -188,13 +187,12 @@ export const useAssetExportStore = defineStore('assetExport', () => { exp.downloadError = message exp.downloadTriggered = false - useToastStore().add({ - severity: 'error', - summary: t('exportToast.downloadFailed', { + useToast().error( + t('exportToast.downloadFailed', { name: exp.exportName }), - detail: message - }) + { description: message } + ) } } diff --git a/src/stores/subgraphStore.test.ts b/src/stores/subgraphStore.test.ts index f9bc41e13c1..1e5ae137372 100644 --- a/src/stores/subgraphStore.test.ts +++ b/src/stores/subgraphStore.test.ts @@ -8,6 +8,7 @@ import { createTestSubgraph, createTestSubgraphNode } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' +import { useToast } from '@/components/ui/toast/toastStore' import type { ExportedSubgraph } from '@/lib/litegraph/src/types/serialisation' import { TemplateIncludeOnDistributionEnum } from '@/platform/workflow/templates/types/template' import type { ComfyNodeDef as ComfyNodeDefV1 } from '@/schemas/nodeDefSchema' @@ -318,6 +319,9 @@ describe('useSubgraphStore', () => { 'Failed to load subgraph blueprint', expect.any(Error) ) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ description: 'Network error', kind: 'error' }) + ]) expect(useNodeDefStore().blueprintNodeDefsByName.size).toBe(0) }) diff --git a/src/stores/subgraphStore.ts b/src/stores/subgraphStore.ts index 2f7ff3f5d0b..837c693389f 100644 --- a/src/stores/subgraphStore.ts +++ b/src/stores/subgraphStore.ts @@ -3,7 +3,7 @@ import { defineStore } from 'pinia' import { t } from '@/i18n' import { SubgraphNode } from '@/lib/litegraph/src/litegraph' import { useSettingStore } from '@/platform/settings/settingStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' @@ -28,6 +28,7 @@ import { useExecutionErrorStore } from '@/stores/executionErrorStore' import { ComfyNodeDefImpl, useNodeDefStore } from '@/stores/nodeDefStore' import type { UserFile } from '@/stores/userFileStore' import { BLUEPRINT_TYPE_PREFIX } from '@/utils/blueprintUtils' +import { getErrorMessage } from '@/utils/errorUtil' async function confirmOverwrite(name: string): Promise { return await useDialogService().confirm({ @@ -260,10 +261,13 @@ export const useSubgraphStore = defineStore('subgraph', () => { const errors = settled.filter((i) => 'reason' in i).map((i) => i.reason) errors.forEach((e) => console.error('Failed to load subgraph blueprint', e)) if (errors.length > 0) { - useToastStore().add({ - severity: 'error', - summary: t('subgraphStore.loadFailure'), - detail: errors.length > 3 ? `x${errors.length}` : `${errors}` + useToast().error(t('subgraphStore.loadFailure'), { + description: + errors.length > 3 + ? `x${errors.length}` + : errors + .map((e) => getErrorMessage(e) ?? t('g.unknownError')) + .join(', ') }) } } @@ -368,11 +372,9 @@ export const useSubgraphStore = defineStore('subgraph', () => { await workflow.save() //add to files list? useWorkflowStore().attachWorkflow(loadedWorkflow) - useToastStore().add({ - severity: 'success', - summary: t('subgraphStore.publishSuccess'), - detail: t('subgraphStore.publishSuccessMessage'), - life: 4000 + useToast().success(t('subgraphStore.publishSuccess'), { + description: t('subgraphStore.publishSuccessMessage'), + duration: 4000 }) } async function editBlueprint(nodeType: string) { @@ -398,10 +400,8 @@ export const useSubgraphStore = defineStore('subgraph', () => { if (!(name in subgraphCache)) throw new Error('not yet loaded') if (isGlobalBlueprint(name)) { - useToastStore().add({ - severity: 'warn', - summary: t('subgraphStore.cannotDeleteGlobal'), - life: 4000 + useToast().warning(t('subgraphStore.cannotDeleteGlobal'), { + duration: 4000 }) return } diff --git a/src/stores/workspaceStore.test.ts b/src/stores/workspaceStore.test.ts new file mode 100644 index 00000000000..07bef79c9d8 --- /dev/null +++ b/src/stores/workspaceStore.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, it, vi } from 'vitest' +import { fromAny } from '@total-typescript/shoehorn' + +import { useToast } from '@/components/ui/toast/toastStore' +import type { Toast } from '@/components/ui/toast/toastStore' +import { reportError } from '@/platform/telemetry/reportError' +import type { ToastMessageOptions } from '@/types/extensionTypes' + +import { useWorkspaceStore } from './workspaceStore' + +vi.mock(import('firebase/auth')) +vi.mock(import('@/platform/telemetry/reportError')) + +interface LegacyToastCase { + expected: Partial + message: ToastMessageOptions + name: string +} + +describe('extension toast API', () => { + it.for([ + { + name: 'maps warn severity, summary, detail and life', + message: { + detail: 'Restart to apply', + life: 3000, + severity: 'warn', + summary: 'Update available' + }, + expected: { + closable: true, + description: 'Restart to apply', + duration: 3000, + kind: 'warning', + title: 'Update available' + } + }, + { + name: 'uses detail as the title when summary is missing', + message: { closable: false, detail: 'Copy failed', severity: 'error' }, + expected: { + closable: false, + description: undefined, + duration: Number.POSITIVE_INFINITY, + kind: 'error', + title: 'Copy failed' + } + }, + { + name: 'keeps a zero life on screen until dismissed', + message: { life: 0, severity: 'error', summary: 'Sync failed' }, + expected: { duration: Number.POSITIVE_INFINITY, kind: 'error' } + }, + { + name: 'defaults a missing severity to info', + message: { summary: 'Queued' }, + expected: { kind: 'info', title: 'Queued' } + }, + { + name: 'renders secondary severity as info', + message: { severity: 'secondary', summary: 'Note' }, + expected: { kind: 'info', title: 'Note' } + }, + { + name: 'renders success severity as success', + message: { severity: 'success', summary: 'Installed' }, + expected: { kind: 'success', title: 'Installed' } + } + ])('legacy add $name', ({ expected, message }) => { + useWorkspaceStore().toast.add(message) + + expect(useToast().toasts).toEqual([expect.objectContaining(expected)]) + }) + + it('legacy add shows a warning severity as a warning and reports it once', () => { + const { toast } = useWorkspaceStore() + const message = fromAny({ + severity: 'warning', + summary: 'Low disk space' + }) + + toast.add(message) + toast.add(message) + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'warning', title: 'Low disk space' }), + expect.objectContaining({ kind: 'warning', title: 'Low disk space' }) + ]) + expect(reportError).toHaveBeenCalledExactlyOnceWith(expect.any(Error), { + surface: 'platform', + errorType: 'deprecated_toast_warning_severity', + level: 'warning' + }) + }) + + it('legacy add logs an unsupported severity instead of throwing', () => { + useWorkspaceStore().toast.add( + fromAny({ + severity: 'danger', + summary: 'Low disk space' + }) + ) + + expect(useToast().toasts).toEqual([]) + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining('"danger"') + ) + }) + + it('legacy addAlert shows the message as a warning title', () => { + useWorkspaceStore().toast.addAlert('Missing model') + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: undefined, + kind: 'warning', + title: 'Missing model' + }) + ]) + }) + + it.for(['error', 'info', 'loading', 'success', 'warning'] as const)( + 'creates and dismisses a %s toast through the id-based API', + (kind) => { + const { toast } = useWorkspaceStore() + const id = toast[kind]('Uploading', { description: 'model.safetensors' }) + + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'model.safetensors', + id, + kind, + title: 'Uploading' + }) + ]) + + toast.dismiss(id) + expect(useToast().toasts).toEqual([]) + } + ) +}) diff --git a/src/stores/workspaceStore.ts b/src/stores/workspaceStore.ts index b452d93daae..a4c0a48c58f 100644 --- a/src/stores/workspaceStore.ts +++ b/src/stores/workspaceStore.ts @@ -2,13 +2,18 @@ import { useMagicKeys } from '@vueuse/core' import { defineStore } from 'pinia' import { computed, ref } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { useSettingStore } from '@/platform/settings/settingStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { reportError } from '@/platform/telemetry/reportError' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { Settings } from '@/platform/settings/types' import { useColorPaletteService } from '@/services/colorPaletteService' import { useDialogService } from '@/services/dialogService' -import type { SidebarTabExtension, ToastManager } from '@/types/extensionTypes' +import type { + SidebarTabExtension, + ToastManager, + ToastMessageOptions +} from '@/types/extensionTypes' import { renderMarkdownToHtml } from '@/utils/markdownRendererUtil' import { useApiKeyAuthStore } from './apiKeyAuthStore' @@ -19,6 +24,19 @@ import { useQueueSettingsStore } from './queueSettingsStore' import { useBottomPanelStore } from './workspace/bottomPanelStore' import { useSidebarTabStore } from './workspace/sidebarTabStore' +const legacySeverityKinds = new Map< + string, + 'error' | 'info' | 'success' | 'warning' +>([ + ['contrast', 'info'], + ['error', 'error'], + ['info', 'info'], + ['secondary', 'info'], + ['success', 'success'], + ['warn', 'warning'], + ['warning', 'warning'] +]) + function workspaceStoreSetup() { const spinner = ref(false) const { shift: shiftDown } = useMagicKeys() @@ -28,7 +46,41 @@ function workspaceStoreSetup() { */ const focusMode = ref(false) - const toast = computed(() => useToastStore()) + const toastStore = useToast() + let reportedWarningSeverity = false + function reportWarningSeverity() { + if (reportedWarningSeverity) return + reportedWarningSeverity = true + reportError(new Error('toast.add received severity "warning"'), { + surface: 'platform', + errorType: 'deprecated_toast_warning_severity', + level: 'warning' + }) + } + const toast: ToastManager = { + add: (message: ToastMessageOptions) => { + const severity: string = message.severity ?? 'info' + if (severity === 'warning') reportWarningSeverity() + const kind = legacySeverityKinds.get(severity) + if (!kind) { + console.error(`toast.add: unsupported severity "${severity}"`) + return + } + toastStore[kind](message.summary ?? message.detail ?? '', { + closable: message.closable, + description: message.summary === undefined ? undefined : message.detail, + duration: message.life || undefined + }) + }, + addAlert: (message) => toastStore.warning(message), + dismiss: toastStore.dismiss, + dismissAll: toastStore.dismissAll, + error: toastStore.error, + info: toastStore.info, + loading: toastStore.loading, + success: toastStore.success, + warning: toastStore.warning + } const queueSettings = computed(() => useQueueSettingsStore()) const command = computed(() => ({ commands: useCommandStore().commands, diff --git a/src/types/extensionTypes.ts b/src/types/extensionTypes.ts index bcf9fd0e1d9..19631db9f85 100644 --- a/src/types/extensionTypes.ts +++ b/src/types/extensionTypes.ts @@ -1,5 +1,7 @@ import type { Component } from 'vue' +import type { ToastId } from '@/types/toastId' + import type { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { ExecutionErrorWsMessage } from '@/platform/remote/comfyui/execution/types' import type { NodeError } from '@/platform/remote/comfyui/types' @@ -48,58 +50,42 @@ export type BottomPanelExtension = | VueBottomPanelExtension | CustomBottomPanelExtension +export interface ToastAction { + label: string + onClick: () => unknown +} + +export interface ToastOptions { + action?: ToastAction + closable?: boolean + description?: string + duration?: number + id?: ToastId +} + /** - * Defines message options in Toast component. + * @deprecated Use `toast.success/error/info/warning/loading(title, options)`. */ export interface ToastMessageOptions { - /** - * Severity level of the message. - * @defaultValue info - */ - severity?: - | 'success' - | 'info' - | 'warn' - | 'error' - | 'secondary' - | 'contrast' - | undefined - /** - * Summary content of the message. - */ - summary?: string | undefined - /** - * Detail content of the message. - */ + closable?: boolean detail?: string - /** - * Whether the message can be closed manually using the close icon. - * @defaultValue true - */ - closable?: boolean | undefined - /** - * Delay in milliseconds to close the message automatically. - */ - life?: number | undefined - /** - * Key of the Toast to display the message. - */ - group?: string | undefined - /** - * Style class of the message. - */ - styleClass?: string | string[] | Record - /** - * Style class of the content. - * Matches PrimeVue Toast API which accepts Vue class bindings. - */ - contentStyleClass?: string | string[] | Record + life?: number + severity?: 'success' | 'info' | 'warn' | 'error' | 'secondary' | 'contrast' + summary?: string } export type ToastManager = { + /** @deprecated Use `success/error/info/warning/loading`. */ add(message: ToastMessageOptions): void - remove(message: ToastMessageOptions): void - removeAll(): void + /** @deprecated Use `warning(message)`. */ + addAlert(message: string): void + dismiss(id: ToastId): boolean + dismissAll(): void + error(title: string, options?: ToastOptions): ToastId + info(title: string, options?: ToastOptions): ToastId + loading(title: string, options?: ToastOptions): ToastId + success(title: string, options?: ToastOptions): ToastId + warning(title: string, options?: ToastOptions): ToastId } export interface ExtensionManager { diff --git a/src/types/index.ts b/src/types/index.ts index 1c4a08fd12e..d3e3e470338 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -39,9 +39,12 @@ import type { CommandManager, ExtensionManager, SidebarTabExtension, + ToastAction, ToastManager, - ToastMessageOptions + ToastMessageOptions, + ToastOptions } from './extensionTypes' +import type { ToastId } from './toastId' export type { NodeId, SerializedNodeId } from './nodeId' export { toNodeId, parseNodeId } from './nodeId' @@ -90,7 +93,10 @@ export type { ToastManager, ExtensionManager, CommandManager, - ToastMessageOptions + ToastAction, + ToastId, + ToastMessageOptions, + ToastOptions } interface CapturedMessages { diff --git a/src/types/toastId.ts b/src/types/toastId.ts new file mode 100644 index 00000000000..75457a55a12 --- /dev/null +++ b/src/types/toastId.ts @@ -0,0 +1,8 @@ +export type ToastId = number & { readonly __brand: 'ToastId' } + +let lastToastId = 0 + +export function createToastId(): ToastId { + lastToastId += 1 + return lastToastId as ToastId +} diff --git a/src/utils/litegraphUtil.ts b/src/utils/litegraphUtil.ts index 85a82441b69..60c6efc7d3c 100644 --- a/src/utils/litegraphUtil.ts +++ b/src/utils/litegraphUtil.ts @@ -21,7 +21,7 @@ import type { } from '@/lib/litegraph/src/types/widgets' import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2' import { inputSpecTree } from '@/schemas/nodeDef/inputSpecTree' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useNodeZIndex } from '@/renderer/extensions/vueNodes/composables/useNodeZIndex' import { app } from '@/scripts/app' import { t } from '@/i18n' @@ -70,7 +70,7 @@ export async function createNode( } return addedNode } else { - useToastStore().addAlert(t('assetBrowser.failedToCreateNode')) + useToast().warning(t('assetBrowser.failedToCreateNode')) return null } } diff --git a/src/views/GraphView.test.ts b/src/views/GraphView.test.ts index 59c7f598011..ff3a2276667 100644 --- a/src/views/GraphView.test.ts +++ b/src/views/GraphView.test.ts @@ -204,15 +204,6 @@ vi.mock( import('@/platform/assets/components/AssetExportProgressDialog.vue'), () => stubModule ) -vi.mock( - import('@/platform/workspace/components/toasts/InviteAcceptedToast.vue'), - () => stubModule -) -vi.mock(import('@/components/toast/GlobalToast.vue'), () => stubModule) -vi.mock( - import('@/components/toast/RerouteMigrationToast.vue'), - () => stubModule -) vi.mock(import('@/components/MenuHamburger.vue'), () => stubModule) vi.mock( import('@/components/dialog/UnloadWindowConfirmDialog.vue'), diff --git a/src/views/GraphView.vue b/src/views/GraphView.vue index 84bb6f49119..744f18acb40 100644 --- a/src/views/GraphView.vue +++ b/src/views/GraphView.vue @@ -20,13 +20,13 @@
- - - - - + + + + + + - @@ -53,11 +53,10 @@ import MenuHamburger from '@/components/MenuHamburger.vue' import UnloadWindowConfirmDialog from '@/components/dialog/UnloadWindowConfirmDialog.vue' import GraphCanvas from '@/components/graph/GraphCanvas.vue' import PartnerNodesEducationCard from '@/components/actionbar/PartnerNodesEducationCard.vue' +import ToastDock from '@/components/ui/toast/ToastDock.vue' +import Toaster from '@/components/ui/toast/Toaster.vue' import TourOverlay from '@/platform/onboarding/TourOverlay.vue' import FirstRunTour from '@/renderer/extensions/firstRunTour/FirstRunTour.vue' -import GlobalToast from '@/components/toast/GlobalToast.vue' -import InviteAcceptedToast from '@/platform/workspace/components/toasts/InviteAcceptedToast.vue' -import RerouteMigrationToast from '@/components/toast/RerouteMigrationToast.vue' import { registerCoreBottomPanelTabs } from '@/composables/bottomPanelTabs/registerCoreBottomPanelTabs' import { registerCoreSidebarTabs } from '@/composables/sidebarTabs/registerCoreSidebarTabs' import { useBrowserTabTitle } from '@/composables/useBrowserTabTitle' diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index e7dcc4a9f84..caa0c97f12e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -53,7 +53,7 @@ import { app } from '@/scripts/app' import NodeSelectionModeBanner from '@/components/graph/NodeSelectionModeBanner.vue' import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore' import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useAssetsStore } from '@/stores/assetsStore' import type { AssetItem } from '@/platform/assets/schemas/assetSchema' import { startAssetDrag } from '@/platform/assets/utils/assetDragUtil' @@ -2070,12 +2070,12 @@ describe('AgentPanelRoot session notices', () => { }) ) renderWithSelectedTarget() - const toast = useToastStore() + const toast = useToast() ws.emit('agent_message_done', {}) await nextTick() - expect(toast.messagesToAdd).toHaveLength(0) + expect(toast.toasts).toHaveLength(0) expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) expect(executionErrors.lastPromptError).toMatchObject({ type: 'agent_api_failed', @@ -2522,10 +2522,10 @@ describe('AgentPanelRoot attach flow', () => { await nextTick() expect(store.attachments).toHaveLength(1) expect(fetchRequests(source)).toHaveLength(1) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'info', - detail: 'Recording.mp3 is already in the asset tray' + kind: 'info', + title: 'Recording.mp3 is already in the asset tray' }) ]) }) @@ -2561,13 +2561,13 @@ describe('AgentPanelRoot attach flow', () => { expect(store.attachments).toEqual([newAttachment]) expect(newAttachment.ref).toBe('stored-library.png') expect(store.prompt.references).toEqual([]) - expect(useToastStore().messagesToAdd).toEqual([]) + expect(useToast().toasts).toEqual([]) expect(dispatchDrag(target, 'drop', data)).toBe(true) expect(store.attachments).toHaveLength(1) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'info', - detail: 'library.png is already in the asset tray' + kind: 'info', + title: 'library.png is already in the asset tray' }) ]) }) @@ -2835,10 +2835,10 @@ describe('AgentPanelRoot attach flow', () => { await nextTick() expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: 'movie.mp4 is larger than 24 MB' + kind: 'warning', + title: 'movie.mp4 is larger than 24 MB' }) ) expect( @@ -3012,10 +3012,10 @@ describe('AgentPanelRoot attach flow', () => { await renderAndPasteScreenshot() await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: 'image.png could not be uploaded' + kind: 'warning', + title: 'image.png could not be uploaded' }) ) ) @@ -3263,10 +3263,10 @@ describe('AgentPanelRoot attach flow', () => { await nextTick() expect(uploaded).toEqual([]) - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: 'big.mp3 is larger than 24 MB' + kind: 'warning', + title: 'big.mp3 is larger than 24 MB' }) ) }) @@ -3573,7 +3573,7 @@ describe('AgentPanelRoot attach flow', () => { }) const { unmount } = renderWithSelectedTarget() await nextTick() - const toast = useToastStore() + const toast = useToast() vi.useFakeTimers() try { dispatchDrag(screen.getByRole('textbox'), 'drop', { @@ -3591,7 +3591,7 @@ describe('AgentPanelRoot attach flow', () => { unmount() await vi.advanceTimersByTimeAsync(60_000) - expect(toast.messagesToAdd).toEqual([]) + expect(toast.toasts).toEqual([]) } finally { vi.useRealTimers() } @@ -3642,7 +3642,7 @@ describe('AgentPanelRoot attach flow', () => { ] }) await vi.waitFor(() => expect(store.attachments[0]?.uploading).toBe(false)) - expect(useToastStore().messagesToAdd).toEqual([]) + expect(useToast().toasts).toEqual([]) dispatchDrag(target, 'drop', { files: [ ...Array.from( @@ -3666,8 +3666,8 @@ describe('AgentPanelRoot attach flow', () => { ) ).toHaveLength(1) await vi.waitFor(() => expect(uploaded).toEqual(['cat.png', 'dog.png'])) - expect(useToastStore().messagesToAdd).toEqual([ - expect.objectContaining({ severity: 'info', detail: notice }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ kind: 'info', title: notice }) ]) expect(screen.getByRole('group', { name: 'dog.png' })).toBeInTheDocument() expect(target).toHaveFocus() @@ -4000,10 +4000,10 @@ describe('AgentPanelRoot attach flow', () => { // A rejected file is the user's to fix; raising the server-error overlay // told them the agent had broken instead. expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: 'cat.png could not be uploaded' + kind: 'warning', + title: 'cat.png could not be uploaded' }) ) expect(reportError).toHaveBeenCalledWith(expect.any(Error), { @@ -4656,9 +4656,9 @@ describe('AgentPanelRoot transcript copy', () => { ) } else { expect(clipboard.copy).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - summary: i18n.global.t('agent.copyUnavailable') + title: i18n.global.t('agent.copyUnavailable') }) ) } @@ -5893,7 +5893,7 @@ describe('AgentPanelRoot workflow binding', () => { name: outcome === 'failed open' ? 'other' : 'scratch' }) ) - await waitFor(() => expect(useToastStore().messagesToAdd).toHaveLength(1)) + await waitFor(() => expect(useToast().toasts).toHaveLength(1)) expect(useAgentPanelStore().selectedWorkflow?.path).toBe(target.path) workflowStore.activeWorkflow = other await nextTick() @@ -5929,9 +5929,7 @@ describe('AgentPanelRoot workflow binding', () => { await userEvent.click( await screen.findByRole('menuitemradio', { name: 'scratch' }) ) - await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toHaveLength(1) - ) + await vi.waitFor(() => expect(useToast().toasts).toHaveLength(1)) expect( screen.getByRole('menuitemradio', { name: 'scratch' }) ).not.toHaveAttribute('aria-disabled', 'true') @@ -5958,9 +5956,7 @@ describe('AgentPanelRoot workflow binding', () => { await userEvent.click( await screen.findByRole('menuitemradio', { name: 'scratch' }) ) - await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toHaveLength(1) - ) + await vi.waitFor(() => expect(useToast().toasts).toHaveLength(1)) expect(scratch.isTemporary).toBe(false) expect(workflowStore.activeWorkflow?.path).toBe(current.path) expect(screen.getByRole('menuitemradio', { name: 'current' })).toBeChecked() @@ -6145,7 +6141,7 @@ describe('AgentPanelRoot workflow binding', () => { expect(workflowStore.activeWorkflow?.path).toBe(target.path) expect(useAgentPanelStore().selectedWorkflow?.path).toBe(target.path) expect(useAgentChatHistoryStore().activeId).toBe('th-1') - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) expect(fetchRequests(blockedRoute)).toHaveLength(requestsBeforeSwitch) } ) @@ -6212,15 +6208,15 @@ describe('AgentPanelRoot workflow binding', () => { expect( screen.queryByText(i18n.global.t('agent.historyOpenFailed')) ).toBeNull() - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) expect(useAgentChatHistoryStore().activeId).toBeNull() expect(workflowStore.activeWorkflow.path).toBe(other.path) } else { expect(await screen.findByRole('alert')).toHaveTextContent( i18n.global.t('agent.historyOpenFailed') ) - expect(useToastStore().messagesToAdd).not.toContainEqual( - expect.objectContaining({ severity: 'warn' }) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ kind: 'warning' }) ) expect(useAgentChatHistoryStore().activeId).toBe('th-1') expect(useAgentPanelStore().selectedWorkflow?.path).toBe(target.path) @@ -6403,7 +6399,7 @@ describe('AgentPanelRoot workflow binding', () => { expect(workflowStore.activeWorkflow?.path).toBe(other.path) expect(useAgentPanelStore().selectedWorkflow?.path).toBe(other.path) expect(fetchRequests(/\/workflows/).length).toBeLessThanOrEqual(1) - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) }) it.for([null, 'th-current'])( @@ -6524,7 +6520,7 @@ describe('AgentPanelRoot workflow binding', () => { 'workflows/current.json', 'workflows/portrait.json' ]) - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) await sendFromComposer('Continue the portrait') expect(bodies[0]).toMatchObject({ workflow_id: 'wf-portrait' }) expect(useWorkflowService().saveWorkflowAs).not.toHaveBeenCalled() @@ -6796,7 +6792,7 @@ describe('AgentPanelRoot workflow binding', () => { await vi.waitFor(() => expect(useAgentPanelStore().selectedWorkflow).toEqual(restored) ) - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) await sendFromComposer('continue editing') expect(bodies[0]).toMatchObject({ @@ -6842,7 +6838,7 @@ describe('AgentPanelRoot workflow binding', () => { expect(useAgentPanelStore().selectedWorkflow).toEqual(current) expect(workflowStore.activeWorkflow).toEqual(current) expect(useWorkflowService().openWorkflow).not.toHaveBeenCalled() - expect(useToastStore().messagesToAdd).toHaveLength(0) + expect(useToast().toasts).toHaveLength(0) } ) @@ -6958,8 +6954,8 @@ describe('AgentPanelRoot workflow binding', () => { expect(localStorage.getItem(StorageKeys.agentThread('personal'))).toBe( 'th-history' ) - expect(useToastStore().messagesToAdd).not.toContainEqual( - expect.objectContaining({ severity: 'warn' }) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ kind: 'warning' }) ) await userEvent.click(screen.getByRole('button', { name: 'New chat' })) @@ -7014,9 +7010,9 @@ describe('AgentPanelRoot workflow binding', () => { await screen.findAllByText('Historical prompt') await vi.waitFor(() => { expect( - useToastStore() - .messagesToAdd.filter(({ severity }) => severity === 'warn') - .map(({ detail }) => detail) + useToast().toasts.flatMap((toast) => + toast.kind === 'warning' ? [toast.title] : [] + ) ).toEqual(toasts) expect( screen @@ -7081,10 +7077,10 @@ describe('AgentPanelRoot workflow binding', () => { failListing() await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: i18n.global.t('agent.targetWorkflowOpenFailed') + kind: 'warning', + title: i18n.global.t('agent.targetWorkflowOpenFailed') }) ) ) @@ -7156,8 +7152,8 @@ describe('AgentPanelRoot workflow binding', () => { screen.getByRole('heading', { name: 'Chat history' }) ).toBeVisible() expect(screen.queryByText('Historical prompt')).not.toBeInTheDocument() - expect(useToastStore().messagesToAdd).not.toContainEqual( - expect.objectContaining({ severity: 'warn' }) + expect(useToast().toasts).not.toContainEqual( + expect.objectContaining({ kind: 'warning' }) ) expect(useAgentPanelStore().selectedWorkflow).toBeNull() expect(useAgentChatHistoryStore().activeId).toBeNull() @@ -7293,9 +7289,7 @@ describe('AgentPanelRoot workflow binding', () => { await userEvent.click( await screen.findByRole('menuitemradio', { name: 'other' }) ) - await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toHaveLength(1) - ) + await vi.waitFor(() => expect(useToast().toasts).toHaveLength(1)) expect(screen.getByRole('menuitemradio', { name: 'current' })).toBeChecked() }) @@ -7874,12 +7868,12 @@ describe('AgentPanelRoot workflow binding', () => { message: 'Expected schema 2, found 1' }) - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'error', - summary: i18n.global.t('agent.workflowSyncFailedTitle'), - detail: `${i18n.global.t('agent.workflowSyncFailedDetail')} (Expected schema 2, found 1)`, - life: 0 + kind: 'error', + title: i18n.global.t('agent.workflowSyncFailedTitle'), + description: `${i18n.global.t('agent.workflowSyncFailedDetail')} (Expected schema 2, found 1)`, + duration: Number.POSITIVE_INFINITY }) ) }) @@ -8413,10 +8407,10 @@ describe('AgentPanelRoot workflow binding', () => { await vi.advanceTimersByTimeAsync(500) await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toContainEqual( + expect(useToast().toasts).toContainEqual( expect.objectContaining({ - severity: 'warn', - detail: i18n.global.t('agent.targetNavigationUnavailable') + kind: 'warning', + title: i18n.global.t('agent.targetNavigationUnavailable') }) ) ) @@ -9401,9 +9395,9 @@ describe('AgentPanelRoot workflow binding', () => { await screen.findByRole('menuitem', { name: /scratch\s*Unsaved/ }) ) await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toEqual( + expect(useToast().toasts).toEqual( expect.arrayContaining([ - expect.objectContaining({ detail: 'Save unavailable' }) + expect.objectContaining({ description: 'Save unavailable' }) ]) ) ) @@ -9702,10 +9696,10 @@ describe('AgentPanelRoot workflow binding', () => { screen.getByRole('button', { name: 'Open reference' }) ) await vi.waitFor(() => - expect(useToastStore().messagesToAdd).toEqual( + expect(useToast().toasts).toEqual( expect.arrayContaining([ expect.objectContaining({ - detail: i18n.global.t('agent.targetNavigationUnavailable') + title: i18n.global.t('agent.targetNavigationUnavailable') }) ]) ) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 620adfeb0e0..d4c5fbc9583 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -56,7 +56,7 @@ import { useExecutionErrorStore } from '@/stores/executionErrorStore' import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore' import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore' import { isLGraphNode } from '@/utils/litegraphUtil' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' import type { RootGraphId } from '@/types/graphScopeId' import { isCloud } from '@/platform/distribution/types' @@ -147,7 +147,7 @@ const CrdtDevPanel = defineAsyncComponent( ) const { t } = useI18n() -const toast = useToastStore() +const toast = useToast() const { open: openAccountPrecondition } = useAccountPreconditionDialog() const { workspaceRole } = useWorkspaceUI() const { @@ -719,22 +719,14 @@ function onWorkflowAdopted( } function warnWorkflowUnavailable(): void { - toast.add({ - severity: 'warn', - detail: t('agent.targetNavigationUnavailable'), - life: 5000 - }) + toast.warning(t('agent.targetNavigationUnavailable'), { duration: 5000 }) } function warnRestoreFailed(): void { const { view } = agentPanelStore // A loading history row reports its own failure. if (view.screen === 'history' && view.selection.status === 'loading') return - toast.add({ - severity: 'warn', - detail: t('agent.targetWorkflowOpenFailed'), - life: 5000 - }) + toast.warning(t('agent.targetWorkflowOpenFailed'), { duration: 5000 }) } function trackWorkflowOpenFailure( @@ -875,12 +867,8 @@ const { }, onReset: graphActivity.resetWorkflow, onSyncError: (message, code) => - toast.add({ - severity: 'error', - summary: t('agent.workflowSyncFailedTitle'), - detail: formatWorkflowSyncErrorDetail(t, message, code), - // A permanent desync remains visible until the person dismisses it. - life: 0 + toast.error(t('agent.workflowSyncFailedTitle'), { + description: formatWorkflowSyncErrorDetail(t, message, code) }) }, { @@ -1432,7 +1420,7 @@ function buildTranscriptMarkdown(entries: ConversationEntry[]): string { function onCopyMarkdown(id: string): void { if (id === history.activeId && id === threadId.value) void copy(buildTranscriptMarkdown(entries.value)) - else toast.add({ severity: 'info', summary: t('agent.copyUnavailable') }) + else toast.info(t('agent.copyUnavailable')) } const coachSteps = computed(() => [ @@ -1667,8 +1655,7 @@ const attachment = useAttachment({ ) ?? MAX_ATTACHMENT_BYTES, // A rejected file is the user's problem to fix, not an agent failure, so it // must not raise the server-error overlay. - onError: (message) => - toast.add({ severity: 'warn', detail: message, life: 5000 }), + onError: (message) => toast.warning(message, { duration: 5000 }), onDuplicate: notifyDuplicateAttachments, stage: composerStore.addAttachment, update: composerStore.updateAttachment, @@ -1685,15 +1672,14 @@ watch( ) function notifyDuplicateAttachments(names: string[]): void { - toast.add({ - severity: 'info', - detail: t( + toast.info( + t( 'agent.attachmentsAlreadyAdded', { name: names[0], count: names.length }, names.length ), - life: 3500 - }) + { duration: 3500 } + ) } onBeforeUnmount(() => @@ -1784,11 +1770,7 @@ function onPanelDragLeave(): void { async function attachDroppedAsset(event: DragEvent): Promise { const asset = event.dataTransfer && getDroppedAsset(event.dataTransfer) if (!asset) { - toast.add({ - severity: 'warn', - detail: t('agent.assetNotAttachable'), - life: 5000 - }) + toast.warning(t('agent.assetNotAttachable'), { duration: 5000 }) return false } @@ -1820,11 +1802,7 @@ async function attachDroppedAsset(event: DragEvent): Promise { sourceKey ) if (result === 'unsupported') - toast.add({ - severity: 'warn', - detail: t('agent.assetNotAttachable'), - life: 5000 - }) + toast.warning(t('agent.assetNotAttachable'), { duration: 5000 }) return result === 'uploaded' } diff --git a/src/workbench/extensions/agent/components/agent/Composer.test.ts b/src/workbench/extensions/agent/components/agent/Composer.test.ts index 598da055861..c8d31a0e265 100644 --- a/src/workbench/extensions/agent/components/agent/Composer.test.ts +++ b/src/workbench/extensions/agent/components/agent/Composer.test.ts @@ -14,8 +14,8 @@ import type { ComponentProps } from 'vue-component-type-helpers' import { i18n } from '@/i18n' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import { consultEscapeOverride } from '@/platform/keybindings/escapeOverride' +import { useToast } from '@/components/ui/toast/toastStore' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import { api } from '@/scripts/api' import { useAgentRunModeStore } from '../../stores/agent/agentRunModeStore' import type { AgentStarterPromptAttribution } from '../../utils/starterPrompts' @@ -659,10 +659,12 @@ describe('Composer', () => { ).toBeChecked() ) expect(screen.getByRole('status')).toBeEmptyDOMElement() - expect(useToastStore().messagesToAdd).toContainEqual({ - severity: 'error', - detail: i18n.global.t('agent.runModeSaveFailed') - }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'error', + title: i18n.global.t('agent.runModeSaveFailed') + }) + ) expect(telemetry.trackAgentRunModeChanged).not.toHaveBeenCalled() }) diff --git a/src/workbench/extensions/agent/components/agent/Composer.workflowClipboard.test.ts b/src/workbench/extensions/agent/components/agent/Composer.workflowClipboard.test.ts index e20db95d211..27a4ddf96b4 100644 --- a/src/workbench/extensions/agent/components/agent/Composer.workflowClipboard.test.ts +++ b/src/workbench/extensions/agent/components/agent/Composer.workflowClipboard.test.ts @@ -54,6 +54,7 @@ describe('workflow reference clipboard', () => { `${before}@[Workflow: Reference B]${after}` ) if (operation === 'copy') await user.keyboard('{Backspace}') + await waitFor(() => expect(store.draft).toBe('')) await user.paste(clipboard) expect(store.draft).toBe(before + after) expect(store.workflowReferences).toEqual([reference]) diff --git a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts index a1a36f4672a..7c0b607262f 100644 --- a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts +++ b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts @@ -6,8 +6,8 @@ import { computed, defineComponent, nextTick, ref } from 'vue' import type { SubscriptionInfo } from '@/composables/billing/types' import { i18n } from '@/i18n' -import { api } from '@/scripts/api' import { WORKSPACE_INSET_RIGHT } from '@/composables/useWorkspaceInset' +import { api } from '@/scripts/api' import { reportError } from '@/platform/telemetry/reportError' import type { TurnId } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { useAgentConversationStore } from '@/workbench/extensions/agent/stores/agent/agentConversationStore' @@ -152,6 +152,22 @@ describe('DockedAgentPanel', () => { ) }) + it('publishes its width for portaled overlays only while docked', async () => { + const store = openPanel() + renderPanel() + + expect( + document.documentElement.style.getPropertyValue(WORKSPACE_INSET_RIGHT) + ).toBe(`${store.width}px`) + + store.isOpen = false + await nextTick() + + expect( + document.documentElement.style.getPropertyValue(WORKSPACE_INSET_RIGHT) + ).toBe('0px') + }) + it('does not mount the Agent root until the panel opens', async () => { const store = openPanel() store.isOpen = false diff --git a/src/workbench/extensions/agent/components/agent/composer/RunModePopover.vue b/src/workbench/extensions/agent/components/agent/composer/RunModePopover.vue index 5fc528255f9..62d96fc036f 100644 --- a/src/workbench/extensions/agent/components/agent/composer/RunModePopover.vue +++ b/src/workbench/extensions/agent/components/agent/composer/RunModePopover.vue @@ -13,17 +13,17 @@ import { useI18n } from 'vue-i18n' import { cn } from '@comfyorg/tailwind-utils' import Button from '@/components/ui/button/Button.vue' +import { useToast } from '@/components/ui/toast/toastStore' import { buildTooltipConfig } from '@/composables/useTooltipConfig' import { reportError } from '@/platform/telemetry/reportError' import { useTelemetry } from '@/platform/telemetry' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { AgentRunModeValue } from '../../../stores/agent/agentRunModeStore' import { useAgentRunModeStore } from '../../../stores/agent/agentRunModeStore' const { t } = useI18n() const store = useAgentRunModeStore() -const toast = useToastStore() +const toast = useToast() const open = ref(false) const savingMode = ref(null) @@ -55,7 +55,7 @@ async function onSelectMode(value: string): Promise { surface: 'agent', errorType: 'agent_run_mode_save_failure' }) - toast.add({ severity: 'error', detail: t('agent.runModeSaveFailed') }) + toast.error(t('agent.runModeSaveFailed')) } finally { savingMode.value = null } diff --git a/src/workbench/extensions/agent/components/agent/message/MessageFeedback.test.ts b/src/workbench/extensions/agent/components/agent/message/MessageFeedback.test.ts index 5e2350ea876..46770cf97fa 100644 --- a/src/workbench/extensions/agent/components/agent/message/MessageFeedback.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/MessageFeedback.test.ts @@ -3,7 +3,7 @@ import { render, screen, waitFor, within } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { i18n } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import type { ReplyAsset } from '../../../utils/replyAssets' @@ -161,12 +161,9 @@ describe('MessageFeedback', () => { await user.click(download) await waitFor(() => - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: '1 download failed' - }) - ) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: '1 download failed' + }) ) await waitFor(() => expect(download).toBeEnabled()) diff --git a/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts b/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts index e7ed6466d99..95396087325 100644 --- a/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts @@ -3,7 +3,7 @@ import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' import { i18n } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import type { ReplyAsset } from '../../../utils/replyAssets' @@ -145,12 +145,9 @@ describe('ReplyAudioCard', () => { await userEvent.click(download) await waitFor(() => - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ - severity: 'error', - detail: '1 download failed' - }) - ) + expect(useToast().error).toHaveBeenCalledWith('Error', { + description: '1 download failed' + }) ) await userEvent.click(download) diff --git a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.test.ts b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.test.ts index 08911f046c4..bdc4108b564 100644 --- a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.test.ts @@ -3,7 +3,7 @@ import { render, screen, within } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { i18n } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' @@ -256,11 +256,13 @@ describe('TabLinkCard', () => { }) await userEvent.click(screen.getByRole('button')) - expect(useToastStore().messagesToAdd).toContainEqual({ - severity: 'warn', - detail: 'This workflow target is no longer available.', - life: 5000 - }) + expect(useToast().toasts).toContainEqual( + expect.objectContaining({ + kind: 'warning', + title: 'This workflow target is no longer available.', + duration: 5000 + }) + ) expect(mocks.reportError).not.toHaveBeenCalled() }) diff --git a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue index 1f78c9903fd..f3b7d060ab8 100644 --- a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue +++ b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue @@ -10,7 +10,7 @@ import { useAgentPanelStore } from '../../../stores/agent/agentPanelStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { reportError } from '@/platform/telemetry/reportError' import { useAgentWorkflowTabBindingStore } from '../../../stores/agent/agentWorkflowTabBindingStore' @@ -26,7 +26,7 @@ const { t } = useI18n() const workflowStore = useWorkflowStore() const workflowService = useWorkflowService() const bindingStore = useAgentWorkflowTabBindingStore() -const toast = useToastStore() +const toast = useToast() const { enabled: agentEnabled } = storeToRefs(useAgentPanelStore()) const targetNavigation = useAgentTargetNavigation() @@ -73,11 +73,7 @@ async function open(): Promise { surface: 'agent', errorType: 'agent_target_navigation_failure' }) - toast.add({ - severity: 'warn', - detail: t('agent.targetNavigationUnavailable'), - life: 5000 - }) + toast.warning(t('agent.targetNavigationUnavailable'), { duration: 5000 }) } } } diff --git a/src/workbench/extensions/agent/components/agent/message/UserMessage.clipboard.test.ts b/src/workbench/extensions/agent/components/agent/message/UserMessage.clipboard.test.ts index 00d9b714c24..949a9e03802 100644 --- a/src/workbench/extensions/agent/components/agent/message/UserMessage.clipboard.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/UserMessage.clipboard.test.ts @@ -88,7 +88,9 @@ describe('sent message workflow clipboard', () => { 'Use @[Workflow: 参考 🐈]\n @[Workflow: Missing]!\n@[Node: Sampler #12]\n@[File: notes.txt]' ) - await user.type(editor, 'New: ') + await user.click(editor) + await user.paste('New: ') + expect(store.draft).toBe('New: ') await user.paste() expect(store.draft).toBe( 'New: Use \n !\n@[Node: Sampler #12]\n@[File: notes.txt]' diff --git a/src/workbench/extensions/agent/composables/agent/useAgentConsent.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentConsent.test.ts index 95be1f2f343..c827813a281 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentConsent.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentConsent.test.ts @@ -5,7 +5,7 @@ vi.mock(import('firebase/auth')) import type { GlobalSetting } from '@comfyorg/ingest-types' import { useAuthStore } from '@/stores/authStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, defineComponent, h, reactive, ref } from 'vue' import { setImmediate } from 'node:timers/promises' @@ -137,7 +137,6 @@ describe('useAgentConsent', () => { fetchWithUnifiedRemint.mockReset() fetchWithUnifiedRemint.mockResolvedValue(settingResponse(false)) reportError.mockReset() - vi.mocked(useToastStore().add).mockReset() }) it.for(['first_load', 'button_click'] as const)( @@ -327,9 +326,10 @@ describe('useAgentConsent', () => { expect(useDialogStore().dialogStack).toHaveLength(0) expect(onOpen).not.toHaveBeenCalled() expect(reportError).toHaveBeenCalledOnce() - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + i18n.global.t('g.error'), expect.objectContaining({ - detail: i18n.global.t('agent.consent.loadError') + description: i18n.global.t('agent.consent.loadError') }) ) // `reportError` has no product-analytics sink, so before this the funnel saw @@ -731,7 +731,7 @@ describe('useAgentConsent', () => { expect(fetchWithUnifiedRemint).not.toHaveBeenCalled() expect(onOpen).not.toHaveBeenCalled() expect(reportError).not.toHaveBeenCalled() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) // Accepting the card is only half of the signed-out flow. Consent was // never persisted, so reporting it accepted would put a decision the user // did not complete into the funnel — but the card half did happen, and @@ -808,9 +808,10 @@ describe('useAgentConsent', () => { surface: 'agent', errorType: 'agent_consent_sign_in_failure' }) - expect(useToastStore().add).toHaveBeenCalledWith( + expect(useToast().error).toHaveBeenCalledWith( + i18n.global.t('g.error'), expect.objectContaining({ - detail: i18n.global.t('agent.consent.signInError') + description: i18n.global.t('agent.consent.signInError') }) ) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentConsent.ts b/src/workbench/extensions/agent/composables/agent/useAgentConsent.ts index 191fc8a7e3e..b83b94bb523 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentConsent.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentConsent.ts @@ -10,7 +10,7 @@ import type { AgentConsentTrigger } from '@/platform/telemetry/types' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { useDialogService } from '@/services/dialogService' import { useDialogStore } from '@/stores/dialogStore' import { useAgentConsentStore } from '@/workbench/extensions/agent/stores/agent/agentConsentStore' @@ -45,7 +45,7 @@ export function useAgentConsent() { const dialogStore = useDialogStore() const dialogService = useDialogService() const consentStore = useAgentConsentStore() - const toastStore = useToastStore() + const toast = useToast() const { isLoggedIn } = useCurrentUser() const { accepted, identity, isChecking } = storeToRefs(consentStore) const { t } = i18n.global @@ -248,10 +248,8 @@ export function useAgentConsent() { surface: 'agent', errorType: 'agent_consent_sign_in_failure' }) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('agent.consent.signInError') + toast.error(t('g.error'), { + description: t('agent.consent.signInError') }) return null } @@ -279,10 +277,8 @@ export function useAgentConsent() { surface: 'agent', errorType: 'agent_consent_setting_write_failure' }) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('agent.consent.saveError') + toast.error(t('g.error'), { + description: t('agent.consent.saveError') }) return null } @@ -316,10 +312,8 @@ export function useAgentConsent() { surface: 'agent', errorType: 'agent_consent_setting_load_failure' }) - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: t('agent.consent.loadError') + toast.error(t('g.error'), { + description: t('agent.consent.loadError') }) return null } diff --git a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts index 46f9a988eff..ea356acb7b6 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts @@ -2,8 +2,8 @@ import { storeToRefs } from 'pinia' import { computed, onScopeDispose, ref } from 'vue' import { useI18n } from 'vue-i18n' +import { useToast } from '@/components/ui/toast/toastStore' import type { AgentWorkflowBindSource } from '@/platform/telemetry/types' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -66,7 +66,7 @@ export function useAgentWorkflowSelection({ const composerStore = useAgentComposerStore() const { workflowReferences } = storeToRefs(composerStore) const { t } = useI18n() - const toast = useToastStore() + const toast = useToast() const { refreshCloudWorkflowIds, cloudIdFor, @@ -151,11 +151,7 @@ export function useAgentWorkflowSelection({ function warnWorkflowSelectionFailed( detail = t('shareWorkflow.saveFailedDescription') ): void { - toast.add({ - severity: 'warn', - summary: t('shareWorkflow.saveFailedTitle'), - detail - }) + toast.warning(t('shareWorkflow.saveFailedTitle'), { description: detail }) } async function onSelectWorkflowTarget(path: string): Promise { diff --git a/src/workbench/extensions/agent/crdt/rejectedOpNotice.ts b/src/workbench/extensions/agent/crdt/rejectedOpNotice.ts index 489f5c28c20..b013d4ab218 100644 --- a/src/workbench/extensions/agent/crdt/rejectedOpNotice.ts +++ b/src/workbench/extensions/agent/crdt/rejectedOpNotice.ts @@ -2,9 +2,9 @@ import { throttle } from 'es-toolkit' import type { ThrottledFunction } from 'es-toolkit' import type { Op } from '@comfyorg/comfy-multi-player' +import { useToast } from '@/components/ui/toast/toastStore' import { i18n } from '@/i18n' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import type { DocOpFailure } from './docFrameClient' import type { OpsResultView } from './opSender' @@ -99,11 +99,9 @@ export function createRejectedOpNotifier() { if (existing) return existing const created = throttle( () => { - useToastStore().add({ - severity: 'error', - summary: i18n.global.t('g.error'), - detail, - life: NOTICE_LIFE_MS + useToast().error(i18n.global.t('g.error'), { + description: detail, + duration: NOTICE_LIFE_MS }) }, NOTICE_LIFE_MS, diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.rejectedWidgetWrite.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.rejectedWidgetWrite.test.ts index 31b888b7390..83b4cc13cdf 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.rejectedWidgetWrite.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.rejectedWidgetWrite.test.ts @@ -3,9 +3,9 @@ import { render } from '@testing-library/vue' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { defineComponent, ref } from 'vue' +import { useToast } from '@/components/ui/toast/toastStore' import { i18n } from '@/i18n' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' import { api } from '@/scripts/api' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' @@ -154,8 +154,8 @@ function rejection(opId: string, code: string): Record { } } -function toastDetails(): unknown[] { - return useToastStore().messagesToAdd.map((message) => message.detail) +function toastDescriptions(): (string | undefined)[] { + return useToast().toasts.map((toast) => toast.description) } /** @@ -195,7 +195,7 @@ describe('a human edit the doc host rejects', () => { answerWithOpsResult(rejection(await submit(WIDGET_EDIT), code)) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT) ]) } @@ -223,7 +223,7 @@ describe('a human edit the doc host rejects', () => { } }) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT) ]) }) @@ -255,7 +255,7 @@ describe('a human edit the doc host rejects', () => { } }) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT) ]) }) @@ -265,13 +265,13 @@ describe('a human edit the doc host rejects', () => { answerWithOpsResult(rejection(await submit(WIDGET_EDIT), 'opaque_widgets')) - expect(useToastStore().messagesToAdd).toEqual([ - { - severity: 'error', - summary: i18n.global.t('g.error'), - detail: expect.stringContaining(WIDGET_REJECTION_TEXT), - life: expect.any(Number) - } + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + title: i18n.global.t('g.error'), + description: expect.stringContaining(WIDGET_REJECTION_TEXT), + duration: expect.any(Number) + }) ]) }) @@ -284,7 +284,7 @@ describe('a human edit the doc host rejects', () => { rejection(await submit(NODE_ADD), 'uncatalogued_widget_write') ) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(GENERIC_REJECTION_TEXT) ]) }) @@ -296,7 +296,7 @@ describe('a human edit the doc host rejects', () => { rejection(await submit(WIDGET_EDIT), 'base_version_conflict') ) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(GENERIC_REJECTION_TEXT) ]) }) @@ -307,7 +307,7 @@ describe('a human edit the doc host rejects', () => { answerWithOpsResult(rejection(await submit(WIDGET_EDIT), 'opaque_widgets')) answerWithOpsResult(rejection(await submit(WIDGET_EDIT), 'opaque_widgets')) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT) ]) }) @@ -325,7 +325,7 @@ describe('a human edit the doc host rejects', () => { await vi.advanceTimersByTimeAsync(10_001) answerWithOpsResult(rejection(await submit(WIDGET_EDIT), 'opaque_widgets')) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT), expect.stringContaining(WIDGET_REJECTION_TEXT) ]) @@ -339,7 +339,7 @@ describe('a human edit the doc host rejects', () => { rejection(await submit(WIDGET_EDIT), 'base_version_conflict') ) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(WIDGET_REJECTION_TEXT), expect.stringContaining(GENERIC_REJECTION_TEXT) ]) @@ -357,7 +357,7 @@ describe('a human edit the doc host rejects', () => { skipped: [] }) - expect(useToastStore().messagesToAdd).toEqual([]) + expect(useToast().toasts).toEqual([]) }) // The host refuses a whole batch with a top-level `code` and no `failed` @@ -370,7 +370,7 @@ describe('a human edit the doc host rejects', () => { answerWithOpsResult(batchRefusal('catalog_mismatch')) - expect(toastDetails()).toEqual([ + expect(toastDescriptions()).toEqual([ expect.stringContaining(GENERIC_REJECTION_TEXT) ]) expect(reportedCodes()).toEqual(['catalog_mismatch']) @@ -439,8 +439,8 @@ describe('a human edit the doc host rejects', () => { // Still carries the canonical substring the e2e spec filters on, so the // partial variant cannot break that contract. - expect(toastDetails()).toEqual([expect.stringContaining(expected)]) - expect(String(toastDetails()[0])).toContain('some earlier edits were') + expect(toastDescriptions()).toEqual([expect.stringContaining(expected)]) + expect(toastDescriptions()[0]).toContain('some earlier edits were') } ) }) diff --git a/src/workbench/extensions/manager/components/ManagerProgressToast.test.ts b/src/workbench/extensions/manager/components/ManagerProgressToast.test.ts index 9e777e9350a..0143ed18f8d 100644 --- a/src/workbench/extensions/manager/components/ManagerProgressToast.test.ts +++ b/src/workbench/extensions/manager/components/ManagerProgressToast.test.ts @@ -61,7 +61,9 @@ it('offers startup retry while keeping accepted tasks pending', async () => { } }) expect( - screen.getByText('Tasks are pending. Retry to continue.') + screen.getByText('Tasks are pending. Retry to continue.', { + selector: 'span' + }) ).toBeVisible() expect(screen.getByRole('button', { name: 'Close' })).toBeDisabled() expect( @@ -99,7 +101,7 @@ it('shows failed installations without suggesting a successful change', async () expect( screen.queryByRole('button', { name: 'Apply Changes' }) ).not.toBeInTheDocument() - expect(screen.getByText('Failed')).toBeInTheDocument() + expect(screen.getByText('Failed', { selector: 'span' })).toBeInTheDocument() const user = userEvent.setup() await user.click(screen.getByRole('button', { name: 'Expand' })) await user.click(screen.getByRole('tab', { name: 'Failed' })) @@ -252,7 +254,7 @@ it.for([[], ['failed']])( } }) expect( - screen.getByText(en.manager.restartToApplyChanges) + screen.getByText(en.manager.restartToApplyChanges, { selector: 'span' }) ).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Apply Changes' })).toBeEnabled() } @@ -297,7 +299,7 @@ it('finishes an empty batch without an error or restart action', () => { plugins: [createI18n({ legacy: false, locale: 'en', messages: { en } })] } }) - expect(screen.getByText(en.g.completed)).toBeVisible() + expect(screen.getByText(en.g.completed, { selector: 'span' })).toBeVisible() expect(screen.queryByText('Failed')).not.toBeInTheDocument() expect( screen.queryByRole('button', { name: 'Apply Changes' }) @@ -487,3 +489,64 @@ it.for([ ).toBeVisible() } ) + +it('renders only while task logs exist', async () => { + render(ManagerProgressToast, { + global: { + plugins: [createI18n({ legacy: false, locale: 'en', messages: { en } })] + } + }) + expect(screen.queryByRole('button', { name: 'Expand' })).toBeNull() + + useComfyManagerStore().taskLogs = [ + { logs: [], taskId: 'pending', taskName: 'Installing pack' } + ] + await nextTick() + + expect(screen.getByRole('button', { name: 'Expand' })).toBeVisible() +}) + +it.for([ + { + name: 'installing', + announcement: en.manager.installingDependencies, + arrange: (store: ReturnType) => { + vi.spyOn(store, 'isProcessingTasks', 'get').mockReturnValue(true) + } + }, + { + name: 'waiting on a failed queue start', + announcement: en.manager.queueWaitingToContinue, + arrange: (store: ReturnType) => { + vi.spyOn(store, 'isProcessingTasks', 'get').mockReturnValue(true) + store.queueError = 'Queue start temporarily unavailable' + } + }, + { + name: 'finished with a failure', + announcement: en.g.failed, + arrange: (store: ReturnType) => { + store.failedTasksIds = ['task'] + } + }, + { + name: 'finished successfully', + announcement: en.manager.restartToApplyChanges, + arrange: (store: ReturnType) => { + store.succeededTasksIds = ['task'] + } + } +])('announces the queue status when $name', ({ announcement, arrange }) => { + const store = useComfyManagerStore() + store.taskLogs = [{ taskId: 'task', taskName: 'Installing pack', logs: [] }] + arrange(store) + render(ManagerProgressToast, { + global: { + plugins: [createI18n({ legacy: false, locale: 'en', messages: { en } })] + } + }) + + expect( + screen.getByText(announcement, { selector: '[role="status"]' }) + ).toBeInTheDocument() +}) diff --git a/src/workbench/extensions/manager/components/ManagerProgressToast.vue b/src/workbench/extensions/manager/components/ManagerProgressToast.vue index a088c171def..9cf144d2caa 100644 --- a/src/workbench/extensions/manager/components/ManagerProgressToast.vue +++ b/src/workbench/extensions/manager/components/ManagerProgressToast.vue @@ -6,7 +6,7 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue' import { useI18n } from 'vue-i18n' import DotSpinner from '@/components/common/DotSpinner.vue' -import HoneyToast from '@/components/honeyToast/HoneyToast.vue' +import ToastPanel from '@/components/ui/toast/ToastPanel.vue' import Button from '@/components/ui/button/Button.vue' import Tabs from '@/components/ui/tabs/Tabs.vue' import TabsContent from '@/components/ui/tabs/TabsContent.vue' @@ -79,6 +79,17 @@ const currentTaskName = computed(() => { return task?.taskName ?? t('manager.installingDependencies') }) +const announcement = computed(() => { + if (comfyManagerStore.queueError && isInProgress.value) + return t('manager.queueWaitingToContinue') + if (isRestarting.value || isRestartCompleted.value) + return currentTaskName.value + if (isInProgress.value) return t('manager.installingDependencies') + if (hasSuccessfulTasks.value) return t('manager.restartToApplyChanges') + if (comfyManagerStore.failedTasksIds.length) return t('g.failed') + return t('g.completed') +}) + const sectionsContainerRef = ref(null) const { y: scrollY } = useScroll(sectionsContainerRef, { eventListenerOptions: { passive: true } @@ -162,7 +173,7 @@ onBeforeUnmount(() => { diff --git a/src/workbench/extensions/manager/components/manager/button/PackUpdateButton.test.ts b/src/workbench/extensions/manager/components/manager/button/PackUpdateButton.test.ts index d17f94ab5e8..f3c70b9bd2d 100644 --- a/src/workbench/extensions/manager/components/manager/button/PackUpdateButton.test.ts +++ b/src/workbench/extensions/manager/components/manager/button/PackUpdateButton.test.ts @@ -5,7 +5,7 @@ import { nextTick } from 'vue' import { createI18n } from 'vue-i18n' import en from '@/locales/en/main.json' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import * as registry from '@/services/comfyRegistryService' import type { components } from '@/types/comfyRegistryTypes' import { useComfyManagerStore } from '@/workbench/extensions/manager/stores/comfyManagerStore' @@ -96,24 +96,27 @@ it('offers an explicit switch to the latest installable version, including Flagg }) it.for([ - { name: 'no eligible release', versions: [], severity: 'warn' }, - { name: 'registry failure', versions: null, severity: 'error' } -])('does not install and reports $name', async ({ versions, severity }) => { - const service = registry.useComfyRegistryService() - vi.spyOn(service, 'getPackVersions').mockResolvedValue(versions) - vi.spyOn(registry, 'useComfyRegistryService').mockReturnValue(service) - renderButton() + { kind: 'warning', name: 'no eligible release', versions: [] }, + { kind: 'error', name: 'registry failure', versions: null } +] as const)( + 'does not install and reports $name', + async ({ kind, versions }) => { + const service = registry.useComfyRegistryService() + vi.spyOn(service, 'getPackVersions').mockResolvedValue( + versions && [...versions] + ) + vi.spyOn(registry, 'useComfyRegistryService').mockReturnValue(service) + renderButton() - await userEvent.click(screen.getByRole('button', { name: 'Update' })) + await userEvent.click(screen.getByRole('button', { name: 'Update' })) - await waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity }) - ) - }) - expect(useComfyManagerStore().installPack.call).not.toHaveBeenCalled() - expect(screen.getByRole('button', { name: 'Update' })).toBeEnabled() -}) + await waitFor(() => { + expect(useToast().toasts).toEqual([expect.objectContaining({ kind })]) + }) + expect(useComfyManagerStore().installPack.call).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Update' })).toBeEnabled() + } +) it('does not re-enable disabled packs during a batch switch', async () => { const manager = useComfyManagerStore() @@ -152,9 +155,7 @@ it('skips switching when the selected version is already installed', async () => await userEvent.click(screen.getByRole('button', { name: 'Update' })) await waitFor(() => { - expect(useToastStore().add).toHaveBeenCalledWith( - expect.objectContaining({ severity: 'info' }) - ) + expect(useToast().info).toHaveBeenCalled() }) expect(manager.installPack.call).not.toHaveBeenCalled() }) diff --git a/src/workbench/extensions/manager/composables/useManagerQueue.ts b/src/workbench/extensions/manager/composables/useManagerQueue.ts index 0d7ada5d998..3e2d0d53270 100644 --- a/src/workbench/extensions/manager/composables/useManagerQueue.ts +++ b/src/workbench/extensions/manager/composables/useManagerQueue.ts @@ -4,7 +4,7 @@ import type { Ref } from 'vue' import { computed, ref } from 'vue' import { t } from '@/i18n' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { app } from '@/scripts/app' import { normalizePackKeys } from '@/utils/packUtils' import type { components } from '@/workbench/extensions/manager/types/generatedManagerTypes' @@ -28,7 +28,7 @@ export const useManagerQueue = ( taskQueue: Ref, installedPacks: Ref> ) => { - const toastStore = useToastStore() + const toast = useToast() // Task queue state (read-only from server) const maxHistoryItems = ref(64) @@ -120,11 +120,7 @@ export const useManagerQueue = ( isHistoryTaskFromThisClient(completedTask) && !wasCompleted ) { - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: result - }) + toast.error(t('g.error'), { description: result }) } } } diff --git a/src/workbench/extensions/manager/composables/useManagerState.test.ts b/src/workbench/extensions/manager/composables/useManagerState.test.ts index 7ed92a8ace4..d94586d78a7 100644 --- a/src/workbench/extensions/manager/composables/useManagerState.test.ts +++ b/src/workbench/extensions/manager/composables/useManagerState.test.ts @@ -1,6 +1,6 @@ +import { useToast } from '@/components/ui/toast/toastStore' import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { useToastStore } from '@/platform/updates/common/toastStore' import { useCommandStore } from '@/stores/commandStore' import { api } from '@/scripts/api' import { useSystemStatsStore } from '@/stores/systemStatsStore' @@ -276,7 +276,7 @@ describe('useManagerState', () => { expect(managerState.isManagerEnabled.value).toBe(false) }) - it('fires warn-severity toast exactly once across multiple consumers', () => { + it('fires the warning toast exactly once across multiple consumers', () => { systemStatsStore.$patch({ systemStats: enabledManagerStats(), isInitialized: true @@ -290,13 +290,14 @@ describe('useManagerState', () => { useManagerState() useManagerState() - expect(useToastStore().add).toHaveBeenCalledTimes(1) - expect(useToastStore().add).toHaveBeenCalledWith({ - severity: 'warn', - summary: 'manager.incompatibleVersion.title', - detail: 'manager.incompatibleVersion.message', - life: 15000 - }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'manager.incompatibleVersion.message', + duration: 15000, + kind: 'warning', + title: 'manager.incompatibleVersion.title' + }) + ]) }) it('openManager on INCOMPATIBLE re-emits the upgrade toast without settings redirect', async () => { @@ -310,17 +311,15 @@ describe('useManagerState', () => { mockServerFeatures({ supports_v4: true, supports_csrf_post: false }) const managerState = useManagerState() - expect(useToastStore().add).toHaveBeenCalledTimes(1) + expect(useToast().warning).toHaveBeenCalledTimes(1) await managerState.openManager() - expect(useToastStore().add).toHaveBeenCalledTimes(2) + expect(useToast().warning).toHaveBeenCalledTimes(2) // second call must still be the upgrade toast, not an error toast - expect(useToastStore().add).toHaveBeenLastCalledWith({ - severity: 'warn', - summary: 'manager.incompatibleVersion.title', - detail: 'manager.incompatibleVersion.message', - life: 15000 - }) + expect(useToast().warning).toHaveBeenLastCalledWith( + 'manager.incompatibleVersion.title', + { description: 'manager.incompatibleVersion.message', duration: 15000 } + ) }) it('does not fire upgrade toast when state is NEW_UI', () => { @@ -334,7 +333,7 @@ describe('useManagerState', () => { mockServerFeatures({ supports_v4: true, supports_csrf_post: true }) useManagerState() - expect(useToastStore().add).not.toHaveBeenCalled() + expect(useToast().toasts).toEqual([]) }) }) diff --git a/src/workbench/extensions/manager/composables/useManagerState.ts b/src/workbench/extensions/manager/composables/useManagerState.ts index 734f5523978..d205b29b311 100644 --- a/src/workbench/extensions/manager/composables/useManagerState.ts +++ b/src/workbench/extensions/manager/composables/useManagerState.ts @@ -4,7 +4,7 @@ import { computed, readonly, watch } from 'vue' import { t } from '@/i18n' import { isCloud } from '@/platform/distribution/types' import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { useCommandStore } from '@/stores/commandStore' import { useSystemStatsStore } from '@/stores/systemStatsStore' @@ -29,11 +29,9 @@ let incompatibleToastShown = false const showIncompatibleToast = (): void => { if (incompatibleToastShown) return incompatibleToastShown = true - useToastStore().add({ - severity: 'warn', - summary: t('manager.incompatibleVersion.title'), - detail: t('manager.incompatibleVersion.message'), - life: 15000 + useToast().warning(t('manager.incompatibleVersion.title'), { + description: t('manager.incompatibleVersion.message'), + duration: 15000 }) } @@ -247,10 +245,8 @@ export function useManagerState() { } catch { // If legacy command doesn't exist if (options?.showToastOnLegacyError !== false) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('manager.legacyMenuNotAvailable') + useToast().error(t('g.error'), { + description: t('manager.legacyMenuNotAvailable') }) } // Fallback to extensions panel if not showing toast @@ -263,10 +259,8 @@ export function useManagerState() { case ManagerUIState.NEW_UI: if (options?.isLegacyOnly) { - useToastStore().add({ - severity: 'error', - summary: t('g.error'), - detail: t('manager.legacyMenuNotAvailable') + useToast().error(t('g.error'), { + description: t('manager.legacyMenuNotAvailable') }) } else { managerDialog.show(options?.initialTab, options?.initialPackId) diff --git a/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts b/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts index de092ccf742..a3a7daa7a45 100644 --- a/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts +++ b/src/workbench/extensions/manager/stores/comfyManagerStore.test.ts @@ -13,7 +13,7 @@ import { nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import en from '@/locales/en/main.json' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import * as registryService from '@/services/comfyRegistryService' import type { components as RegistryComponents } from '@/types/comfyRegistryTypes' @@ -135,8 +135,8 @@ describe('useComfyManagerStore', () => { expectedInstalled: false, expectedToasts: [ expect.objectContaining({ - severity: 'error', - detail: + kind: 'error', + description: 'This action is not allowed by the current security configuration. See the terminal for details.' }) ] @@ -150,8 +150,8 @@ describe('useComfyManagerStore', () => { expectedInstalled: false, expectedToasts: [ expect.objectContaining({ - severity: 'error', - detail: 'Download failed' + kind: 'error', + description: 'Download failed' }) ] }, @@ -164,8 +164,8 @@ describe('useComfyManagerStore', () => { expectedInstalled: true, expectedToasts: [ expect.objectContaining({ - severity: 'error', - detail: 'Version installation denied' + kind: 'error', + description: 'Version installation denied' }) ] }, @@ -238,10 +238,10 @@ describe('useComfyManagerStore', () => { expect(store.isPackInstalled('test-pack')).toBe(expectedInstalled) expect(store.installedPacks).toEqual(installed) expect(store.isProcessingTasks).toBe(false) - expect(useToastStore().messagesToAdd).toEqual(expectedToasts) + expect(useToast().toasts).toEqual(expectedToasts) api.dispatchCustomEvent('cm-task-completed', detail) - expect(useToastStore().messagesToAdd).toEqual(expectedToasts) + expect(useToast().toasts).toEqual(expectedToasts) } ) @@ -265,10 +265,10 @@ describe('useComfyManagerStore', () => { expect(store.isPackInstalling('test-pack')).toBe(false) expect(store.isPackInstalled('test-pack')).toBe(false) expect(store.isProcessingTasks).toBe(false) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'Request rejected. Check the terminal.' + kind: 'error', + description: 'Request rejected. Check the terminal.' }) ]) expect(mockManagerService.startQueue).not.toHaveBeenCalled() @@ -297,8 +297,10 @@ describe('useComfyManagerStore', () => { expect(store.isPackInstalling('test-pack')).toBe(true) expect(store.isProcessingTasks).toBe(true) expect(store.failedTasksIds).toEqual([]) - expect(useToastStore().messagesToAdd).toEqual([ - expect.objectContaining({ detail: 'Queue start temporarily unavailable' }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + description: 'Queue start temporarily unavailable' + }) ]) await store.installPack.call(request) @@ -342,8 +344,8 @@ describe('useComfyManagerStore', () => { expect(store.isPackInstalling('test-pack')).toBe(false) expect(store.isPackInstalled('test-pack')).toBe(false) expect(store.isProcessingTasks).toBe(false) - expect(useToastStore().messagesToAdd.at(-1)).toEqual( - expect.objectContaining({ severity: 'error', detail: result }) + expect(useToast().toasts.at(-1)).toEqual( + expect.objectContaining({ kind: 'error', description: result }) ) }) @@ -374,8 +376,11 @@ describe('useComfyManagerStore', () => { expect(store.isPackInstalling('pending-pack')).toBe(true) expect(store.isPackInstalling('rejected-pack')).toBe(false) expect(store.isProcessingTasks).toBe(true) - expect(useToastStore().messagesToAdd).toEqual([ - expect.objectContaining({ severity: 'error', detail: 'Request rejected' }) + expect(useToast().toasts).toEqual([ + expect.objectContaining({ + kind: 'error', + description: 'Request rejected' + }) ]) }) @@ -618,10 +623,10 @@ describe('useComfyManagerStore', () => { api.dispatchCustomEvent('cm-task-completed', detail) await nextTick() api.dispatchCustomEvent('cm-task-completed', detail) - expect(useToastStore().messagesToAdd).toEqual([ + expect(useToast().toasts).toEqual([ expect.objectContaining({ - severity: 'error', - detail: 'Operation failed' + kind: 'error', + description: 'Operation failed' }) ]) expect(store.failedTasksLogs.map((log) => log.taskId)).toEqual([ @@ -698,7 +703,7 @@ describe('useComfyManagerStore', () => { api.dispatchCustomEvent('cm-task-completed', detail) await nextTick() api.dispatchCustomEvent('cm-task-completed', detail) - expect(useToastStore().messagesToAdd).toHaveLength(toastCount) + expect(useToast().toasts).toHaveLength(toastCount) } ) @@ -743,7 +748,7 @@ describe('useComfyManagerStore', () => { expect(store.isTaskInProgress(taskId)).toBe(false) expect(store.succeededTasksLogs.map((log) => log.taskId)).toEqual([taskId]) expect(store.failedTasksIds).toEqual([]) - expect(useToastStore().messagesToAdd).toEqual([]) + expect(useToast().toasts).toEqual([]) await store.enablePack({ id: 'other-pack', version: '1.0.0' }) expect(store.isProcessingTasks).toBe(true) @@ -881,7 +886,7 @@ describe('useComfyManagerStore', () => { newerResult: null, newerError: 'Latest startup failed', expectedToasts: [ - expect.objectContaining({ detail: 'Latest startup failed' }) + expect.objectContaining({ description: 'Latest startup failed' }) ] }, { @@ -891,7 +896,7 @@ describe('useComfyManagerStore', () => { newerResult: null, newerError: 'Latest startup failed', expectedToasts: [ - expect.objectContaining({ detail: 'Latest startup failed' }) + expect.objectContaining({ description: 'Latest startup failed' }) ] } ])( @@ -932,7 +937,7 @@ describe('useComfyManagerStore', () => { expect(store.isProcessingTasks).toBe(true) expect(store.queueError).toBe(newerError) - expect(useToastStore().messagesToAdd).toEqual(expectedToasts) + expect(useToast().toasts).toEqual(expectedToasts) } ) @@ -963,7 +968,7 @@ describe('useComfyManagerStore', () => { expect(store.isProcessingTasks).toBe(true) expect(store.queueError).toBeNull() - expect(useToastStore().messagesToAdd).toEqual([]) + expect(useToast().toasts).toEqual([]) }) it('keeps a newer completion event when an earlier queue status request finishes', async () => { diff --git a/src/workbench/extensions/manager/stores/comfyManagerStore.ts b/src/workbench/extensions/manager/stores/comfyManagerStore.ts index 2ae45f305bf..452e7e50803 100644 --- a/src/workbench/extensions/manager/stores/comfyManagerStore.ts +++ b/src/workbench/extensions/manager/stores/comfyManagerStore.ts @@ -7,7 +7,7 @@ import { t } from '@/i18n' import { useCachedRequest } from '@/composables/useCachedRequest' import { useServerLogs } from '@/composables/useServerLogs' import { reportError } from '@/platform/telemetry/reportError' -import { useToastStore } from '@/platform/updates/common/toastStore' +import { useToast } from '@/components/ui/toast/toastStore' import { api } from '@/scripts/api' import { app } from '@/scripts/app' import { useComfyRegistryService } from '@/services/comfyRegistryService' @@ -43,7 +43,7 @@ function isTaskForRequest(taskId: string, requestId: string) { */ export const useComfyManagerStore = defineStore('comfyManager', () => { const managerService = useComfyManagerService() - const toastStore = useToastStore() + const toast = useToast() const installedPacks = ref({}) const enabledPacksIds = ref>(new Set()) @@ -304,11 +304,7 @@ export const useComfyManagerStore = defineStore('comfyManager', () => { if (requestId === queueStartRequest && isProcessingTasks.value) { queueError.value = managerService.error.value ?? t('g.unknownError') - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: queueError.value - }) + toast.error(t('g.error'), { description: queueError.value }) } } @@ -333,11 +329,7 @@ export const useComfyManagerStore = defineStore('comfyManager', () => { taskIdToPackId.value.delete(taskId) pendingRequests.value.delete(taskId) const message = managerService.error.value ?? t('g.unknownError') - toastStore.add({ - severity: 'error', - summary: t('g.error'), - detail: message - }) + toast.error(t('g.error'), { description: message }) requestFailures.value[taskId] = { ui_id: taskId, @@ -392,33 +384,25 @@ export const useComfyManagerStore = defineStore('comfyManager', () => { policy: keyof typeof versionStatusFilters ) { const registry = useComfyRegistryService() - const summary = pack.name ?? pack.id + const packName = pack.name ?? pack.id const versions = await registry.getPackVersions(pack.id, { statuses: versionStatusFilters[policy] }) if (!isEnabledPackId(pack.id)) return if (versions === null) { - toastStore.add({ - severity: 'error', - summary, - detail: registry.error.value ?? t('manager.errorConnecting') + toast.error(packName, { + description: registry.error.value ?? t('manager.errorConnecting') }) return } const version = versions[0]?.version if (!version) { - toastStore.add({ - severity: 'warn', - summary, - detail: t('manager.noUpdateVersion') - }) + toast.warning(packName, { description: t('manager.noUpdateVersion') }) return } if (version === getInstalledPackVersion(pack.id)) { - toastStore.add({ - severity: 'info', - summary, - detail: t('manager.updateVersionInstalled', { version }) + toast.info(packName, { + description: t('manager.updateVersionInstalled', { version }) }) return } @@ -453,10 +437,8 @@ export const useComfyManagerStore = defineStore('comfyManager', () => { surface: 'platform', errorType: 'failure_updating_node_packs' }) - toastStore.add({ - severity: 'error', - summary: t('manager.update'), - detail: t('manager.updateFailed') + toast.error(t('manager.update'), { + description: t('manager.updateFailed') }) } finally { for (const pack of packsToUpdate) {