Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(notification): migrate to React Base UI Toast (#20332)

boojackd7d670426c64
diff --git a/docs/plans/2026-05-13-notification-react-migration-design.md b/docs/plans/2026-05-13-notification-react-migration-design.md
new file mode 100644
index 0000000000..c4bb61c6e2
--- /dev/null
+++ b/docs/plans/2026-05-13-notification-react-migration-design.md
@@ -0,0 +1,165 @@
+# Notification System Migration — Vue → React (Base UI Toast)
+
+**Date:** 2026-05-13
+**Companion docs:**
+- [2026-04-08-react-migration-playbook.md](./2026-04-08-react-migration-playbook.md)
+- [2026-05-12-react-migration-status-and-plan.md](./2026-05-12-react-migration-status-and-plan.md)
+
+## Goal
+
+Replace the Vue-rendered notification system (`NotificationContext.vue` + Naive UI's `NNotificationProvider` + `useNotification()`) with a React-rendered one built on Base UI's Toast primitive. After this work, **React owns toast rendering for the entire app**; Vue retains only the `pushNotification()` API for backwards compatibility with its 17 remaining callers, which now route through a window event into the React renderer.
+
+## Non-goals
+
+- Migrate `App.vue` itself to React — that's Phase B2.
+- Migrate the Pinia `notificationStore` to Zustand — that's Phase B3. The Pinia store stays as a thin pass-through during this PR.
+- Add new toast variants (action toasts, promise toasts, etc.). Parity with the current Naive UI surface only.
+
+## Current architecture
+
+| Path | Renderer |
+|---|---|
+| Vue caller → `useNotificationStore().pushNotification(...)` → `watchEffect` in `NotificationContext.vue` → `useNotification().create()` | Naive UI |
+| React caller → `useAppStore().notify(...)` (Zustand slice) → emits `window` `CustomEvent('bb.react-notification')` → `NotificationContext.vue` catches → `useNotification().create()` | Naive UI (via Vue bridge) |
+
+149 total `pushNotification` consumers: 17 Vue, 132 React.
+
+## Target architecture
+
+```
+Vue caller ──┐
+ ▼
+ pushNotification() ─┐ ┌─► Base UI <Toaster />
+ ▼ │ (React tree)
+ Pinia notificationStore │
+ │ emit CustomEvent('bb.vue-notification')
+ ▼ │
+ window listener (react/lib/toast.ts) │
+ │ │
+ ▼ │
+ toastManager.add() ─────────────────────►─┘
+ ▲
+ │
+React caller ──► notify() ────┘
+```
+
+Single renderer (React/Base UI). Vue callers keep their API; the Pinia store now publishes a window event instead of running its own render loop. React callers bypass the event entirely and call `toastManager.add()` straight from the Zustand slice.
+
+## File layout
+
+### Created
+
+| File | Purpose |
+|---|---|
+| `frontend/src/react/components/ui/toast.tsx` | shadcn-style styled wrappers around `@base-ui/react/toast` parts (`Title`, `Description`, `Action`, `Close`, `Arrow`, `Root`). `cva` variants for `type: success / info / warn / critical`. |
+| `frontend/src/react/components/ui/toaster.tsx` | The `<Toaster />` mount: `Toast.Provider` + `Toast.Portal` (`container={getLayerRoot("overlay")}`) + `Toast.Viewport`. Subscribes to `toastManager` via Base UI's hook to render items. |
+| `frontend/src/react/lib/toast.ts` | Module-level `toastManager = createToastManager()` (no React tree dependency). Exports `pushReactNotification(item: NotificationCreate)` which maps the existing `NotificationCreate` shape to a Base UI Toast. Registers the `bb.vue-notification` window listener at module-eval time (top-level side effect). |
+
+### Modified
+
+| File | Change |
+|---|---|
+| `frontend/src/react/stores/app/notification.ts` | `notify()` calls `toastManager.add()` directly. Drop `emitReactNotification` import. Remove the unused `notifications` state array (no consumer reads it). |
+| `frontend/src/react/shell-bridge.ts` | Remove `notification: "bb.react-notification"` event + `emitReactNotification()`. Direction is flipped now. |
+| `frontend/src/store/modules/notification.ts` (Pinia) | Replace internal queue/`tryPopNotification` consumption with: emit `CustomEvent('bb.vue-notification', { detail: item })` on every `pushNotification(...)`. Keep the public method signatures unchanged so all 17 Vue callers compile. |
+| `frontend/src/App.vue` | Remove `<NNotificationProvider>` and `<NotificationContext>` wrappers; drop their imports. |
+| `frontend/src/react/main.tsx` (or wherever the React shell root mounts) | Render `<Toaster />` once at the React root. |
+| `frontend/src/shell-bridge.test.ts` | Drop the `NotificationContext.vue` mock entry. |
+
+### Deleted
+
+| File | |
+|---|---|
+| `frontend/src/NotificationContext.vue` | The Vue render loop is gone. |
+
+## API parity (`NotificationCreate` mapping)
+
+The existing shape is preserved:
+
+```ts
+{
+ module: "bytebase",
+ style: "SUCCESS" | "INFO" | "WARN" | "CRITICAL",
+ title: string,
+ description?: string | (() => unknown),
+ link?: string,
+ linkTitle?: string,
+ manualHide?: boolean,
+}
+```
+
+Mapping in `pushReactNotification`:
+
+| Field | Maps to |
+|---|---|
+| `style` → `type` | `SUCCESS`→`"success"`, `INFO`→`"info"`, `WARN`→`"warning"`, `CRITICAL`→`"error"`. |
+| `title` | `<Toast.Title>` |
+| `description: string` | `<Toast.Description>` |
+| `description: () => VNode` | **Not supported.** Function-typed descriptions must be plain strings; if grep finds any caller using a function, rewrite that caller as part of this PR (audit before merge). |
+| `link + linkTitle` | `<Toast.Action>` rendered inside the toast body, opens link in new tab. |
+| `manualHide: true` | `Toast.Root` with `timeout={null}` (or equivalent — confirm against Base UI's API at implementation time). |
+| Default duration | 6000ms. |
+| `style: "CRITICAL"` duration | 10000ms. |
+| `module: "bytebase"` filter | Applied at the window listener level before calling `toastManager.add()`. |
+
+## Accessibility
+
+Base UI Toast provides ARIA live region semantics, focus management, swipe-to-dismiss, and keyboard navigation (Tab/Shift+Tab between toasts, Esc to dismiss focused one) out of the box. Set `priority="high"` (or equivalent assertive politeness) on `CRITICAL` toasts; `priority="low"` on others.
+
+`<Toast.Close>` button: `aria-label={t("common.close")}`.
+
+## Layering
+
+`<Toast.Portal container={getLayerRoot("overlay")}>` — same overlay family as dialogs, sheets, dropdowns. Position: bottom-right (matches the current Naive UI default). No raw `z-index` per `frontend/AGENTS.md`'s overlay policy.
+
+## i18n
+
+No new keys required. Existing `pushNotification` callers already pass localized strings. The close-button `aria-label` reuses `common.close`.
+
+## Risks & mitigations
+
+1. **Listener registration order.** The `bb.vue-notification` window listener must be registered before any `pushNotification` fires. Achieved by registering it at module-eval time (top-level side effect in `react/lib/toast.ts`); the React entry point imports the module before any rendering or Vue bootstrap completes.
+2. **Duplicate toasts during transition.** If `NotificationContext.vue` is still mounted when the new path lights up, every notification renders twice. Mitigation: deletion of `NotificationContext.vue` lands in the **same commit** that flips the Pinia store to emit events. Atomic switch.
+3. **Function-typed `description`.** The existing API permits `description: () => VNode` for Vue render functions. React can't render Vue VNodes. Pre-implementation audit: `grep -rn "description:.*=>" frontend/src` to find function uses; rewrite as plain strings (expected count: ~0–3). If a caller genuinely needs richness, use a `Trans` component string with markup placeholders instead.
+4. **Test mocks.** `shell-bridge.test.ts` and `layout-bridge.test.ts` mock `NotificationContext.vue`. Remove those entries when the file is deleted.
+5. **Pinia store consumers.** Any code that depends on `notificationStore.tryPopNotification` (the queue-pop API) breaks. Audit: `grep -rn "tryPopNotification" frontend/src`. The only known consumer is `NotificationContext.vue` itself (also being deleted), but verify.
+
+## Validation gates
+
+| Gate | When |
+|---|---|
+| `pnpm --dir frontend fix` | After every commit |
+| `pnpm --dir frontend type-check` | After every commit |
+| `pnpm --dir frontend test` | After commits 3 + 5 (state plumbing changes) |
+| Manual smoke | After commit 5 — see below |
+
+### Manual smoke checklist
+
+- Trigger a SUCCESS toast (e.g. successful save) — green, auto-dismisses at 6s.
+- Trigger an INFO toast — blue, auto-dismisses at 6s.
+- Trigger a WARN toast — yellow.
+- Trigger a CRITICAL toast (e.g. SQL execution error) — red, auto-dismisses at 10s.
+- Trigger a toast with `link + linkTitle` — action button renders, opens link in new tab.
+- Trigger a toast with `manualHide: true` — stays until the close button is clicked.
+- Trigger multiple toasts rapidly — they stack with proper animations.
+- Hover a toast — pause auto-dismiss; mouse out — resume.
+- Tab into toasts — focus moves between them; Esc dismisses focused one.
+- Swipe gesture on touch — dismisses.
+- Toast renders above open dialogs and sheets (same `overlay` layer).
+- Toast renders below `critical` layer (session-expired surface).
+- Auth flow with `pushNotification` from middlewares (e.g. trigger an auth interceptor error) — toast renders correctly.
+
+## Estimated commits
+
+1. **Add Base UI Toast wrappers.** Create `react/components/ui/toast.tsx` + `react/components/ui/toaster.tsx`. No mounts yet, no wiring. Static; just shadcn-style component definitions.
+2. **Add the toast manager + window listener.** Create `react/lib/toast.ts` with `createToastManager()` and `pushReactNotification()`. Wire the `bb.vue-notification` listener.
+3. **Mount `<Toaster />` + flip the Pinia store.** Render `<Toaster />` in the React root. Rewrite `store/modules/notification.ts` to dispatch the window event instead of running its own loop. Atomic with commit 5.
+4. **Swap the React slice.** Update `react/stores/app/notification.ts` to call `toastManager.add()` directly. Drop the `emitReactNotification` path from `react/shell-bridge.ts`.
+5. **Delete the Vue path.** Remove `NotificationContext.vue`, unwrap `App.vue`, drop test mocks. Same commit as 3 if we want true atomicity (recommended).
+
+Practically, commits 3 and 5 should be a single commit — otherwise the app double-renders or no-renders for the duration between. Final shape: **4 commits**.
+
+## Out-of-scope follow-ups
+
+- Phase B3: Pinia `notificationStore` → Zustand. The pass-through becomes a thin Zustand slice; the window-event bridge collapses to a direct function call.
+- Phase B2: App.vue migration. When `App.vue` becomes React, the `bb.vue-notification` event bridge can be deleted entirely — only Vue store callers will still need it, and the Vue store itself dies in B3.
diff --git a/docs/plans/2026-05-13-notification-react-migration-plan.md b/docs/plans/2026-05-13-notification-react-migration-plan.md
new file mode 100644
index 0000000000..ea5b1a269a
--- /dev/null
+++ b/docs/plans/2026-05-13-notification-react-migration-plan.md
@@ -0,0 +1,1107 @@
+# Notification System Migration — Vue → React (Base UI Toast) Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Replace `NotificationContext.vue` + Naive UI's `NNotificationProvider` with a React renderer built on Base UI Toast. React becomes the sole renderer; Vue's existing `pushNotification()` API keeps working by emitting a window event that the React side catches.
+
+**Architecture:** Module-level `toastManager = createToastManager()` lives outside any React tree so non-component code can call it. A long-lived React root mounted at `<div id="bb-toaster-root">` renders `<Toaster />`, which iterates the manager's toasts via `useToastManager()`. Vue's Pinia `notificationStore` dispatches `bb.vue-notification` window events; a module-eval-time listener forwards them to the manager.
+
+**Tech Stack:** React, `@base-ui/react/toast`, `class-variance-authority`, Tailwind CSS v4, Vue 3 (Pinia store stays, only renderer dies), Vite `import.meta.glob`.
+
+**Companion docs:**
+- Spec: `docs/plans/2026-05-13-notification-react-migration-design.md`
+- Playbook: `docs/plans/2026-04-08-react-migration-playbook.md`
+
+---
+
+## Branch setup
+
+- [ ] **Step 1: Pull latest main and create branch**
+
+```bash
+git checkout main && git pull --ff-only
+git checkout -b chore/frontend/notification-react-migration
+```
+
+- [ ] **Step 2: Baseline green**
+
+```bash
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+```
+
+Expected: type-check exit 0; vitest reports all tests pass.
+
+---
+
+## Task 1: Add shadcn-style wrappers around Base UI Toast parts
+
+Static UI primitives. No runtime wiring yet.
+
+**Files:**
+- Create: `frontend/src/react/components/ui/toast.tsx`
+
+- [ ] **Step 1: Write `toast.tsx`**
+
+```tsx
+import { Toast as BaseToast } from "@base-ui/react/toast";
+import { cva, type VariantProps } from "class-variance-authority";
+import { CheckCircle2, Info, AlertTriangle, XCircle, X } from "lucide-react";
+import type { ComponentProps, ReactNode } from "react";
+import { cn } from "@/react/lib/utils";
+
+// Map BBNotificationStyle ("SUCCESS" | "INFO" | "WARN" | "CRITICAL") onto
+// the visual variant of the toast container.
+export type ToastVariant = "success" | "info" | "warning" | "error";
+
+const toastRootVariants = cva(
+ // Base: absolutely-positioned card. Base UI Toast.Root supplies its own
+ // transform-based animation slot via CSS variables; we layer surface
+ // styling on top.
+ [
+ "absolute right-0 bottom-0",
+ "w-(--toast-width) max-w-[calc(100vw-2rem)]",
+ "rounded-md border bg-popover text-popover-foreground shadow-md",
+ "px-4 py-3 pr-10",
+ // Base UI emits these CSS vars; we use them for the stack/expand transforms.
+ "transform [transition:transform_250ms,opacity_250ms]",
+ "[transform:translateY(calc(var(--toast-swipe-movement-y,0px)+var(--toast-index)*-12px))_scale(calc(1-var(--toast-index)*0.05))]",
+ "[&[data-expanded]]:[transform:translateY(calc(var(--toast-offset-y,0px)*-1-var(--toast-index)*16px))]",
+ "[&[data-starting-style]]:opacity-0",
+ "[&[data-ending-style]]:opacity-0",
+ ].join(" "),
+ {
+ variants: {
+ variant: {
+ success: "border-success/40",
+ info: "border-info/40",
+ warning: "border-warning/40",
+ error: "border-error/40",
+ },
+ },
+ defaultVariants: { variant: "info" },
+ }
+);
+
+const iconVariants = cva("size-5 shrink-0 mt-0.5", {
+ variants: {
+ variant: {
+ success: "text-success",
+ info: "text-info",
+ warning: "text-warning",
+ error: "text-error",
+ },
+ },
+ defaultVariants: { variant: "info" },
+});
+
+const iconMap: Record<ToastVariant, typeof CheckCircle2> = {
+ success: CheckCircle2,
+ info: Info,
+ warning: AlertTriangle,
+ error: XCircle,
+};
+
+type ToastRootProps = Omit<
+ ComponentProps<typeof BaseToast.Root>,
+ "className"
+> &
+ VariantProps<typeof toastRootVariants> & {
+ className?: string;
+ showIcon?: boolean;
+ children?: ReactNode;
+ };
+
+function ToastRoot({
+ variant = "info",
+ showIcon = true,
+ className,
+ children,
+ ...props
+}: ToastRootProps) {
+ const Icon = iconMap[variant ?? "info"];
+ return (
+ <BaseToast.Root
+ {...props}
+ className={cn(toastRootVariants({ variant }), className)}
+ >
+ <div className="flex items-start gap-x-3">
+ {showIcon ? <Icon className={iconVariants({ variant })} /> : null}
+ <div className="flex min-w-0 flex-1 flex-col gap-y-1">{children}</div>
+ </div>
+ </BaseToast.Root>
+ );
+}
+
+function ToastTitle({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Title>) {
+ return (
+ <BaseToast.Title
+ {...props}
+ className={cn("text-sm font-medium leading-5", className)}
+ />
+ );
+}
+
+function ToastDescription({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Description>) {
+ return (
+ <BaseToast.Description
+ {...props}
+ className={cn(
+ "text-sm leading-5 text-muted-foreground whitespace-pre-wrap",
+ className
+ )}
+ />
+ );
+}
+
+function ToastAction({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Action>) {
+ return (
+ <BaseToast.Action
+ {...props}
+ className={cn(
+ "mt-1 inline-flex w-fit text-sm font-medium text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className
+ )}
+ />
+ );
+}
+
+function ToastClose({
+ className,
+ "aria-label": ariaLabel,
+ ...props
+}: ComponentProps<typeof BaseToast.Close>) {
+ return (
+ <BaseToast.Close
+ {...props}
+ aria-label={ariaLabel ?? "Close"}
+ className={cn(
+ "absolute right-2 top-2 inline-flex size-7 items-center justify-center rounded-sm text-muted-foreground opacity-60 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className
+ )}
+ >
+ <X className="size-4" />
+ </BaseToast.Close>
+ );
+}
+
+export { ToastRoot, ToastTitle, ToastDescription, ToastAction, ToastClose };
+```
+
+- [ ] **Step 2: Verify type-check + lint**
+
+```bash
+pnpm --dir frontend type-check
+pnpm --dir frontend fix
+```
+
+Expected: both green; `fix` may reorganize imports.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add frontend/src/react/components/ui/toast.tsx
+git commit -m "feat(react/ui): add shadcn-style wrappers around Base UI Toast parts
+
+Static primitives only; no runtime wiring yet. cva variants on
+ToastRoot map BBNotificationStyle (SUCCESS/INFO/WARN/CRITICAL) onto
+visual variants (success/info/warning/error). ToastClose has a default
+'Close' aria-label that callers can override via i18n.
+
+Follows the dialog.tsx pattern: Base UI primitive + cn() + tokens; no
+raw colors; portal/layering handled in toaster.tsx (next commit).
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>"
+```
+
+---
+
+## Task 2: Add the toast manager + window listener
+
+Module-level standalone manager. Importable from any code (React, Vue, framework-neutral). Listener registers at module-eval time.
+
+**Files:**
+- Create: `frontend/src/react/lib/toast.ts`
+- Create: `frontend/src/react/lib/toast.test.ts`
+
+- [ ] **Step 1: Write the failing unit test for the mapping function**
+
+```ts
+// frontend/src/react/lib/toast.test.ts
+import { describe, expect, test, vi, beforeEach } from "vitest";
+
+const addMock = vi.fn();
+vi.mock("@base-ui/react/toast", () => ({
+ createToastManager: () => ({ add: addMock, close: vi.fn() }),
+}));
+
+import { pushReactNotification, mapNotificationToToast } from "./toast";
+
+describe("mapNotificationToToast", () => {
+ beforeEach(() => {
+ addMock.mockReset();
+ });
+
+ test("SUCCESS maps to type=success, priority=low, timeout=6000", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: "Saved",
+ })
+ ).toMatchObject({
+ type: "success",
+ priority: "low",
+ timeout: 6000,
+ title: "Saved",
+ });
+ });
+
+ test("CRITICAL maps to type=error, priority=high, timeout=10000", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Boom",
+ })
+ ).toMatchObject({
+ type: "error",
+ priority: "high",
+ timeout: 10000,
+ });
+ });
+
+ test("WARN maps to type=warning, INFO maps to type=info", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "WARN",
+ title: "Heads up",
+ })
+ ).toMatchObject({ type: "warning" });
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "FYI",
+ })
+ ).toMatchObject({ type: "info" });
+ });
+
+ test("manualHide=true sets timeout=0 (manager treats 0 as manual)", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "T",
+ manualHide: true,
+ })
+ ).toMatchObject({ timeout: 0 });
+ });
+
+ test("description string passes through; link/linkTitle become actionProps", () => {
+ const mapped = mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "T",
+ description: "details",
+ link: "https://example.com",
+ linkTitle: "Open",
+ });
+ expect(mapped.description).toBe("details");
+ expect(mapped.actionProps).toMatchObject({
+ "aria-label": "Open",
+ onClick: expect.any(Function),
+ });
+ });
+});
+
+describe("pushReactNotification", () => {
+ beforeEach(() => addMock.mockReset());
+
+ test("calls toastManager.add with mapped options", () => {
+ pushReactNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: "Saved",
+ });
+ expect(addMock).toHaveBeenCalledTimes(1);
+ expect(addMock.mock.calls[0][0]).toMatchObject({
+ title: "Saved",
+ type: "success",
+ priority: "low",
+ timeout: 6000,
+ });
+ });
+
+ test("ignores notifications with module !== 'bytebase'", () => {
+ pushReactNotification({
+ // @ts-expect-error — test guards a runtime filter
+ module: "other",
+ style: "INFO",
+ title: "ignored",
+ });
+ expect(addMock).not.toHaveBeenCalled();
+ });
+});
+```
+
+- [ ] **Step 2: Run test to verify it fails**
+
+```bash
+pnpm --dir frontend test -- frontend/src/react/lib/toast.test.ts
+```
+
+Expected: FAIL with "Cannot find module './toast'" or similar.
+
+- [ ] **Step 3: Write `frontend/src/react/lib/toast.ts`**
+
+```ts
+import { createToastManager } from "@base-ui/react/toast";
+import type { ToastManagerAddOptions } from "@base-ui/react/toast";
+import type { NotificationCreate } from "@/types/notification";
+
+const NOTIFICATION_DURATION_MS = 6000;
+const CRITICAL_NOTIFICATION_DURATION_MS = 10000;
+
+const VUE_NOTIFICATION_EVENT = "bb.vue-notification";
+
+/**
+ * Module-level toast manager — created once, lives outside any React tree.
+ * Callers anywhere (React components, Zustand slices, plain TS modules,
+ * the Vue side via the window-event bridge below) can call .add() / .close().
+ *
+ * The <Toaster /> component subscribes via Base UI's useToastManager() hook
+ * and renders each toast.
+ */
+export const toastManager = createToastManager();
+
+type ToastOptions = ToastManagerAddOptions<Record<string, unknown>>;
+
+/**
+ * Convert the project's NotificationCreate shape into Base UI Toast options.
+ * Pure function — exported for testing.
+ */
+export function mapNotificationToToast(item: NotificationCreate): ToastOptions {
+ const type =
+ item.style === "SUCCESS"
+ ? "success"
+ : item.style === "WARN"
+ ? "warning"
+ : item.style === "CRITICAL"
+ ? "error"
+ : "info";
+ const priority: "low" | "high" = item.style === "CRITICAL" ? "high" : "low";
+ const timeout = item.manualHide
+ ? 0
+ : item.style === "CRITICAL"
+ ? CRITICAL_NOTIFICATION_DURATION_MS
+ : NOTIFICATION_DURATION_MS;
+
+ const actionProps =
+ item.link && item.linkTitle
+ ? {
+ "aria-label": item.linkTitle,
+ onClick: () => {
+ window.open(item.link, "_blank", "noopener,noreferrer");
+ },
+ children: item.linkTitle,
+ }
+ : undefined;
+
+ return {
+ title: item.title,
+ description:
+ typeof item.description === "string" ? item.description : undefined,
+ type,
+ priority,
+ timeout,
+ actionProps,
+ };
+}
+
+/**
+ * Push a notification through the React toast renderer. Safe to call from
+ * any context (component, store, plain TS module). Filters by
+ * module === "bytebase" to match the previous Vue NotificationContext.
+ */
+export function pushReactNotification(item: NotificationCreate): void {
+ if (item.module !== "bytebase") return;
+ toastManager.add(mapNotificationToToast(item));
+}
+
+// Module-eval-time listener: catch notifications originating on the Vue side
+// (Pinia notificationStore.pushNotification) and forward them to the toast
+// manager. Registered exactly once per module load; main.ts imports this
+// module during app bootstrap, before any pushNotification fires.
+if (typeof window !== "undefined") {
+ window.addEventListener(VUE_NOTIFICATION_EVENT, (event: Event) => {
+ const detail = (event as CustomEvent<NotificationCreate>).detail;
+ if (detail) pushReactNotification(detail);
+ });
+}
+```
+
+- [ ] **Step 4: Run test to verify it passes**
+
+```bash
+pnpm --dir frontend test -- frontend/src/react/lib/toast.test.ts
+```
+
+Expected: all 7 tests pass.
+
+- [ ] **Step 5: Lint**
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend type-check
+```
+
+Expected: green.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add frontend/src/react/lib/toast.ts frontend/src/react/lib/toast.test.ts
+git commit -m "feat(react/lib): add toast manager + Vue-event bridge
+
+Module-level createToastManager() (no React tree dependency) plus a
+pushReactNotification(NotificationCreate) helper that maps the existing
+project shape onto Base UI Toast options:
+
+ SUCCESS/INFO/WARN/CRITICAL -> success/info/warning/error
+ CRITICAL -> priority='high', 10s timeout
+ others -> priority='low', 6s timeout
+ manualHide=true -> timeout=0 (manual close)
+ link + linkTitle -> actionProps (opens in new tab)
+ module !== 'bytebase' -> ignored (mirrors NotificationContext filter)
+
+Listener for 'bb.vue-notification' window events is registered at module
+eval time so it's live before any pushNotification fires. <Toaster /> in
+the next commit subscribes to the manager.
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>"
+```
+
+---
+
+## Task 3: Add the `<Toaster />` component
+
+The mount component that consumes the manager and renders each toast. Portals each Toast.Root into the overlay layer for accessibility-policy consistency.
+
+**Files:**
+- Create: `frontend/src/react/components/ui/toaster.tsx`
+
+- [ ] **Step 1: Write `toaster.tsx`**
+
+```tsx
+import { Toast as BaseToast } from "@base-ui/react/toast";
+import { useTranslation } from "react-i18next";
+import {
+ ToastRoot,
+ ToastTitle,
+ ToastDescription,
+ ToastAction,
+ ToastClose,
+ type ToastVariant,
+} from "./toast";
+import { toastManager } from "@/react/lib/toast";
+import { getLayerRoot, LAYER_Z_INDEX } from "./layer";
+
+const TOAST_LIMIT = 5;
+
+// Map Base UI's type string (which we set in toast.ts) onto our visual variant.
+function variantFromType(type: string | undefined): ToastVariant {
+ if (type === "success" || type === "warning" || type === "error") {
+ return type;
+ }
+ return "info";
+}
+
+function ToastList() {
+ const { toasts } = BaseToast.useToastManager();
+ const { t } = useTranslation();
+ return (
+ <>
+ {toasts.map((toast) => (
+ <ToastRoot
+ key={toast.id}
+ toast={toast}
+ variant={variantFromType(toast.type)}
+ >
+ <ToastClose aria-label={t("common.close")} />
+ {toast.title ? <ToastTitle>{toast.title}</ToastTitle> : null}
+ {toast.description ? (
+ <ToastDescription>{toast.description}</ToastDescription>
+ ) : null}
+ {toast.actionProps ? <ToastAction {...toast.actionProps} /> : null}
+ </ToastRoot>
+ ))}
+ </>
+ );
+}
+
+/**
+ * The Toaster shell — mounted once, persistent for the app lifetime.
+ *
+ * Structure: Provider supplies the context bound to the standalone
+ * toastManager. The whole Viewport is portaled into getLayerRoot("overlay")
+ * so toasts inherit the overlay family's aria-hidden / inert behavior
+ * (e.g. session-expired surface at the 'critical' layer obscures them).
+ */
+export function Toaster() {
+ return (
+ <BaseToast.Provider toastManager={toastManager} limit={TOAST_LIMIT}>
+ <BaseToast.Portal container={getLayerRoot("overlay")}>
+ <BaseToast.Viewport
+ className="fixed bottom-4 right-4 flex w-(--toast-width) flex-col gap-2"
+ style={{
+ // Tailwind v4 reads CSS vars; expose toast width here so the
+ // toast card class can reference it. Width matches naive-ui's
+ // default.
+ ["--toast-width" as string]: "24rem",
+ zIndex: LAYER_Z_INDEX.overlay,
+ }}
+ >
+ <ToastList />
+ </BaseToast.Viewport>
+ </BaseToast.Portal>
+ </BaseToast.Provider>
+ );
+}
+```
+
+- [ ] **Step 2: Verify**
+
+```bash
+pnpm --dir frontend type-check
+pnpm --dir frontend fix
+```
+
+Expected: green.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add frontend/src/react/components/ui/toaster.tsx
+git commit -m "feat(react/ui): add Toaster shell component
+
+Renders <BaseToast.Provider> bound to the module-level toastManager,
+viewport pinned to bottom-right at the overlay layer z-index. Each toast
+portals into getLayerRoot('overlay') so the critical layer (session-
+expired surface) can obscure it via the layer policy.
+
+Title/description/action button + Close (with i18n aria-label from
+common.close). Variant is read from Base UI's type field set by
+pushReactNotification's style->type mapping.
+
+Not yet mounted anywhere — that lands in the next commit alongside the
+mountToaster wiring.
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>"
+```
+
+---
+
+## Task 4: Wire the persistent React root for the Toaster
+
+Boot a dedicated React root from `main.ts` after Vue starts. Follows the existing `mountSidebar` pattern.
+
+**Files:**
+- Create: `frontend/src/react/mountToaster.ts`
+- Modify: `frontend/index.html`
+- Modify: `frontend/src/main.ts`
+
+- [ ] **Step 1: Add the DOM hook to `index.html`**
+
+Read the current head of `frontend/index.html`, find `<div id="app"></div>`, add the toaster root after it:
+
+```html
+ <div id="app"></div>
+ <!-- React Toaster root: hosts the persistent toast renderer.
+ Visually empty; toasts portal into getLayerRoot("overlay"). -->
+ <div id="bb-toaster-root"></div>
+```
+
+- [ ] **Step 2: Write `frontend/src/react/mountToaster.ts`**
+
+```ts
+// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
+// Vite resolves the glob at build time and creates a lazy chunk for the matched module.
+const toasterLoader = import.meta.glob("./components/ui/toaster.tsx");
+
+// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
+type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
+
+let cachedDeps: ReactDeps | null = null;
+
+async function loadCoreDeps() {
+ if (cachedDeps) return cachedDeps;
+ const [
+ { createElement, StrictMode },
+ { createRoot },
+ { I18nextProvider },
+ i18nModule,
+ ] = await Promise.all([
+ import("react"),
+ import("react-dom/client"),
+ import("react-i18next"),
+ import("@/react/i18n"),
+ ]);
+ await i18nModule.i18nReady;
+ cachedDeps = {
+ createElement,
+ StrictMode,
+ createRoot,
+ I18nextProvider,
+ i18n: i18nModule.default,
+ };
+ return cachedDeps;
+}
+
+async function loadToaster() {
+ const loader = toasterLoader["./components/ui/toaster.tsx"];
+ if (!loader) throw new Error("Toaster not found");
+ const mod = (await loader()) as Record<string, unknown>;
+ return mod.Toaster as ReactDeps;
+}
+
+/**
+ * Mount the persistent <Toaster /> into the given container. Called once
+ * at app bootstrap; the root lives until page unload.
+ *
+ * Importing this file also pulls in @/react/lib/toast, which registers the
+ * `bb.vue-notification` window listener at module-eval time. Call this
+ * function before any Vue code calls pushNotification.
+ */
+export async function mountToaster(container: HTMLElement) {
+ // Side-effect import: registers the bb.vue-notification window listener.
+ await import("@/react/lib/toast");
+ const [deps, Toaster] = await Promise.all([loadCoreDeps(), loadToaster()]);
+ const tree = deps.createElement(
+ deps.StrictMode,
+ null,
+ deps.createElement(
+ deps.I18nextProvider,
+ { i18n: deps.i18n },
+ deps.createElement(Toaster)
+ )
+ );
+ const root = deps.createRoot(container);
+ root.render(tree);
+ return root;
+}
+```
+
+- [ ] **Step 3: Wire `mountToaster` into `frontend/src/main.ts`**
+
+Read `frontend/src/main.ts`, find the section where `app.mount("#app")` happens (search for the end of the async IIFE), and add the Toaster mount immediately after Vue mounts:
+
+```ts
+// ... existing imports ...
+import { mountToaster } from "./react/mountToaster";
+
+// ... existing bootstrap IIFE ...
+ app.mount("#app");
+
+ // Boot the React toaster after Vue is mounted. This also registers the
+ // bb.vue-notification window listener (side effect of importing
+ // @/react/lib/toast inside mountToaster), so any subsequent
+ // pushNotification call reaches the React renderer.
+ const toasterRoot = document.getElementById("bb-toaster-root");
+ if (toasterRoot) {
+ void mountToaster(toasterRoot);
+ }
+})();
+```
+
+The exact insertion location is right after the existing `app.mount("#app")` line. Add the `import { mountToaster }` line near the other `./react/` imports if any, otherwise alongside other module imports at the top.
+
+- [ ] **Step 4: Verify**
+
+```bash
+pnpm --dir frontend type-check
+pnpm --dir frontend fix
+pnpm --dir frontend test -- frontend/src/react/lib/toast.test.ts
+```
+
+Expected: all green.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/index.html frontend/src/react/mountToaster.ts frontend/src/main.ts
+git commit -m "feat(react): mount persistent Toaster root at app bootstrap
+
+Add <div id='bb-toaster-root'> to index.html (visually empty; toasts
+portal into the overlay layer). mountToaster() follows the existing
+mountSidebar pattern: lazy-load via import.meta.glob to keep vue-tsc
+away from .tsx, wrap with StrictMode + I18nextProvider, createRoot()
+once.
+
+Importing mountToaster pulls in @/react/lib/toast as a side effect,
+which registers the bb.vue-notification window listener at module-eval
+time. Bootstrap order: Vue app mounts -> Toaster mounts -> any
+subsequent pushNotification reaches the React renderer.
+
+Still inert: nothing emits bb.vue-notification yet. The next commit
+flips the Pinia store and tears down the Vue renderer atomically.
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>"
+```
+
+---
+
+## Task 5: Atomic switch — flip the Pinia store, drop the Vue renderer
+
+This is the single cutover commit. All-or-nothing to avoid double-rendering.
+
+**Files:**
+- Modify: `frontend/src/store/modules/notification.ts`
+- Modify: `frontend/src/react/stores/app/notification.ts`
+- Modify: `frontend/src/react/stores/app/types.ts`
+- Modify: `frontend/src/react/shell-bridge.ts`
+- Modify: `frontend/src/App.vue`
+- Modify: `frontend/src/shell-bridge.test.ts`
+- Delete: `frontend/src/NotificationContext.vue`
+
+- [ ] **Step 1: Rewrite the Pinia store to emit window events**
+
+Replace the entire contents of `frontend/src/store/modules/notification.ts`:
+
+```ts
+import { defineStore } from "pinia";
+import { v1 as uuidv1 } from "uuid";
+import type { Notification, NotificationCreate } from "@/types";
+
+const VUE_NOTIFICATION_EVENT = "bb.vue-notification";
+
+/**
+ * Notification store — kept as a Pinia store for backward compatibility
+ * with the 17 Vue-side pushNotification() callers. Internally it no longer
+ * queues anything; instead each push dispatches a window CustomEvent that
+ * the React toast manager (frontend/src/react/lib/toast.ts) catches and
+ * renders. Vue retains no renderer.
+ *
+ * This store dies entirely in Phase B3 (Pinia -> Zustand).
+ */
+export const useNotificationStore = defineStore("notification", {
+ state: () => ({}),
+ actions: {
+ pushNotification(notificationCreate: NotificationCreate) {
+ const notification: Notification = {
+ id: uuidv1(),
+ createdTs: Date.now() / 1000,
+ ...notificationCreate,
+ };
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(
+ new CustomEvent<Notification>(VUE_NOTIFICATION_EVENT, {
+ detail: notification,
+ })
+ );
+ }
+ },
+ },
+});
+
+export const pushNotification = (notificationCreate: NotificationCreate) => {
+ useNotificationStore().pushNotification(notificationCreate);
+};
+```
+
+This drops `appendNotification`, `removeNotification`, `tryPopNotification`, `notificationByModule`, and `findNotification` — none have any external consumer after this commit. Vue callers continue to use `pushNotification` unchanged.
+
+- [ ] **Step 2: Swap React notify slice to call toastManager directly**
+
+Replace `frontend/src/react/stores/app/notification.ts`:
+
+```ts
+import { pushReactNotification } from "@/react/lib/toast";
+import type { AppSliceCreator, NotificationSlice } from "./types";
+
+export const createNotificationSlice: AppSliceCreator<NotificationSlice> = () => ({
+ notify: (notification) => {
+ pushReactNotification(notification);
+ },
+});
+```
+
+The `notifications` array state is gone — no consumer reads it.
+
+- [ ] **Step 3: Update the slice type**
+
+Read `frontend/src/react/stores/app/types.ts`, find the `NotificationSlice` type:
+
+```ts
+export type NotificationSlice = {
+ notifications: NotificationCreate[];
+ notify: (notification: NotificationCreate) => void;
+};
+```
+
+Replace with:
+
+```ts
+export type NotificationSlice = {
+ notify: (notification: NotificationCreate) => void;
+};
+```
+
+- [ ] **Step 4: Strip the obsolete bridge from `react/shell-bridge.ts`**
+
+Read `frontend/src/react/shell-bridge.ts` and replace its contents:
+
+```ts
+export const ReactShellBridgeEvent = {
+ localeChange: "bb.react-locale-change",
+ quickstartReset: "bb.react-quickstart-reset",
+} as const;
+
+export type ReactShellBridgeEventName =
+ (typeof ReactShellBridgeEvent)[keyof typeof ReactShellBridgeEvent];
+
+export type ReactQuickstartResetDetail = {
+ keys: string[];
+};
+
+export function emitReactLocaleChange(lang: string) {
+ window.dispatchEvent(
+ new CustomEvent(ReactShellBridgeEvent.localeChange, { detail: lang })
+ );
+}
+
+export function emitReactQuickstartReset(detail: ReactQuickstartResetDetail) {
+ window.dispatchEvent(
+ new CustomEvent(ReactShellBridgeEvent.quickstartReset, { detail })
+ );
+}
+```
+
+This removes the `notification` event key and `emitReactNotification`. Notification flow now goes Vue→`bb.vue-notification`→`toastManager` directly; no React-to-Vue notification bridge.
+
+- [ ] **Step 5: Unwrap `App.vue`**
+
+Read `frontend/src/App.vue`, find the notification wrappers (lines 9–20 in the current file):
+
+```vue
+ <NNotificationProvider
+ ...
+ >
+ <OverlayStackManager>
+ <NotificationContext>
+ ...
+ </NotificationContext>
+ </OverlayStackManager>
+ </NNotificationProvider>
+```
+
+Replace with just the inner content (keep `OverlayStackManager`):
+
+```vue
+ <OverlayStackManager>
+ ...
+ </OverlayStackManager>
+```
+
+Also remove from the script imports section:
+
+```ts
+import { NConfigProvider, NNotificationProvider } from "naive-ui";
+// becomes:
+import { NConfigProvider } from "naive-ui";
+
+// and delete:
+import NotificationContext from "./NotificationContext.vue";
+```
+
+If `NNotificationProvider` had any prop attributes (placement, max, etc.) on the opening tag in App.vue, those go away too — Base UI Toast handles positioning at the React layer.
+
+- [ ] **Step 6: Update test mocks**
+
+Read `frontend/src/shell-bridge.test.ts`. Find the block mocking `NotificationContext.vue`:
+
+```ts
+vi.mock("./components/misc/OverlayStackManager.vue", async () => { ... });
+```
+
+And the `useNotificationStore` mock around line 22–30:
+
+```ts
+const mocks = vi.hoisted(() => ({
+ // ...
+ tryPopNotification: vi.fn(),
+ // ...
+}));
+
+// later:
+useNotificationStore: () => ({
+ // ...
+ tryPopNotification: mocks.tryPopNotification,
+ // ...
+}),
+```
+
+Remove `tryPopNotification` from `mocks` and from the `useNotificationStore` mock object. If the test imports `NotificationContext.vue` directly, drop that mock entry.
+
+Then read `frontend/src/layouts/layout-bridge.test.ts` and check for `NotificationContext` or `tryPopNotification` mock entries — remove if present.
+
+Final pass:
+
+```bash
+grep -rn "NotificationContext\|tryPopNotification" frontend/src
+```
+
+Expected: zero matches outside this commit's deletions.
+
+- [ ] **Step 7: Delete `NotificationContext.vue`**
+
+```bash
+git rm frontend/src/NotificationContext.vue
+```
+
+- [ ] **Step 8: Verify all gates**
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+pnpm --dir frontend check
+```
+
+Expected: all green. The full test suite must still pass (~1871 tests). The `check` script runs eslint + biome + react-i18n + react-layering + locale-sort.
+
+- [ ] **Step 9: Manual smoke (see full checklist in spec §"Manual smoke checklist")**
+
+Run dev server and exercise:
+
+```bash
+pnpm --dir frontend dev
+```
+
+Quick subset:
+- Trigger a SUCCESS toast (save anything) → green, auto-dismisses ~6s
+- Trigger a CRITICAL toast (force an error, e.g. SQL execution error) → red, ~10s
+- Trigger a toast with `manualHide: true` → stays until close button click
+- Open a Dialog, then trigger a toast → toast appears above the dialog backdrop
+- Trigger session-expired (clear auth cookie + reload) → critical layer obscures any toasts
+
+Full checklist is in the spec. Do not commit until you've smoked at least the four above.
+
+- [ ] **Step 10: Commit**
+
+```bash
+git add -A frontend
+git commit -m "refactor(notification): React Base UI Toast replaces NotificationContext.vue
+
+Atomic cutover from Vue/Naive UI notifications to React/Base UI Toast.
+After this commit:
+- The Pinia notificationStore is a thin pass-through that emits
+ CustomEvent('bb.vue-notification') for each pushNotification. No
+ internal queue; no renderer.
+- React @/react/stores/app/notification's notify() calls toastManager.add()
+ directly through pushReactNotification (no longer emits a window event).
+- react/shell-bridge.ts loses the bb.react-notification event +
+ emitReactNotification; bridge direction is now Vue -> React only.
+- App.vue drops <NNotificationProvider> + <NotificationContext> wrappers.
+- NotificationContext.vue + its test mocks deleted.
+
+149 callers of pushNotification (17 Vue, 132 React) keep their API. Vue
+callers route via the window event; React callers route via the slice ->
+manager direct path. End state: one renderer (React).
+
+Phase B2 dependencies retired: -1 .vue file (NotificationContext), -1
+Naive UI provider mount. Pinia store stays until Phase B3.
+
+Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>"
+```
+
+---
+
+## Task 6: Pre-PR validation
+
+- [ ] **Step 1: Walk the pre-PR checklist**
+
+Open `docs/pre-pr-checklist.md` and verify every item. In particular:
+
+- No `frontend/src/NotificationContext.vue` left behind: `find frontend/src -name "NotificationContext.vue"` — should be empty.
+- No leftover `tryPopNotification` calls: `grep -rn "tryPopNotification" frontend/src` — empty.
+- No leftover `emitReactNotification`: `grep -rn "emitReactNotification" frontend/src` — empty.
+- No leftover `bb.react-notification`: `grep -rn "bb.react-notification" frontend/src` — empty.
+- No raw `z-index` introduced anywhere except `LAYER_Z_INDEX.overlay` in `toaster.tsx`.
+
+- [ ] **Step 2: Push and open PR**
+
+```bash
+git push -u origin chore/frontend/notification-react-migration
+gh pr create --title "refactor(notification): migrate to React Base UI Toast" --body "$(cat <<'EOF'
+## Summary
+
+Replaces Vue's NotificationContext.vue + Naive UI NNotificationProvider with a React renderer built on Base UI Toast. React becomes the sole renderer; Vue's pushNotification API stays for backwards compatibility with its 17 callers, routing through a window event into the React side.
+
+- 5 commits, ~3 files added / ~6 modified / 1 deleted
+- Pinia notificationStore retained as a thin pass-through (Phase B3 work)
+- App.vue still Vue; only the notification wrapper is stripped
+
+## Test plan
+
+- [x] `pnpm --dir frontend type-check`
+- [x] `pnpm --dir frontend test`
+- [x] `pnpm --dir frontend check`
+- [ ] Manual smoke (see spec §"Manual smoke checklist"):
+ - [ ] SUCCESS / INFO / WARN / CRITICAL variants
+ - [ ] manualHide
+ - [ ] link + linkTitle action button
+ - [ ] toast above dialogs / sheets
+ - [ ] critical layer (session-expired) obscures toasts
+ - [ ] auth middleware error path still produces a toast
+
+Companion docs:
+- Spec: `docs/plans/2026-05-13-notification-react-migration-design.md`
+- Plan: `docs/plans/2026-05-13-notification-react-migration-plan.md`
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+EOF
+)"
+```
+
+---
+
+## Out-of-scope follow-ups
+
+- **Phase B3**: Pinia `notificationStore` → Zustand. After that, the `bb.vue-notification` window event can collapse into a direct function call.
+- **Phase B2**: When `App.vue` migrates to React, the `<OverlayStackManager>` wrapper goes too; the Toaster's persistent root can fold into the main React shell root.
+- **Toast API extensions** (action toasts that don't just open links, promise toasts via Base UI's `toastManager.promise()`, sticky toasts with custom dismiss buttons). Not needed for parity.
+
+---
+
+## Self-review notes (inline)
+
+**Spec coverage check:**
+- §"Architecture" → Tasks 2 (manager) + 3 (Toaster) + 5 (Pinia rewrite) cover the diagram end-to-end. ✓
+- §"File layout / Created" → Task 1 (toast.tsx), Task 2 (toast.ts), Task 3 (toaster.tsx), Task 4 (mountToaster.ts). ✓
+- §"File layout / Modified" → Task 5 covers notification.ts (slice), notification.ts (Pinia), shell-bridge.ts, App.vue, main.ts (via Task 4). ✓
+- §"API parity" → mapping function tested in Task 2 covers SUCCESS/INFO/WARN/CRITICAL, manualHide, link/linkTitle. ✓
+- §"Accessibility" → `priority` mapping in Task 2; `aria-label={t("common.close")}` in Task 3. ✓
+- §"Layering" → `Toast.Portal container={getLayerRoot("overlay")}` in Task 3; `LAYER_Z_INDEX.overlay` on viewport. ✓
+- §"i18n" → `common.close` reused; no new keys. ✓
+- §"Risks" #1 (listener order) → Task 2 module-eval-time listener registration; Task 4 mounts after Vue. ✓
+- §"Risks" #2 (duplicate toasts) → Task 5 is atomic. ✓
+- §"Risks" #3 (function-typed description) → grep audit found zero callers; mapping types description as string only. ✓
+- §"Risks" #4 (test mocks) → Task 5 Step 6. ✓
+- §"Risks" #5 (Pinia consumers of tryPopNotification) → Task 5 Step 1 drops it; Step 6 verifies grep is empty. ✓
+
+**Type consistency check:** `pushReactNotification` signature and `mapNotificationToToast` return type are used consistently across Tasks 2, 3, 5. `NotificationCreate` shape comes from the existing `@/types/notification` and is not modified.
+
+**Placeholder scan:** No TBDs. Every code step has full code. Every command has an expected outcome.
+
+**Estimated total:** 5 logical commits (branch setup + Tasks 1–5) plus Task 6 (push + PR). Roughly 1 day of focused work.
diff --git a/frontend/index.html b/frontend/index.html
index b572f3ead8..f9ef082687 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -18,6 +18,9 @@
></div>
<div id="app"></div>
+ <!-- React Toaster root: hosts the persistent toast renderer.
+ Visually empty; toasts portal into getLayerRoot("overlay"). -->
+ <div id="bb-toaster-root"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
index 8cd9572880..8aecafded8 100644
--- a/frontend/src/App.vue
+++ b/frontend/src/App.vue
@@ -6,25 +6,18 @@
>
<ReactPageMount page="Watermark" container-class="contents" />
- <NNotificationProvider
- :max="MAX_NOTIFICATION_DISPLAY_COUNT"
- placement="bottom-right"
- >
- <OverlayStackManager>
- <NotificationContext>
- <AuthContext>
- <router-view />
- </AuthContext>
- </NotificationContext>
- </OverlayStackManager>
- </NNotificationProvider>
+ <OverlayStackManager>
+ <AuthContext>
+ <router-view />
+ </AuthContext>
+ </OverlayStackManager>
</NConfigProvider>
</template>
<script lang="ts" setup>
import { Code, ConnectError } from "@connectrpc/connect";
import { cloneDeep, isEqual } from "lodash-es";
-import { NConfigProvider, NNotificationProvider } from "naive-ui";
+import { NConfigProvider } from "naive-ui";
import {
onErrorCaptured,
onMounted,
@@ -38,7 +31,6 @@ import { dateLang, generalLang, themeOverrides } from "../naive-ui.config";
import AuthContext from "./AuthContext.vue";
import OverlayStackManager from "./components/misc/OverlayStackManager.vue";
import { overrideAppProfile } from "./customAppProfile";
-import NotificationContext from "./NotificationContext.vue";
import { locale, t } from "./plugins/i18n";
import {
type ReactQuickstartResetDetail,
@@ -47,9 +39,6 @@ import {
import { useNotificationStore, useUIStateStore } from "./store";
import { isDev, setDocumentTitle } from "./utils";
-// Show at most 3 notifications to prevent excessive notification when shit hits the fan.
-const MAX_NOTIFICATION_DISPLAY_COUNT = 3;
-
const route = useRoute();
const router = useRouter();
const notificationStore = useNotificationStore();
diff --git a/frontend/src/NotificationContext.vue b/frontend/src/NotificationContext.vue
deleted file mode 100644
index ba1432d671..0000000000
--- a/frontend/src/NotificationContext.vue
+++ /dev/null
@@ -1,111 +0,0 @@
-<template>
- <slot></slot>
-</template>
-
-<script setup lang="ts">
-import { useNotification } from "naive-ui";
-import { h, onMounted, onUnmounted, watchEffect } from "vue";
-import { ReactShellBridgeEvent } from "@/react/shell-bridge";
-import { useNotificationStore } from "@/store";
-import type { BBNotificationStyle, NotificationCreate } from "@/types";
-
-const NOTIFICATION_DURATION = 6000;
-const CRITICAL_NOTIFICATION_DURATION = 10000;
-
-const notificationStore = useNotificationStore();
-const notification = useNotification();
-
-const getNotificationType = (style: BBNotificationStyle) => {
- switch (style) {
- case "CRITICAL":
- return "error";
- case "INFO":
- return "info";
- case "WARN":
- return "warning";
- default:
- return "success";
- }
-};
-
-const showNotification = (item: NotificationCreate) => {
- if (!item) {
- return;
- }
-
- const duration = item.manualHide
- ? undefined
- : item.style === "CRITICAL"
- ? CRITICAL_NOTIFICATION_DURATION
- : NOTIFICATION_DURATION;
-
- notification.create({
- type: getNotificationType(item.style),
- keepAliveOnHover: true,
- duration,
- title: () =>
- h(
- "div",
- {
- class: "text-sm font-medium text-gray-900 whitespace-pre-wrap mt-1",
- },
- item.title
- ),
- content:
- typeof item.description !== "undefined"
- ? () => {
- if (typeof item.description === "function") {
- return item.description();
- }
- if (typeof item.description === "string") {
- return h(
- "div",
- { class: "text-sm text-gray-500 whitespace-pre-wrap" },
- item.description
- );
- }
- }
- : undefined,
- meta:
- item.link && item.linkTitle
- ? () => {
- return h(
- "a",
- { href: item.link, class: "normal-link", target: "_blank" },
- item.linkTitle
- );
- }
- : undefined,
- });
-};
-
-const watchNotification = () => {
- const item = notificationStore.tryPopNotification({
- module: "bytebase",
- });
- if (item) {
- showNotification(item);
- }
-};
-
-const handleReactNotification = (event: Event) => {
- const item = (event as CustomEvent<NotificationCreate>).detail;
- if (item?.module === "bytebase") {
- showNotification(item);
- }
-};
-
-watchEffect(watchNotification);
-onMounted(() => {
- window.addEventListener(
- ReactShellBridgeEvent.notification,
- handleReactNotification
- );
-});
-onUnmounted(() => {
- window.removeEventListener(
- ReactShellBridgeEvent.notification,
- handleReactNotification
- );
-});
-</script>
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index e6d40c7b23..dcee965d68 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -10,6 +10,10 @@ import highlight from "./plugins/highlight";
import i18n from "./plugins/i18n";
import NaiveUI from "./plugins/naive-ui";
import "./polyfill";
+// Side-effect: registers the bb.vue-notification window listener and
+// constructs the toastManager singleton. Must load before any auth/error
+// interceptor can fire pushNotification during bootstrap RPCs.
+import "./react/lib/toast";
import { router } from "./router";
import {
pinia,
@@ -60,4 +64,14 @@ migrateStorageKeys();
app.use(router).use(highlight).use(i18n).use(NaiveUI);
app.mount("#app");
+
+ // Boot the React toaster after Vue is mounted. Importing mountToaster
+ // pulls in @/react/lib/toast as a side effect, which registers the
+ // bb.vue-notification window listener at module-eval time. Any
+ // subsequent pushNotification reaches the React renderer.
+ const toasterRoot = document.getElementById("bb-toaster-root");
+ if (toasterRoot) {
+ const { mountToaster } = await import("./react/mountToaster");
+ void mountToaster(toasterRoot);
+ }
})();
diff --git a/frontend/src/react/components/ui/toast.tsx b/frontend/src/react/components/ui/toast.tsx
new file mode 100644
index 0000000000..0d6aed6566
--- /dev/null
+++ b/frontend/src/react/components/ui/toast.tsx
@@ -0,0 +1,135 @@
+import { Toast as BaseToast } from "@base-ui/react/toast";
+import { cva } from "class-variance-authority";
+import { AlertTriangle, CheckCircle2, Info, X, XCircle } from "lucide-react";
+import type { ComponentProps, ReactNode } from "react";
+import { cn } from "@/react/lib/utils";
+
+// Map BBNotificationStyle ("SUCCESS" | "INFO" | "WARN" | "CRITICAL") onto
+// the visual variant of the toast container.
+export type ToastVariant = "success" | "info" | "warning" | "error";
+
+// Toast card: neutral border (variant is signalled by the icon color, matching
+// sonner / react-hot-toast / shadcn-default — a full colored border is visual
+// noise when the icon already carries the type signal).
+const toastRoot = [
+ "absolute right-0 bottom-0",
+ "w-(--toast-width) max-w-[calc(100vw-2rem)]",
+ "rounded-md border bg-popover text-popover-foreground shadow-md",
+ "px-4 py-3 pr-10",
+ // Base UI emits these CSS vars; we use them for the stack/expand transforms.
+ "transform [transition:transform_250ms,opacity_250ms]",
+ "[transform:translateY(calc(var(--toast-swipe-movement-y,0px)+var(--toast-index)*-12px))_scale(calc(1-var(--toast-index)*0.05))]",
+ "[&[data-expanded]]:[transform:translateY(calc(var(--toast-offset-y,0px)*-1-var(--toast-index)*16px))]",
+ "[&[data-starting-style]]:opacity-0",
+ "[&[data-ending-style]]:opacity-0",
+].join(" ");
+
+const iconVariants = cva("size-5 shrink-0 mt-0.5", {
+ variants: {
+ variant: {
+ success: "text-success",
+ info: "text-info",
+ warning: "text-warning",
+ error: "text-error",
+ },
+ },
+ defaultVariants: { variant: "info" },
+});
+
+const iconMap: Record<ToastVariant, typeof CheckCircle2> = {
+ success: CheckCircle2,
+ info: Info,
+ warning: AlertTriangle,
+ error: XCircle,
+};
+
+type ToastRootProps = Omit<
+ ComponentProps<typeof BaseToast.Root>,
+ "className"
+> & {
+ variant?: ToastVariant;
+ className?: string;
+ showIcon?: boolean;
+ children?: ReactNode;
+};
+
+function ToastRoot({
+ variant = "info",
+ showIcon = true,
+ className,
+ children,
+ ...props
+}: ToastRootProps) {
+ const Icon = iconMap[variant];
+ return (
+ <BaseToast.Root {...props} className={cn(toastRoot, className)}>
+ <div className="flex items-start gap-x-3">
+ {showIcon ? <Icon className={iconVariants({ variant })} /> : null}
+ <div className="flex min-w-0 flex-1 flex-col gap-y-1">{children}</div>
+ </div>
+ </BaseToast.Root>
+ );
+}
+
+function ToastTitle({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Title>) {
+ return (
+ <BaseToast.Title
+ {...props}
+ className={cn("text-sm font-medium leading-5", className)}
+ />
+ );
+}
+
+function ToastDescription({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Description>) {
+ return (
+ <BaseToast.Description
+ {...props}
+ className={cn(
+ "text-sm leading-5 text-muted-foreground whitespace-pre-wrap",
+ className
+ )}
+ />
+ );
+}
+
+function ToastAction({
+ className,
+ ...props
+}: ComponentProps<typeof BaseToast.Action>) {
+ return (
+ <BaseToast.Action
+ {...props}
+ className={cn(
+ "mt-1 inline-flex w-fit text-sm font-medium text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className
+ )}
+ />
+ );
+}
+
+function ToastClose({
+ className,
+ "aria-label": ariaLabel,
+ ...props
+}: ComponentProps<typeof BaseToast.Close>) {
+ return (
+ <BaseToast.Close
+ {...props}
+ aria-label={ariaLabel ?? "Close"}
+ className={cn(
+ "absolute right-2 top-2 inline-flex size-7 items-center justify-center rounded-sm text-muted-foreground opacity-60 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className
+ )}
+ >
+ <X className="size-4" />
+ </BaseToast.Close>
+ );
+}
+
+export { ToastAction, ToastClose, ToastDescription, ToastRoot, ToastTitle };
diff --git a/frontend/src/react/components/ui/toaster.tsx b/frontend/src/react/components/ui/toaster.tsx
new file mode 100644
index 0000000000..c36e485635
--- /dev/null
+++ b/frontend/src/react/components/ui/toaster.tsx
@@ -0,0 +1,74 @@
+import { Toast as BaseToast } from "@base-ui/react/toast";
+import { useTranslation } from "react-i18next";
+import { toastManager } from "@/react/lib/toast";
+import { getLayerRoot, LAYER_Z_INDEX } from "./layer";
+import {
+ ToastAction,
+ ToastClose,
+ ToastDescription,
+ ToastRoot,
+ ToastTitle,
+ type ToastVariant,
+} from "./toast";
+
+const TOAST_LIMIT = 5;
+
+// Map Base UI's type string (which we set in toast.ts) onto our visual variant.
+function variantFromType(type: string | undefined): ToastVariant {
+ if (type === "success" || type === "warning" || type === "error") {
+ return type;
+ }
+ return "info";
+}
+
+function ToastList() {
+ const { toasts } = BaseToast.useToastManager();
+ const { t } = useTranslation();
+ return (
+ <>
+ {toasts.map((toast) => (
+ <ToastRoot
+ key={toast.id}
+ toast={toast}
+ variant={variantFromType(toast.type)}
+ >
+ <ToastClose aria-label={t("common.close")} />
+ {toast.title ? <ToastTitle>{toast.title}</ToastTitle> : null}
+ {toast.description ? (
+ <ToastDescription>{toast.description}</ToastDescription>
+ ) : null}
+ {toast.actionProps ? <ToastAction {...toast.actionProps} /> : null}
+ </ToastRoot>
+ ))}
+ </>
+ );
+}
+
+/**
+ * The Toaster shell — mounted once, persistent for the app lifetime.
+ *
+ * Structure: Provider supplies the context bound to the standalone
+ * toastManager. The whole Viewport is portaled into getLayerRoot("overlay")
+ * so toasts inherit the overlay family's aria-hidden / inert behavior
+ * (e.g. session-expired surface at the 'critical' layer obscures them).
+ */
+export function Toaster() {
+ return (
+ <BaseToast.Provider toastManager={toastManager} limit={TOAST_LIMIT}>
+ <BaseToast.Portal container={getLayerRoot("overlay")}>
+ <BaseToast.Viewport
+ className="fixed bottom-4 right-4 flex w-(--toast-width) flex-col gap-2"
+ style={{
+ // Tailwind v4 reads CSS vars; expose toast width here so the
+ // toast card class can reference it. Width matches naive-ui's
+ // default.
+ ["--toast-width" as string]: "24rem",
+ zIndex: LAYER_Z_INDEX.overlay,
+ }}
+ >
+ <ToastList />
+ </BaseToast.Viewport>
+ </BaseToast.Portal>
+ </BaseToast.Provider>
+ );
+}
diff --git a/frontend/src/react/lib/toast.test.ts b/frontend/src/react/lib/toast.test.ts
new file mode 100644
index 0000000000..352ca9a430
--- /dev/null
+++ b/frontend/src/react/lib/toast.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const { addMock } = vi.hoisted(() => ({ addMock: vi.fn() }));
+vi.mock("@base-ui/react/toast", () => ({
+ Toast: {
+ createToastManager: () => ({ add: addMock, close: vi.fn() }),
+ },
+}));
+
+import { mapNotificationToToast, pushReactNotification } from "./toast";
+
+describe("mapNotificationToToast", () => {
+ test("SUCCESS maps to type=success, priority=low, timeout=6000", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: "Saved",
+ })
+ ).toMatchObject({
+ type: "success",
+ priority: "low",
+ timeout: 6000,
+ title: "Saved",
+ });
+ });
+
+ test("CRITICAL maps to type=error, priority=high, timeout=10000", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Boom",
+ })
+ ).toMatchObject({
+ type: "error",
+ priority: "high",
+ timeout: 10000,
+ });
+ });
+
+ test("WARN maps to type=warning, INFO maps to type=info", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "WARN",
+ title: "Heads up",
+ })
+ ).toMatchObject({ type: "warning" });
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "FYI",
+ })
+ ).toMatchObject({ type: "info" });
+ });
+
+ test("manualHide=true sets timeout=0 (manager treats 0 as manual)", () => {
+ expect(
+ mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "T",
+ manualHide: true,
+ })
+ ).toMatchObject({ timeout: 0 });
+ });
+
+ test("description string passes through; link/linkTitle become actionProps", () => {
+ const mapped = mapNotificationToToast({
+ module: "bytebase",
+ style: "INFO",
+ title: "T",
+ description: "details",
+ link: "https://example.com",
+ linkTitle: "Open",
+ });
+ expect(mapped.description).toBe("details");
+ expect(mapped.actionProps).toMatchObject({
+ "aria-label": "Open",
+ onClick: expect.any(Function),
+ });
+ });
+});
+
+describe("pushReactNotification", () => {
+ beforeEach(() => addMock.mockReset());
+
+ test("calls toastManager.add with mapped options", () => {
+ pushReactNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: "Saved",
+ });
+ expect(addMock).toHaveBeenCalledTimes(1);
+ expect(addMock.mock.calls[0][0]).toMatchObject({
+ title: "Saved",
+ type: "success",
+ priority: "low",
+ timeout: 6000,
+ });
+ });
+
+ test("ignores notifications with module !== 'bytebase'", () => {
+ pushReactNotification({
+ module: "other",
+ style: "INFO",
+ title: "ignored",
+ });
+ expect(addMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/react/lib/toast.ts b/frontend/src/react/lib/toast.ts
new file mode 100644
index 0000000000..8cc6f67c1e
--- /dev/null
+++ b/frontend/src/react/lib/toast.ts
@@ -0,0 +1,79 @@
+import {
+ Toast as BaseToast,
+ type ToastManagerAddOptions,
+} from "@base-ui/react/toast";
+import { VueShellBridgeEvent } from "@/react/shell-bridge";
+import type { BBNotificationStyle, NotificationCreate } from "@/types";
+
+const NOTIFICATION_DURATION_MS = 6000;
+const CRITICAL_NOTIFICATION_DURATION_MS = 10000;
+
+const STYLE_TO_TYPE: Record<
+ BBNotificationStyle,
+ "success" | "info" | "warning" | "error"
+> = {
+ SUCCESS: "success",
+ INFO: "info",
+ WARN: "warning",
+ CRITICAL: "error",
+};
+
+export const toastManager = BaseToast.createToastManager();
+
+type ToastOptions = ToastManagerAddOptions<Record<string, unknown>>;
+
+export function mapNotificationToToast(item: NotificationCreate): ToastOptions {
+ const type = STYLE_TO_TYPE[item.style];
+ const priority: "low" | "high" = item.style === "CRITICAL" ? "high" : "low";
+ const timeout = item.manualHide
+ ? 0
+ : item.style === "CRITICAL"
+ ? CRITICAL_NOTIFICATION_DURATION_MS
+ : NOTIFICATION_DURATION_MS;
+
+ const actionProps =
+ item.link && item.linkTitle
+ ? {
+ "aria-label": item.linkTitle,
+ onClick: () => {
+ window.open(item.link, "_blank", "noopener,noreferrer");
+ },
+ children: item.linkTitle,
+ }
+ : undefined;
+
+ return {
+ title: item.title,
+ description:
+ typeof item.description === "string" ? item.description : undefined,
+ type,
+ priority,
+ timeout,
+ actionProps,
+ };
+}
+
+// Filter mirrors the previous Vue NotificationContext: only the "bytebase"
+// module renders; other modules (e.g. agent) own their own UI surface.
+export function pushReactNotification(item: NotificationCreate): void {
+ if (item.module !== "bytebase") return;
+ toastManager.add(mapNotificationToToast(item));
+}
+
+// Bridge from the Vue side: pushNotification() in the Pinia store dispatches
+// a window CustomEvent. Register at module-eval so events fired during app
+// bootstrap (e.g. auth/error interceptors before <Toaster /> mounts) are
+// caught and queued in toastManager; the Provider drains the queue on mount.
+// main.ts imports this module synchronously to make that ordering reliable.
+if (typeof window !== "undefined") {
+ const handler = (event: Event) => {
+ const detail = (event as CustomEvent<NotificationCreate>).detail;
+ if (detail) pushReactNotification(detail);
+ };
+ window.addEventListener(VueShellBridgeEvent.notification, handler);
+ if (import.meta.hot) {
+ import.meta.hot.dispose(() => {
+ window.removeEventListener(VueShellBridgeEvent.notification, handler);
+ });
+ }
+}
diff --git a/frontend/src/react/mountToaster.ts b/frontend/src/react/mountToaster.ts
new file mode 100644
index 0000000000..c32caa473f
--- /dev/null
+++ b/frontend/src/react/mountToaster.ts
@@ -0,0 +1,62 @@
+// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
+// Vite resolves the glob at build time and creates a lazy chunk for the matched module.
+const toasterLoader = import.meta.glob("./components/ui/toaster.tsx");
+
+// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
+type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
+
+let cachedDeps: ReactDeps | null = null;
+
+async function loadCoreDeps() {
+ if (cachedDeps) return cachedDeps;
+ const [
+ { createElement, StrictMode },
+ { createRoot },
+ { I18nextProvider },
+ i18nModule,
+ ] = await Promise.all([
+ import("react"),
+ import("react-dom/client"),
+ import("react-i18next"),
+ import("@/react/i18n"),
+ ]);
+ await i18nModule.i18nReady;
+ cachedDeps = {
+ createElement,
+ StrictMode,
+ createRoot,
+ I18nextProvider,
+ i18n: i18nModule.default,
+ };
+ return cachedDeps;
+}
+
+async function loadToaster() {
+ const loader = toasterLoader["./components/ui/toaster.tsx"];
+ if (!loader) throw new Error("Toaster not found");
+ const mod = (await loader()) as Record<string, unknown>;
+ return mod.Toaster as ReactDeps;
+}
+
+/**
+ * Mount the persistent <Toaster /> into the given container. Called once
+ * at app bootstrap; the root lives until page unload. The bb.vue-notification
+ * listener is already registered (main.ts side-effect-imports
+ * @/react/lib/toast); this function only attaches the Provider so queued
+ * toasts can render.
+ */
+export async function mountToaster(container: HTMLElement) {
+ const [deps, Toaster] = await Promise.all([loadCoreDeps(), loadToaster()]);
+ const tree = deps.createElement(
+ deps.StrictMode,
+ null,
+ deps.createElement(
+ deps.I18nextProvider,
+ { i18n: deps.i18n },
+ deps.createElement(Toaster)
+ )
+ );
+ const root = deps.createRoot(container);
+ root.render(tree);
+ return root;
+}
diff --git a/frontend/src/react/shell-bridge.ts b/frontend/src/react/shell-bridge.ts
index e339006c67..e32d0bf958 100644
--- a/frontend/src/react/shell-bridge.ts
+++ b/frontend/src/react/shell-bridge.ts
@@ -1,11 +1,12 @@
-import type { NotificationCreate } from "@/types/notification";
-
export const ReactShellBridgeEvent = {
localeChange: "bb.react-locale-change",
- notification: "bb.react-notification",
quickstartReset: "bb.react-quickstart-reset",
} as const;
+export const VueShellBridgeEvent = {
+ notification: "bb.vue-notification",
+} as const;
+
export type ReactShellBridgeEventName =
(typeof ReactShellBridgeEvent)[keyof typeof ReactShellBridgeEvent];
@@ -19,14 +20,6 @@ export function emitReactLocaleChange(lang: string) {
);
}
-export function emitReactNotification(notification: NotificationCreate) {
- window.dispatchEvent(
- new CustomEvent(ReactShellBridgeEvent.notification, {
- detail: notification,
- })
- );
-}
-
export function emitReactQuickstartReset(detail: ReactQuickstartResetDetail) {
window.dispatchEvent(
new CustomEvent(ReactShellBridgeEvent.quickstartReset, { detail })
diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.ts
index 54a3e887f0..ab992d2628 100644
--- a/frontend/src/react/stores/app/index.test.ts
+++ b/frontend/src/react/stores/app/index.test.ts
@@ -566,10 +566,10 @@ describe("useAppStore", () => {
expect(store.getState().instancesByName[instance.name]).toBe(instance);
});
- test("dispatches notification events for the Vue shell bridge", () => {
+ test("notify() routes to the React toast manager", async () => {
+ const { toastManager } = await import("@/react/lib/toast");
+ const addSpy = vi.spyOn(toastManager, "add");
const store = createAppStore();
- const listener = vi.fn();
- window.addEventListener(ReactShellBridgeEvent.notification, listener);
store.getState().notify({
module: "bytebase",
@@ -577,9 +577,12 @@ describe("useAppStore", () => {
title: "Saved",
});
- expect(store.getState().notifications).toHaveLength(1);
- expect(listener).toHaveBeenCalledTimes(1);
- window.removeEventListener(ReactShellBridgeEvent.notification, listener);
+ expect(addSpy).toHaveBeenCalledTimes(1);
+ expect(addSpy.mock.calls[0][0]).toMatchObject({
+ title: "Saved",
+ type: "success",
+ });
+ addSpy.mockRestore();
});
test("keeps user-scoped preferences in localStorage", () => {
diff --git a/frontend/src/react/stores/app/notification.ts b/frontend/src/react/stores/app/notification.ts
index 049fae2bd1..81801667a1 100644
--- a/frontend/src/react/stores/app/notification.ts
+++ b/frontend/src/react/stores/app/notification.ts
@@ -1,15 +1,10 @@
-import { emitReactNotification } from "@/react/shell-bridge";
+import { pushReactNotification } from "@/react/lib/toast";
import type { AppSliceCreator, NotificationSlice } from "./types";
-export const createNotificationSlice: AppSliceCreator<NotificationSlice> = (
- set
-) => ({
- notifications: [],
-
+export const createNotificationSlice: AppSliceCreator<
+ NotificationSlice
+> = () => ({
notify: (notification) => {
- set((state) => ({
- notifications: [...state.notifications, notification],
- }));
- emitReactNotification(notification);
+ pushReactNotification(notification);
},
});
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index 0d693561e6..803a63067a 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -125,7 +125,6 @@ export type InstanceSlice = {
};
export type NotificationSlice = {
- notifications: NotificationCreate[];
notify: (notification: NotificationCreate) => void;
};
diff --git a/frontend/src/shell-bridge.test.ts b/frontend/src/shell-bridge.test.ts
index 4cbbab4509..d3fc1f598e 100644
--- a/frontend/src/shell-bridge.test.ts
+++ b/frontend/src/shell-bridge.test.ts
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { nextTick } from "vue";
import {
emitReactLocaleChange,
- emitReactNotification,
emitReactQuickstartReset,
} from "@/react/shell-bridge";
@@ -22,8 +21,6 @@ const mocks = vi.hoisted(() => ({
setDocumentTitle: vi.fn(),
overrideAppProfile: vi.fn(),
pushNotification: vi.fn(),
- tryPopNotification: vi.fn(),
- notificationCreate: vi.fn(),
introState: {} as Record<string, boolean>,
saveIntroStateByKey: vi.fn(
async ({ key, newState }: { key: string; newState: boolean }) => {
@@ -44,10 +41,6 @@ vi.mock("naive-ui", async () => {
});
return {
NConfigProvider: passthrough("NConfigProvider"),
- NNotificationProvider: passthrough("NNotificationProvider"),
- useNotification: () => ({
- create: mocks.notificationCreate,
- }),
};
});
@@ -106,7 +99,6 @@ vi.mock("./plugins/i18n", () => ({
vi.mock("./store", () => ({
useNotificationStore: () => ({
pushNotification: mocks.pushNotification,
- tryPopNotification: mocks.tryPopNotification,
}),
useUIStateStore: () => ({
introState: mocks.introState,
@@ -134,7 +126,6 @@ vi.mock("vue-router", async () => {
});
import App from "./App.vue";
-import NotificationContext from "./NotificationContext.vue";
beforeEach(() => {
vi.clearAllMocks();
@@ -191,37 +182,4 @@ describe("React shell bridge", () => {
wrapper.unmount();
});
-
- test("shows bytebase notifications and ignores other modules", async () => {
- const wrapper = mount(NotificationContext, {
- attachTo: document.body,
- slots: {
- default: "<div />",
- },
- });
- await nextTick();
-
- emitReactNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: "Saved",
- });
-
- expect(mocks.notificationCreate).toHaveBeenCalledWith(
- expect.objectContaining({
- type: "success",
- })
- );
-
- mocks.notificationCreate.mockClear();
- emitReactNotification({
- module: "other",
- style: "SUCCESS",
- title: "Ignored",
- });
-
- expect(mocks.notificationCreate).not.toHaveBeenCalled();
-
- wrapper.unmount();
- });
});
diff --git a/frontend/src/store/modules/notification.ts b/frontend/src/store/modules/notification.ts
index e4b5a2cc90..39154662fc 100644
--- a/frontend/src/store/modules/notification.ts
+++ b/frontend/src/store/modules/notification.ts
@@ -1,70 +1,30 @@
import { defineStore } from "pinia";
-import { v1 as uuidv1 } from "uuid";
-import type {
- Notification,
- NotificationCreate,
- NotificationFilter,
-} from "@/types";
-
-interface NotificationState {
- notificationByModule: Map<string, Notification[]>;
-}
+import { VueShellBridgeEvent } from "@/react/shell-bridge";
+import type { NotificationCreate } from "@/types";
+/**
+ * Notification store — kept as a Pinia store for backward compatibility
+ * with the 17 Vue-side pushNotification() callers. No internal queue: each
+ * push dispatches a window CustomEvent that the React toast manager
+ * (frontend/src/react/lib/toast.ts) catches and renders. The Pinia layer
+ * dies entirely in Phase B3 (Pinia -> Zustand).
+ */
export const useNotificationStore = defineStore("notification", {
- state: (): NotificationState => ({
- notificationByModule: new Map(),
- }),
+ state: () => ({}),
actions: {
- appendNotification(notification: Notification) {
- const list = this.notificationByModule.get(notification.module);
- if (list) {
- list.push(notification);
- } else {
- this.notificationByModule.set(notification.module, [notification]);
- }
- },
- removeNotification(notification: Notification) {
- const list = this.notificationByModule.get(notification.module);
- if (list) {
- const i = list.indexOf(notification);
- if (i > -1) {
- list.splice(i, 1);
- }
+ pushNotification(notification: NotificationCreate) {
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(
+ new CustomEvent<NotificationCreate>(
+ VueShellBridgeEvent.notification,
+ { detail: notification }
+ )
+ );
}
},
- pushNotification(notificationCreate: NotificationCreate) {
- const notification: Notification = {
- id: uuidv1(),
- createdTs: Date.now() / 1000,
- ...notificationCreate,
- };
- this.appendNotification(notification);
- },
- tryPopNotification(filter: NotificationFilter) {
- const notification = findNotification(this.$state, filter);
- if (notification) {
- this.removeNotification(notification);
- }
- return notification;
- },
},
});
-function findNotification(
- state: NotificationState,
- filter: NotificationFilter
-): Notification | undefined {
- const list = state.notificationByModule.get(filter.module);
- if (list && list.length > 0) {
- if (filter.id) {
- return list.find((item) => item.id === filter.id);
- }
- return list[0];
- }
- return undefined;
-}
-
-export const pushNotification = (notificationCreate: NotificationCreate) => {
- const store = useNotificationStore();
- store.pushNotification(notificationCreate);
+export const pushNotification = (notification: NotificationCreate) => {
+ useNotificationStore().pushNotification(notification);
};
diff --git a/frontend/src/types/notification.ts b/frontend/src/types/notification.ts
index 19521fdc56..a870f0c992 100644
--- a/frontend/src/types/notification.ts
+++ b/frontend/src/types/notification.ts
@@ -2,9 +2,7 @@ import type { VNodeChild } from "vue";
export type BBNotificationStyle = "INFO" | "SUCCESS" | "WARN" | "CRITICAL";
-export type Notification = {
- id: string;
- createdTs: number;
+export type NotificationCreate = {
module: string;
style: BBNotificationStyle;
title: string;
@@ -13,12 +11,3 @@ export type Notification = {
linkTitle?: string;
manualHide?: boolean;
};
-
-// "id" and "createdTs" is auto generated upon the notification store
-// receives.
-export type NotificationCreate = Omit<Notification, "id" | "createdTs">;
-
-export type NotificationFilter = {
- module: string;
- id?: string;
-};