Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: standardize react overlay layering (#20012)
p0nyabdb5b52d806
diff --git a/docs/superpowers/specs/2026-04-14-react-overlay-layering-policy-design.md b/docs/superpowers/specs/2026-04-14-react-overlay-layering-policy-design.mdnew file mode 100644index 0000000000..a89854944f--- /dev/null+++ b/docs/superpowers/specs/2026-04-14-react-overlay-layering-policy-design.md@@ -0,0 +1,236 @@+# React Overlay Layering Policy Design++## Summary++Define a React-only global layering policy for Bytebase that replaces ad hoc `z-index` decisions with three semantic overlay families:++- `overlay` for standard app overlays+- `agent` for the page agent window and all agent-owned overlays+- `critical` for forced session-expired / re-login UI++The policy must preserve one intentional exception to ordinary modal behavior: the agent stays visible and interactive above normal app dialogs and sheets so users can supervise ongoing DOM manipulation. The only UI allowed above the agent is forced auth recovery.++## Goals++- Replace raw global `z-index` usage in React feature code with semantic layer ownership.+- Keep standard app overlays predictable during the Vue-to-React migration.+- Ensure the `AgentWindow` and minimized launcher remain above normal app overlays.+- Ensure forced session-expired / re-login UI is the only surface allowed above the agent.+- Define interaction precedence, not just paint order, for pointer events, focus, and `Escape`.+- Create a policy that can be enforced through design-system primitives and code review.++## Non-Goals++- Do not standardize legacy Vue / Naive UI stacking in this policy.+- Do not ban all `z-index` usage; component-internal paint order still needs it.+- Do not introduce many permanent top-level families beyond `overlay`, `agent`, and `critical`.+- Do not let individual features negotiate exceptions with local `z-index` values.++## Current State++Bytebase's React overlays are partially standardized today but not yet policy-driven:++- shared React overlay primitives currently coordinate around a common `z-50`+- the `AgentWindow` shell currently uses a lower layer (`z-40`)+- some React surfaces still use one-off values such as `z-[60]` or `z-[999]`++That model is insufficient for the intended product behavior because the user wants the agent to remain above normal app dialogs while the agent manipulates the page. A single shared `z-50` family cannot express that requirement cleanly.++## Policy Decision++Bytebase React will use a small fixed set of semantic global layers:++- `base`+- `overlay`+- `agent`+- `critical`++Precedence is strict:++- `critical` > `agent` > `overlay` > `base`++No additional permanent global layer may be introduced without an explicit policy change.++## Layer Model++### `base`++`base` is normal page rendering:++- page content+- layout chrome+- sticky headers and footers+- component-local paint order++`base` does not participate in global overlay arbitration.++### `overlay`++`overlay` is the default family for normal app overlays:++- `Dialog`+- `Sheet`+- `AlertDialog`+- `Select`+- `DropdownMenu`+- `Popover`+- `Tooltip`++These surfaces remain modal relative to the app, but they are not allowed to cover or disable the agent layer.++### `agent`++`agent` is a global supervisor family:++- full `AgentWindow`+- minimized agent launcher+- dialogs, menus, selects, tooltips, and other overlays opened from agent UI++This family remains above normal app overlays and stays interactive while app overlays are open underneath it.++### `critical`++`critical` is reserved for forced auth recovery:++- session-expired UI+- re-login UI required before further interaction+- child overlays opened from that UI++`critical` is the only family allowed to cover and disable the agent.++## Ownership Rules++Layer ownership is determined by surface owner, not by whichever `z-index` value a feature wants.++Rules:++- regular product pages use app overlay primitives only+- agent UI uses agent-owned primitives only+- auth recovery flows use critical-owned primitives only+- callers may not promote a surface into a higher family with custom classes or inline styles+- child overlays inherit the family of the parent surface that opened them++Examples:++- a `Select` opened inside a settings `Dialog` remains in `overlay`+- a confirm dialog opened from the `AgentWindow` belongs to `agent`+- a tooltip opened from the re-login panel belongs to `critical`++## Portal Architecture++Each family gets a dedicated portal root in `document.body`:++- app overlay root+- agent root+- critical root++These roots make cross-family precedence deterministic and inspectable. Product code should not choose portal roots directly. Design-system primitives choose the correct root automatically.++Within one family, later-mounted portals render above earlier-mounted portals. The policy relies on mount order only within a family, not across families.++## Primitive Model++The design system should expose separate primitive families or wrappers:++- app primitives for standard product overlays+- agent primitives for agent-owned overlays+- critical primitives for auth recovery overlays++Most teams should only use the app primitive family. Agent and critical primitives are intentionally narrow and used by a small number of owned surfaces.++Numeric layer values remain internal to the design system.++## Interaction Model++The policy must govern pointer events, focus, and keyboard dismissal in addition to paint order.++### Pointer Events++- pointer events go to the highest visible family under the pointer+- app backdrops and dialogs may not intercept clicks intended for visible agent UI+- when `critical` is visible, it intercepts interaction ahead of both `agent` and `overlay`++### Focus And Modality++- app overlays remain modal within the app overlay family+- the agent exists outside the app overlay family's modal domain+- the critical family is modal relative to everything++This means a normal app dialog can still trap focus for the app, while the user can interact with the agent as a separate higher-priority surface.++### Escape Handling++`Escape` handling follows active-surface and family precedence:++- the active topmost surface gets first refusal+- if a higher family handles `Escape`, lower families do not also act on it+- underlying app overlays may only receive `Escape` if the higher family declines it++This prevents agent interaction from accidentally dismissing an underlying app dialog.++## Allowed Local `z-index`++Local `z-index` remains allowed for component-internal paint order such as:++- sticky table headers+- resize handles+- icon or badge layering+- selection highlights++This is allowed only when the value does not attempt to outrank another page surface. If a `z-index` choice is intended to beat another surface elsewhere on the page, it belongs in the layer system and should not be local feature code.++## Guardrails++React feature code must not:++- use raw global `z-*` classes to beat other surfaces+- use inline `zIndex` for cross-surface ordering+- create feature-owned top-level portal roots+- add temporary escape hatches such as `z-[9999]`+- introduce additional global families without policy review++If a surface cannot be expressed in the policy, the design-system contract is incomplete and should be fixed centrally.++## Migration Strategy++Recommended rollout:++1. Introduce semantic layer tokens and dedicated portal roots.+2. Convert existing shared app overlay primitives to the `overlay` family.+3. Convert the `AgentWindow`, minimized launcher, and agent-owned child overlays to the `agent` family.+4. Build a shared session-expired / re-login surface in the `critical` family.+5. Add review and lint guardrails against ad hoc React global `z-index` usage.+6. Migrate existing React outliers to owned primitives and family-based portals.++## Testing Strategy++Minimum behavioral coverage:++- standard app overlay over app overlay within the `overlay` family+- agent shell above app dialog and sheet+- agent child dialog/menu above app overlay+- minimized agent launcher above app overlay+- critical session-expired UI above the agent+- critical child overlays above the agent+- pointer routing to agent over an underlying app backdrop+- `Escape` precedence across `overlay`, `agent`, and `critical`+- focus behavior when app modal and agent are both present++## Risks++- If family ownership is not enforced through primitives, features will route around the policy with local numbers.+- If portal roots are not explicit, cross-family ordering will become dependent on incidental mount behavior.+- If interaction precedence is under-specified, visual order will look correct while keyboard and pointer behavior remain broken.+- If the critical family is not tightly scoped, other teams will start requesting exceptions above the agent.++## Recommendation++Adopt a strict three-family React overlay policy with dedicated portal roots, semantic ownership, and explicit interaction precedence.++This is the smallest model that matches Bytebase's intended product behavior:++- standard app overlays remain coherent+- the agent stays on top while supervising page automation+- forced re-auth is the sole exception that can cover and disable the agent++Anything looser will regress into another round of ad hoc `z-index` escalation during migration.diff --git a/frontend/AGENTS.md b/frontend/AGENTS.mdindex 80d4374b54..9ae5f260b9 100644--- a/frontend/AGENTS.md+++ b/frontend/AGENTS.md@@ -32,7 +32,17 @@ React UI components live in `src/react/components/ui/` and follow shadcn-style p- **Use `truncate` shorthand** — not `overflow-hidden text-ellipsis whitespace-nowrap`- **Use `cn()` for conditional classes** — import from `@/react/lib/utils`, don't write manual template literal ternaries- **No manual `dark:` overrides** — use semantic tokens that handle theming-- **No manual `z-index` on overlay *consumers*** — callers of `Dialog`, `Sheet`, `Popover`, `Select`, `Tooltip` must not set their own `z-index`. The primitives in `src/react/components/ui/` already coordinate stacking (all overlays use `z-50`; within that layer, later-mounted portals win by DOM order). Do **not** strip `z-50` from `select.tsx`, `tooltip.tsx`, `dialog.tsx`, or `alert-dialog.tsx` — removing it makes Select/Tooltip render behind Dialog (BYT-9226, PR #19824)+- **Overlay layering policy** — React overlays use three semantic families: `overlay`, `agent`, and `critical`.+ - Standard app overlays mount into `overlay`.+ - The shared primitives in `src/react/components/ui/` are the `overlay` entry points; they are not for agent-owned or critical surfaces.+ - `AgentWindow`, the minimized launcher, and other agent-owned overlays mount into `agent` and stay above normal app overlays.+ - Agent-owned surfaces should use the wrappers in `src/react/plugins/agent/components/ui/` or other agent-owned code that mounts into `getLayerRoot("agent")`.+ - Forced session-expired / re-login UI mounts into `critical` and is the only layer allowed above and disabling the agent.+ - `critical` is reserved for auth/session recovery surfaces such as `SessionExpiredSurface`; do not introduce new feature-level critical overlays without an explicit policy change.+ - Each family has a dedicated portal root; use `getLayerRoot(<family>)` to choose the family root, and use `LAYER_SURFACE_CLASS` / `LAYER_BACKDROP_CLASS` from `src/react/components/ui/layer.ts` for shared intra-family stacking where appropriate.+ - Children inherit the owning family. If a parent mounts into `agent` or `critical`, its descendants must not remount into a lower family.+ - Raw global `z-index` values are forbidden in React feature code for cross-surface stacking. Local component-internal `z-index` remains allowed when it only affects internal composition.+ - Consumers of overlay primitives must not set their own global `z-index`.- **Dialog vs Sheet** — use `<Sheet>` (right-side drawer, in `src/react/components/ui/sheet.tsx`) for **creating or editing a resource**. Use `<Dialog>` for **confirmations, single-field prompts, critical interrupts, and read-only result displays**. The dividing line is whether the user is filling out a form with multiple fields — drawers keep the parent list/table visible behind a scrim and scale to multi-section forms, while dialogs are for short blocking interactions. `AlertDialog` is the right pick for destructive confirms that need an explicit acknowledgment.- **Sheet width tiers** — `<SheetContent>` accepts a `width` variant. Pick the tier that matches the form complexity; don't inline ad-hoc widths. Add a new tier to `sheet.tsx` only if a genuinely new size is needed.- `narrow` (384px) — single-field pickers, short 2–3 field forms, environment/project selection, read-only display sheetsdiff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vueindex c8aec3fc77..5c12967b0b 100644--- a/frontend/src/AuthContext.vue+++ b/frontend/src/AuthContext.vue@@ -5,7 +5,7 @@</div><template v-if="!isAuthRoute && authStore.isLoggedIn"><!-- Do not show the modal when the user is in auth related pages. -->- <SigninModal v-if="authStore.unauthenticatedOccurred" />+ <SessionExpiredSurfaceMount v-if="authStore.unauthenticatedOccurred" /><InactiveRemindModal v-else /></template></template>@@ -14,9 +14,9 @@import { computed, onMounted, onUnmounted, ref, watch } from "vue";import { useRouter } from "vue-router";import { BBSpin } from "@/bbkit";+import SessionExpiredSurfaceMount from "@/components/SessionExpiredSurfaceMount.vue";import { isAuthRelatedRoute } from "@/utils/auth";import InactiveRemindModal from "@/views/auth/InactiveRemindModal.vue";-import SigninModal from "@/views/auth/SigninModal.vue";import { t } from "./plugins/i18n";import { WORKSPACE_ROOT_MODULE } from "./router/dashboard/workspaceRoutes";import {diff --git a/frontend/src/components/SessionExpiredSurfaceMount.vue b/frontend/src/components/SessionExpiredSurfaceMount.vuenew file mode 100644index 0000000000..4c3d939ba2--- /dev/null+++ b/frontend/src/components/SessionExpiredSurfaceMount.vue@@ -0,0 +1,85 @@+<template>+ <div ref="container" />+</template>++<script lang="ts" setup>+import { computed, onMounted, onUnmounted, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { useRoute } from "vue-router";+import { mountReactPage, updateReactPage } from "@/react/mount";++const { locale } = useI18n();+const route = useRoute();+const container = ref<HTMLElement>();+// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import+let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any+let isUnmounted = false;+let syncVersion = 0;+let syncChain = Promise.resolve();++const props = computed(() => ({ currentPath: route.fullPath }));+let latestLocale = locale.value;+let latestProps = props.value;++const syncMountedPage = async (+ nextLocale: string,+ nextProps: { currentPath: string }+) => {+ const currentSyncVersion = ++syncVersion;+ syncChain = syncChain+ .catch(() => {})+ .then(async () => {+ if (isUnmounted || currentSyncVersion !== syncVersion) return;+ const i18nModule = await import("@/react/i18n");+ if (isUnmounted || currentSyncVersion !== syncVersion) return;+ if (i18nModule.default.language !== nextLocale) {+ await i18nModule.default.changeLanguage(nextLocale);+ }+ if (isUnmounted || !root || currentSyncVersion !== syncVersion) return;+ await updateReactPage(root, "SessionExpiredSurface", nextProps);+ });+ await syncChain;+};++onMounted(async () => {+ if (!container.value) return;+ isUnmounted = false;+ latestLocale = locale.value;+ latestProps = props.value;+ const mountedLocale = latestLocale;+ const mountedProps = latestProps;+ const i18nModule = await import("@/react/i18n");+ if (i18nModule.default.language !== mountedLocale) {+ await i18nModule.default.changeLanguage(mountedLocale);+ }+ if (isUnmounted || !container.value) return;+ const mountedRoot = await mountReactPage(+ container.value,+ "SessionExpiredSurface",+ mountedProps+ );+ if (isUnmounted) {+ mountedRoot.unmount();+ return;+ }+ root = mountedRoot;+ if (latestLocale !== mountedLocale || latestProps !== mountedProps) {+ await syncMountedPage(latestLocale, latestProps);+ }+});++watch([locale, props], async ([nextLocale, nextProps]) => {+ latestLocale = nextLocale;+ latestProps = nextProps;+ if (!root) return;+ await syncMountedPage(nextLocale, nextProps);+});++onUnmounted(() => {+ isUnmounted = true;+ syncVersion++;+ syncChain = Promise.resolve();+ root?.unmount();+ root = null;+});+</script>diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.tsindex 50ac0964a7..0f1dbdcee0 100644--- a/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts@@ -122,6 +122,7 @@ describe("authInterceptor", () => {});expect(mocks.authStore.unauthenticatedOccurred).toBe(true);+ expect(mocks.pushNotification).toHaveBeenCalledTimes(1);expect(mocks.pushNotification).toHaveBeenCalledWith({module: "bytebase",style: "WARN",diff --git a/frontend/src/react/components/HighlightLabelText.tsx b/frontend/src/react/components/HighlightLabelText.tsxindex 37a04e687e..aca8a708b1 100644--- a/frontend/src/react/components/HighlightLabelText.tsx+++ b/frontend/src/react/components/HighlightLabelText.tsx@@ -1,4 +1,4 @@-import { getHighlightHTMLByRegExp } from "@/utils";+import { getHighlightHTMLByRegExp } from "@/utils/util";interface HighlightLabelTextProps {text: string;diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsxnew file mode 100644index 0000000000..2bb15aff34--- /dev/null+++ b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx@@ -0,0 +1,417 @@+import { flushPromises, mount } from "@vue/test-utils";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { nextTick } from "vue";++vi.mock("./SigninBridge", () => ({+ SigninBridge: () => <button data-testid="signin-bridge">Sign in</button>,+}));++vi.mock("@/store", () => ({+ useAuthStore: () => ({+ logout: vi.fn(),+ }),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++const mountMocks = vi.hoisted(() => ({+ reactI18nLanguage: { value: "en-US" },+ changeLanguage: vi.fn(async (locale: string) => {+ mountMocks.reactI18nLanguage.value = locale;+ }),+ mountReactPage: vi.fn(async () => ({ unmount: vi.fn() })),+ routePath: null as unknown,+ updateReactPage: vi.fn(async () => {}),+ locale: null as { value: string } | null,+ reactI18n: {+ get language() {+ return mountMocks.reactI18nLanguage.value;+ },+ changeLanguage: vi.fn(async (locale: string) => {+ mountMocks.reactI18nLanguage.value = locale;+ }),+ },+}));++mountMocks.reactI18n.changeLanguage = mountMocks.changeLanguage;++vi.mock("@/react/i18n", () => ({+ default: mountMocks.reactI18n,+}));++vi.mock("@/react/mount", () => ({+ mountReactPage: mountMocks.mountReactPage,+ updateReactPage: mountMocks.updateReactPage,+}));++vi.mock("vue-i18n", async () => {+ const { ref } = await import("vue");+ mountMocks.locale ||= ref("zh-CN");++ return {+ useI18n: () => ({+ locale: mountMocks.locale,+ }),+ };+});++vi.mock("vue-router", async () => {+ const { ref } = await import("vue");+ mountMocks.routePath ||= ref("/instances");++ return {+ useRoute: () => ({+ get fullPath() {+ return (+ mountMocks.routePath as {+ value: string;+ }+ ).value;+ },+ }),+ };+});++import SessionExpiredSurfaceMount from "@/components/SessionExpiredSurfaceMount.vue";+import { Dialog, DialogContent } from "@/react/components/ui/dialog";+import { SessionExpiredSurface } from "./SessionExpiredSurface";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("SessionExpiredSurface", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ mountMocks.changeLanguage.mockClear();+ mountMocks.mountReactPage.mockClear();+ mountMocks.updateReactPage.mockClear();+ mountMocks.locale!.value = "zh-CN";+ mountMocks.reactI18nLanguage.value = "en-US";+ (+ mountMocks.routePath as {+ value: string;+ }+ ).value = "/instances";+ });++ test("mounts into the critical root", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(<SessionExpiredSurface currentPath="/instances" />);+ await Promise.resolve();+ });++ const criticalRoot = document.getElementById("bb-react-layer-critical");+ expect(criticalRoot).toBeInstanceOf(HTMLDivElement);+ expect(+ criticalRoot?.querySelector("[data-session-expired-surface]")+ ).toBeTruthy();++ await act(async () => {+ root.unmount();+ });+ });++ test("moves focus into the critical dialog", async () => {+ const backgroundButton = document.createElement("button");+ backgroundButton.textContent = "Background";+ document.body.appendChild(backgroundButton);+ backgroundButton.focus();++ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(<SessionExpiredSurface currentPath="/instances" />);+ await Promise.resolve();+ });++ const criticalRoot = document.getElementById("bb-react-layer-critical");+ expect(criticalRoot).toBeInstanceOf(HTMLDivElement);++ await act(async () => {+ await vi.waitFor(() => {+ expect(document.activeElement).not.toBe(backgroundButton);+ expect(+ criticalRoot?.contains(document.activeElement as Node)+ ).toBeTruthy();+ });+ });++ await act(async () => {+ root.unmount();+ });+ });++ test("does not let Escape dismiss lower-layer dialogs", async () => {+ const onOpenChange = vi.fn();+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <>+ <Dialog open onOpenChange={onOpenChange}>+ <DialogContent>Underlying dialog</DialogContent>+ </Dialog>+ <SessionExpiredSurface currentPath="/instances" />+ </>+ );+ await Promise.resolve();+ });++ const signinButton = document.querySelector(+ "[data-testid='signin-bridge']"+ ) as HTMLButtonElement | null;++ expect(signinButton).toBeInstanceOf(HTMLButtonElement);++ await act(async () => {+ signinButton?.focus();+ signinButton?.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "Escape",+ bubbles: true,+ cancelable: true,+ })+ );+ await Promise.resolve();+ });++ expect(onOpenChange).not.toHaveBeenCalled();++ await act(async () => {+ root.unmount();+ });+ });++ test("keeps the agent layer inert while the critical surface is open", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const agentRoot = document.createElement("div");++ agentRoot.id = "bb-react-layer-agent";+ document.body.appendChild(agentRoot);++ await act(async () => {+ root.render(+ <>+ <Dialog open>+ <DialogContent>Underlying dialog</DialogContent>+ </Dialog>+ <SessionExpiredSurface currentPath="/instances" />+ </>+ );+ await Promise.resolve();+ });++ await vi.waitFor(() => {+ expect(agentRoot.getAttribute("aria-hidden")).toBe("true");+ });++ await act(async () => {+ root.unmount();+ });+ });++ test("syncs React i18n before the initial mount", async () => {+ const calls: string[] = [];+ mountMocks.changeLanguage.mockImplementation(async () => {+ calls.push("changeLanguage");+ });+ mountMocks.mountReactPage.mockImplementation(async () => {+ calls.push("mountReactPage");+ return { unmount: vi.fn() };+ });++ const wrapper = mount(SessionExpiredSurfaceMount);+ await flushPromises();++ await vi.waitFor(() => {+ expect(mountMocks.changeLanguage).toHaveBeenCalledWith("zh-CN");+ expect(mountMocks.mountReactPage).toHaveBeenCalledTimes(1);+ expect(calls).toEqual(["changeLanguage", "mountReactPage"]);+ });++ wrapper.unmount();+ });++ test("reconciles the latest route after async mount resolves", async () => {+ let resolveMount: ((root: unknown) => void) | undefined;+ const mountedRoot = { unmount: vi.fn(() => {}) };+ mountMocks.mountReactPage.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveMount = (root) => {+ resolve(root as { unmount: typeof mountedRoot.unmount });+ };+ })+ );++ const wrapper = mount(SessionExpiredSurfaceMount);+ await flushPromises();++ expect(mountMocks.mountReactPage).toHaveBeenCalledWith(+ expect.any(HTMLDivElement),+ "SessionExpiredSurface",+ { currentPath: "/instances" }+ );++ (+ mountMocks.routePath as {+ value: string;+ }+ ).value = "/projects/demo";+ await nextTick();+ await flushPromises();++ expect(mountMocks.updateReactPage).not.toHaveBeenCalled();++ resolveMount?.(mountedRoot);+ await flushPromises();++ await vi.waitFor(() => {+ expect(mountMocks.updateReactPage).toHaveBeenCalledWith(+ mountedRoot,+ "SessionExpiredSurface",+ { currentPath: "/projects/demo" }+ );+ });++ wrapper.unmount();+ });++ test("unmounts late-mounted roots when the Vue bridge is already gone", async () => {+ let resolveMount: ((root: unknown) => void) | undefined;+ const mountedRoot = { unmount: vi.fn(() => {}) };+ mountMocks.mountReactPage.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveMount = (root) => {+ resolve(root as { unmount: typeof mountedRoot.unmount });+ };+ })+ );++ const wrapper = mount(SessionExpiredSurfaceMount);+ await flushPromises();++ wrapper.unmount();+ resolveMount?.(mountedRoot);+ await flushPromises();++ expect(mountedRoot.unmount).toHaveBeenCalledTimes(1);+ });++ test("keeps the newest route when async syncs finish out of order", async () => {+ const mountedRoot = { unmount: vi.fn(() => {}) };+ const pendingLanguageChanges: Array<() => void> = [];+ let changeLanguageCall = 0;++ mountMocks.changeLanguage.mockImplementation(async () => {+ changeLanguageCall++;+ if (changeLanguageCall === 1) {+ return;+ }+ await new Promise<void>((resolve) => {+ pendingLanguageChanges.push(resolve);+ });+ });+ mountMocks.mountReactPage.mockResolvedValue(mountedRoot);++ const wrapper = mount(SessionExpiredSurfaceMount);+ await flushPromises();++ (+ mountMocks.routePath as {+ value: string;+ }+ ).value = "/projects/first";+ await nextTick();+ await flushPromises();++ (+ mountMocks.routePath as {+ value: string;+ }+ ).value = "/projects/second";+ await nextTick();+ await flushPromises();++ expect(pendingLanguageChanges).toHaveLength(1);++ await flushPromises();+ pendingLanguageChanges[0]?.();+ await flushPromises();++ expect(pendingLanguageChanges).toHaveLength(2);++ pendingLanguageChanges[1]?.();+ await flushPromises();++ expect(mountMocks.updateReactPage).toHaveBeenLastCalledWith(+ mountedRoot,+ "SessionExpiredSurface",+ { currentPath: "/projects/second" }+ );++ wrapper.unmount();+ });++ test("keeps the newest locale when async locale syncs finish out of order", async () => {+ const mountedRoot = { unmount: vi.fn(() => {}) };+ const pendingLanguageChanges = new Map<string, () => void>();++ mountMocks.mountReactPage.mockResolvedValue(mountedRoot);+ mountMocks.changeLanguage.mockImplementation(async (locale: string) => {+ if (locale === "zh-CN") {+ mountMocks.reactI18nLanguage.value = locale;+ return;+ }+ await new Promise<void>((resolve) => {+ pendingLanguageChanges.set(locale, () => {+ mountMocks.reactI18nLanguage.value = locale;+ resolve();+ });+ });+ });++ const wrapper = mount(SessionExpiredSurfaceMount);+ await flushPromises();++ mountMocks.locale!.value = "fr-FR";+ await nextTick();+ await flushPromises();++ mountMocks.locale!.value = "de-DE";+ await nextTick();+ await flushPromises();++ expect(pendingLanguageChanges.size).toBe(1);++ pendingLanguageChanges.get("fr-FR")?.();+ await flushPromises();++ expect(pendingLanguageChanges.size).toBe(2);++ pendingLanguageChanges.get("de-DE")?.();+ await flushPromises();++ expect(mountMocks.reactI18n.language).toBe("de-DE");++ wrapper.unmount();+ });+});diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.tsxnew file mode 100644index 0000000000..308502d6ee--- /dev/null+++ b/frontend/src/react/components/auth/SessionExpiredSurface.tsx@@ -0,0 +1,35 @@+import { Dialog as BaseDialog } from "@base-ui/react/dialog";+import { useTranslation } from "react-i18next";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+} from "@/react/components/ui/layer";+import { SigninBridge } from "./SigninBridge";++export function SessionExpiredSurface({+ currentPath,+}: {+ currentPath: string;+}) {+ const { t } = useTranslation();++ return (+ <BaseDialog.Root open onOpenChange={() => {}}>+ <BaseDialog.Portal container={getLayerRoot("critical")}>+ <BaseDialog.Backdrop+ className={`fixed inset-0 ${LAYER_BACKDROP_CLASS} bg-overlay/60`}+ />+ <BaseDialog.Popup+ data-session-expired-surface+ className={`fixed inset-0 ${LAYER_SURFACE_CLASS} flex items-center justify-center outline-none`}+ >+ <BaseDialog.Title className="sr-only">+ {t("auth.token-expired-title")}+ </BaseDialog.Title>+ <SigninBridge currentPath={currentPath} />+ </BaseDialog.Popup>+ </BaseDialog.Portal>+ </BaseDialog.Root>+ );+}diff --git a/frontend/src/react/components/auth/SigninBridge.test.tsx b/frontend/src/react/components/auth/SigninBridge.test.tsxnew file mode 100644index 0000000000..3356e6a8ae--- /dev/null+++ b/frontend/src/react/components/auth/SigninBridge.test.tsx@@ -0,0 +1,245 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";++const bridgeMocks = vi.hoisted(() => {+ type RootComponent = { render?: () => unknown };+ const app = {+ mount: vi.fn(),+ unmount: vi.fn(),+ use: vi.fn(),+ };+ app.use.mockReturnValue(app);++ return {+ app,+ createApp: vi.fn((_component: RootComponent) => app),+ h: vi.fn(),+ logout: vi.fn(),+ t: vi.fn((key: string) => key),+ };+});++vi.mock("vue", async () => {+ const actual = await vi.importActual<typeof import("vue")>("vue");+ return {+ ...actual,+ createApp: bridgeMocks.createApp,+ h: bridgeMocks.h,+ };+});++vi.mock("@/plugins/i18n", () => ({+ default: {+ global: {+ t: bridgeMocks.t,+ },+ },+}));++vi.mock("@/plugins/naive-ui", () => ({+ default: {},+}));++vi.mock("naive-ui", () => ({+ NButton: { name: "NButton" },+ NConfigProvider: { name: "NConfigProvider" },+}));++vi.mock("@/../naive-ui.config", () => ({+ dateLang: { value: "date-lang" },+ generalLang: { value: "general-lang" },+ themeOverrides: { value: { common: { primaryColor: "#4f46e5" } } },+}));++vi.mock("@/router", () => ({+ router: {},+}));++vi.mock("@/store", () => ({+ pinia: {},+ useAuthStore: () => ({+ logout: bridgeMocks.logout,+ }),+}));++vi.mock("@/views/auth/Signin.vue", () => ({+ default: { name: "Signin" },+}));++import { SigninBridge } from "./SigninBridge";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("SigninBridge", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ bridgeMocks.createApp.mockClear();+ bridgeMocks.h.mockClear();+ bridgeMocks.app.mount.mockClear();+ bridgeMocks.app.unmount.mockClear();+ bridgeMocks.app.use.mockClear();+ bridgeMocks.app.use.mockReturnValue(bridgeMocks.app);+ bridgeMocks.logout.mockClear();+ bridgeMocks.t.mockClear();+ });++ test("wraps signin with Naive theme config and restores the logout footer", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(<SigninBridge currentPath="/instances" />);+ });++ const render = bridgeMocks.createApp.mock.calls[0]?.[0]?.render;+ expect(render).toBeTypeOf("function");+ if (!render) {+ throw new Error(+ "expected SigninBridge to pass a render function to createApp"+ );+ }++ render();++ const configProviderCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "NConfigProvider"+ );+ expect(configProviderCall?.[1]).toEqual({+ locale: "general-lang",+ dateLocale: "date-lang",+ themeOverrides: { common: { primaryColor: "#4f46e5" } },+ });+ const providerSlots = configProviderCall?.[2] as+ | { default?: () => unknown }+ | undefined;+ expect(providerSlots?.default).toBeTypeOf("function");+ providerSlots?.default?.();++ const signinCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "Signin"+ );+ expect(signinCall).toBeDefined();+ expect(signinCall?.[1]).toEqual({+ redirect: false,+ redirectUrl: "/instances",+ allowSignup: false,+ });++ const slots = signinCall?.[2] as { footer?: () => unknown } | undefined;+ expect(slots?.footer).toBeTypeOf("function");+ slots?.footer?.();++ const footerButtonCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "NButton"+ );+ expect(footerButtonCall?.[1]).toMatchObject({+ quaternary: true,+ size: "small",+ });+ const buttonLabel = footerButtonCall?.[2] as (() => unknown) | undefined;+ buttonLabel?.();+ expect(bridgeMocks.t).toHaveBeenCalledWith("common.logout");++ const onClick = footerButtonCall?.[1]?.onClick as (() => void) | undefined;+ onClick?.();+ expect(bridgeMocks.logout).toHaveBeenCalledTimes(1);++ act(() => {+ root.unmount();+ });+ });++ test("updates redirectUrl without remounting the Vue signin app", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(<SigninBridge currentPath="/instances" />);+ });++ const render = bridgeMocks.createApp.mock.calls[0]?.[0]?.render;+ expect(render).toBeTypeOf("function");+ if (!render) {+ throw new Error(+ "expected SigninBridge to pass a render function to createApp"+ );+ }++ bridgeMocks.h.mockClear();+ render();+ let configProviderCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "NConfigProvider"+ );+ let providerSlots = configProviderCall?.[2] as+ | { default?: () => unknown }+ | undefined;+ providerSlots?.default?.();++ let signinCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "Signin"+ );+ expect(signinCall?.[1]).toMatchObject({+ redirectUrl: "/instances",+ });++ act(() => {+ root.render(<SigninBridge currentPath="/projects/demo" />);+ });++ expect(bridgeMocks.createApp).toHaveBeenCalledTimes(1);+ expect(bridgeMocks.app.unmount).not.toHaveBeenCalled();++ bridgeMocks.h.mockClear();+ render();+ configProviderCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "NConfigProvider"+ );+ providerSlots = configProviderCall?.[2] as+ | { default?: () => unknown }+ | undefined;+ providerSlots?.default?.();+ signinCall = bridgeMocks.h.mock.calls.find(+ ([component]) =>+ typeof component === "object" &&+ component !== null &&+ "name" in component &&+ component.name === "Signin"+ );+ expect(signinCall?.[1]).toMatchObject({+ redirectUrl: "/projects/demo",+ });++ act(() => {+ root.unmount();+ });+ });+});diff --git a/frontend/src/react/components/auth/SigninBridge.tsx b/frontend/src/react/components/auth/SigninBridge.tsxnew file mode 100644index 0000000000..bccc74a26d--- /dev/null+++ b/frontend/src/react/components/auth/SigninBridge.tsx@@ -0,0 +1,110 @@+import { NButton, NConfigProvider } from "naive-ui";+import { useEffect, useRef } from "react";+import { createApp, h, type Ref as VueRef, ref as vueRef } from "vue";+import { dateLang, generalLang, themeOverrides } from "@/../naive-ui.config";+import i18n from "@/plugins/i18n";+import NaiveUI from "@/plugins/naive-ui";+import { router } from "@/router";+import { pinia, useAuthStore } from "@/store";+import Signin from "@/views/auth/Signin.vue";++export function SigninBridge({ currentPath }: { currentPath: string }) {+ const containerRef = useRef<HTMLDivElement>(null);+ const redirectUrlRef = useRef<VueRef<string> | null>(null);++ useEffect(() => {+ if (!containerRef.current) return;+ const currentPathState = vueRef(currentPath);+ redirectUrlRef.current = currentPathState;++ const renderSignin = () =>+ h(+ Signin as never,+ {+ redirect: false,+ redirectUrl: currentPathState.value,+ allowSignup: false,+ },+ {+ footer: () =>+ h(+ NButton,+ {+ quaternary: true,+ size: "small",+ onClick: () => useAuthStore().logout(),+ },+ () => i18n.global.t("common.logout")+ ),+ }+ );++ const app = createApp({+ render() {+ return h(+ NConfigProvider,+ {+ locale: generalLang.value,+ dateLocale: dateLang.value,+ themeOverrides: themeOverrides.value,+ },+ {+ default: () =>+ h(+ "div",+ {+ class:+ "bg-white shadow-lg rounded-md py-3 flex pointer-events-auto flex-col gap-3",+ style: {+ maxWidth: "calc(100vw - 80px)",+ maxHeight: "calc(100vh - 80px)",+ },+ },+ [+ h(+ "div",+ {+ class: "px-4 max-h-screen overflow-auto w-full h-full",+ },+ [+ h(+ "div",+ {+ class:+ "flex items-center w-auto md:min-w-96 max-w-full h-auto md:py-4",+ },+ [+ h(+ "div",+ {+ class:+ "flex flex-col justify-center items-center flex-1 gap-y-2",+ },+ [renderSignin()]+ ),+ ]+ ),+ ]+ ),+ ]+ ),+ }+ );+ },+ });+ app.use(router).use(pinia).use(i18n).use(NaiveUI);+ app.mount(containerRef.current);++ return () => {+ redirectUrlRef.current = null;+ app.unmount();+ };+ }, []);++ useEffect(() => {+ if (!redirectUrlRef.current) return;+ redirectUrlRef.current.value = currentPath;+ }, [currentPath]);++ return <div ref={containerRef} />;+}diff --git a/frontend/src/react/components/ui/alert-dialog.tsx b/frontend/src/react/components/ui/alert-dialog.tsxindex e045aa62c6..704cd09dd1 100644--- a/frontend/src/react/components/ui/alert-dialog.tsx+++ b/frontend/src/react/components/ui/alert-dialog.tsx@@ -1,6 +1,12 @@import { AlertDialog as BaseAlertDialog } from "@base-ui/react/alert-dialog";import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+ usePreserveHigherLayerAccess,+} from "./layer";const AlertDialog = BaseAlertDialog.Root;@@ -14,7 +20,10 @@ function AlertDialogOverlay({return (<BaseAlertDialog.Backdropref={ref}- className={cn("fixed inset-0 z-50 bg-overlay/50", className)}+ className={cn(+ `fixed inset-0 ${LAYER_BACKDROP_CLASS} bg-overlay/50`,+ className+ )}{...props}/>);@@ -26,13 +35,15 @@ function AlertDialogContent({ref,...props}: ComponentProps<typeof BaseAlertDialog.Popup>) {+ usePreserveHigherLayerAccess("overlay");+return (- <BaseAlertDialog.Portal>+ <BaseAlertDialog.Portal container={getLayerRoot("overlay")}><AlertDialogOverlay /><BaseAlertDialog.Popupref={ref}className={cn(- "fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2",+ `fixed left-1/2 top-1/2 ${LAYER_SURFACE_CLASS} -translate-x-1/2 -translate-y-1/2`,"w-full max-w-md","rounded-sm bg-background p-6 shadow-lg",classNamediff --git a/frontend/src/react/components/ui/combobox.test.tsx b/frontend/src/react/components/ui/combobox.test.tsxnew file mode 100644index 0000000000..6fad8ef5f6--- /dev/null+++ b/frontend/src/react/components/ui/combobox.test.tsx@@ -0,0 +1,68 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test } from "vitest";+import { Combobox } from "./combobox";+import { Dialog, DialogContent } from "./dialog";+import { LAYER_BACKDROP_CLASS, LAYER_SURFACE_CLASS } from "./layer";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("Combobox", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ test("mounts a portaled dropdown into the overlay surface layer above the dialog surface", () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <Dialog open>+ <DialogContent className="dialog-surface">+ <div>Dialog body</div>+ <Combobox+ className="test-combobox"+ portal+ value=""+ onChange={() => {}}+ options={[{ value: "alpha", label: "Alpha" }]}+ placeholder="Pick one"+ />+ </DialogContent>+ </Dialog>+ );+ });++ const overlayRoot = document.getElementById("bb-react-layer-overlay");+ expect(overlayRoot).toBeInstanceOf(HTMLDivElement);++ const trigger = overlayRoot?.querySelector(".test-combobox > div");+ expect(trigger).toBeInstanceOf(HTMLDivElement);++ act(() => {+ trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ const dialogSurface = overlayRoot?.querySelector(".dialog-surface");+ expect(dialogSurface).toBeInstanceOf(HTMLDivElement);+ expect(dialogSurface?.className).toContain(LAYER_SURFACE_CLASS);++ expect(overlayRoot?.innerHTML).toContain(LAYER_BACKDROP_CLASS);++ const dropdown = overlayRoot?.querySelector(+ "div.bg-background.border.border-control-border.rounded-sm.shadow-lg.overflow-hidden"+ ) as HTMLDivElement | null;+ expect(dropdown).toBeInstanceOf(HTMLDivElement);+ expect(dropdown?.textContent).toContain("Alpha");+ expect(dropdown?.className).toContain(LAYER_SURFACE_CLASS);+ expect(overlayRoot?.lastElementChild).toBe(dropdown);++ act(() => {+ root.unmount();+ });+ });+});diff --git a/frontend/src/react/components/ui/combobox.tsx b/frontend/src/react/components/ui/combobox.tsxindex 96009fd133..83ad35e08a 100644--- a/frontend/src/react/components/ui/combobox.tsx+++ b/frontend/src/react/components/ui/combobox.tsx@@ -10,6 +10,7 @@ import {import { createPortal } from "react-dom";import { cn } from "@/react/lib/utils";import { HighlightLabelText } from "../HighlightLabelText";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";import { SearchInput } from "./search-input";export interface ComboboxOption {@@ -337,7 +338,8 @@ export function Combobox(props: ComboboxProps) {style={portal ? dropdownStyle : undefined}className={cn("bg-background border border-control-border rounded-sm shadow-lg overflow-hidden",- portal ? "z-[999]" : "absolute z-50 mt-1 min-w-full w-max"+ portal && LAYER_SURFACE_CLASS,+ !portal && "absolute z-50 mt-1 min-w-full w-max")}><SearchInput@@ -400,7 +402,7 @@ export function Combobox(props: ComboboxProps) {{/* Dropdown */}{open &&(portal- ? createPortal(dropdownContent, document.body)+ ? createPortal(dropdownContent, getLayerRoot("overlay")): dropdownContent)}</div>);diff --git a/frontend/src/react/components/ui/dialog.test.tsx b/frontend/src/react/components/ui/dialog.test.tsxnew file mode 100644index 0000000000..dc43e18cb4--- /dev/null+++ b/frontend/src/react/components/ui/dialog.test.tsx@@ -0,0 +1,115 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test, vi } from "vitest";+import { Dialog, DialogContent } from "./dialog";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+} from "./layer";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("Dialog", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ test("renders a child backdrop above the parent surface within the overlay layer", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <>+ <Dialog open>+ <DialogContent className="parent-surface">Parent</DialogContent>+ </Dialog>+ <Dialog open>+ <DialogContent className="child-surface">Child</DialogContent>+ </Dialog>+ </>+ );+ });++ const overlayRoot = document.getElementById("bb-react-layer-overlay");+ expect(overlayRoot).toBeInstanceOf(HTMLDivElement);++ await vi.waitFor(() => {+ const overlayElements = Array.from(+ overlayRoot?.querySelectorAll("*") ?? []+ );+ const backdrops = overlayElements.filter(+ (child): child is HTMLElement =>+ child instanceof HTMLElement &&+ child.className.includes(LAYER_BACKDROP_CLASS) &&+ child.className.includes("bg-overlay/50")+ );+ expect(backdrops).toHaveLength(2);++ const parentSurface = overlayElements.find(+ (child): child is HTMLElement =>+ child instanceof HTMLElement &&+ child.className.includes("parent-surface")+ );+ const childSurface = overlayElements.find(+ (child): child is HTMLElement =>+ child instanceof HTMLElement &&+ child.className.includes("child-surface")+ );+ expect(parentSurface).toBeInstanceOf(HTMLDivElement);+ expect(childSurface).toBeInstanceOf(HTMLDivElement);+ expect(parentSurface?.className).toContain(LAYER_SURFACE_CLASS);+ expect(childSurface?.className).toContain(LAYER_SURFACE_CLASS);++ expect(+ backdrops[0].compareDocumentPosition(parentSurface as Node) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ expect(+ (parentSurface as Node).compareDocumentPosition(backdrops[1]) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ expect(+ backdrops[1].compareDocumentPosition(childSurface as Node) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ });++ await act(async () => {+ root.unmount();+ });+ });++ test("keeps the agent layer visible to assistive tech when an app dialog opens", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const agentRoot = getLayerRoot("agent");+ const agentButton = document.createElement("button");++ agentButton.textContent = "Agent action";+ agentRoot.appendChild(agentButton);++ await act(async () => {+ root.render(+ <Dialog open>+ <DialogContent>App dialog</DialogContent>+ </Dialog>+ );+ });++ await vi.waitFor(() => {+ expect(agentRoot.getAttribute("aria-hidden")).toBeNull();+ expect(agentRoot.getAttribute("inert")).toBeNull();+ expect(agentRoot.getAttribute("data-base-ui-inert")).toBeNull();+ });++ await act(async () => {+ root.unmount();+ });+ });+});diff --git a/frontend/src/react/components/ui/dialog.tsx b/frontend/src/react/components/ui/dialog.tsxindex 74a37acad1..35bc085e3b 100644--- a/frontend/src/react/components/ui/dialog.tsx+++ b/frontend/src/react/components/ui/dialog.tsx@@ -1,6 +1,12 @@import { Dialog as BaseDialog } from "@base-ui/react/dialog";import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+ usePreserveHigherLayerAccess,+} from "./layer";// ---- Root ----const Dialog = BaseDialog.Root;@@ -9,11 +15,6 @@ const Dialog = BaseDialog.Root;const DialogTrigger = BaseDialog.Trigger;// ---- Overlay / Backdrop -----// Dialog, Select, Tooltip, and AlertDialog all use `z-50`. Within that shared-// z-layer, stacking falls back to DOM portal mount order — later mounts win —-// which correctly places a Select/Tooltip opened *inside* a Dialog on top of-// the dialog backdrop. Do not bump Dialog above z-50 (or other overlays below)-// without updating all four components together. See BYT-9226 / PR #19824.function DialogOverlay({className,ref,@@ -22,7 +23,10 @@ function DialogOverlay({return (<BaseDialog.Backdropref={ref}- className={cn("fixed inset-0 z-50 bg-overlay/50", className)}+ className={cn(+ `fixed inset-0 ${LAYER_BACKDROP_CLASS} bg-overlay/50`,+ className+ )}{...props}/>);@@ -35,13 +39,15 @@ function DialogContent({ref,...props}: ComponentProps<typeof BaseDialog.Popup>) {+ usePreserveHigherLayerAccess("overlay");+return (- <BaseDialog.Portal>+ <BaseDialog.Portal container={getLayerRoot("overlay")}><DialogOverlay /><BaseDialog.Popupref={ref}className={cn(- "fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2",+ `fixed left-1/2 top-1/2 ${LAYER_SURFACE_CLASS} -translate-x-1/2 -translate-y-1/2`,"w-[calc(100vw-8rem)] max-w-3xl 2xl:max-w-[55vw]","max-h-[calc(100vh-10rem)] overflow-y-auto","rounded-sm bg-background shadow-lg",diff --git a/frontend/src/react/components/ui/dropdown-menu.tsx b/frontend/src/react/components/ui/dropdown-menu.tsxindex ab1b9bc3c7..c2404efb68 100644--- a/frontend/src/react/components/ui/dropdown-menu.tsx+++ b/frontend/src/react/components/ui/dropdown-menu.tsx@@ -1,6 +1,7 @@import { Menu as BaseMenu } from "@base-ui/react/menu";import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";// ---- Root ----// Default to non-modal: row action menus should let users click through to@@ -19,13 +20,6 @@ function DropdownMenu({const DropdownMenuTrigger = BaseMenu.Trigger;// ---- Portal + Positioner + Popup -----// The `z-50` on the Positioner matches the z-index used by Dialog/Select/Tooltip-// (see ui/dialog.tsx, ui/select.tsx, ui/tooltip.tsx). It must not be removed —-// Dialog's backdrop/popup are hardcoded at z-50, so a DropdownMenu without an-// explicit z-index renders *behind* any open Dialog regardless of DOM portal-// order (z-auto loses to z-50). Within the same z-layer, stacking falls back to-// DOM order, which correctly puts later-mounted portals on top.-// See BYT-9226 and PR #19824 for the original regression.function DropdownMenuContent({className,children,@@ -38,11 +32,11 @@ function DropdownMenuContent({align?: ComponentProps<typeof BaseMenu.Positioner>["align"];}) {return (- <BaseMenu.Portal>+ <BaseMenu.Portal container={getLayerRoot("overlay")}><BaseMenu.PositionersideOffset={sideOffset}align={align}- className="z-50"+ className={LAYER_SURFACE_CLASS}><BaseMenu.Popupref={ref}diff --git a/frontend/src/react/components/ui/layer.test.tsx b/frontend/src/react/components/ui/layer.test.tsxnew file mode 100644index 0000000000..e3c516d902--- /dev/null+++ b/frontend/src/react/components/ui/layer.test.tsx@@ -0,0 +1,45 @@+import { afterEach, describe, expect, test } from "vitest";+import { getLayerRoot, LAYER_ROOT_ID, LAYER_Z_INDEX } from "./layer";++describe("layer roots", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ test("creates each layer root once with stable ordering", () => {+ const critical = getLayerRoot("critical");+ const overlay = getLayerRoot("overlay");+ const agent = getLayerRoot("agent");++ expect(overlay.id).toBe(LAYER_ROOT_ID.overlay);+ expect(agent.id).toBe(LAYER_ROOT_ID.agent);+ expect(critical.id).toBe(LAYER_ROOT_ID.critical);++ expect(overlay.style.zIndex).toBe(String(LAYER_Z_INDEX.overlay));+ expect(agent.style.zIndex).toBe(String(LAYER_Z_INDEX.agent));+ expect(critical.style.zIndex).toBe(String(LAYER_Z_INDEX.critical));++ expect(document.body.children[0]?.id).toBe(LAYER_ROOT_ID.overlay);+ expect(document.body.children[1]?.id).toBe(LAYER_ROOT_ID.agent);+ expect(document.body.children[2]?.id).toBe(LAYER_ROOT_ID.critical);++ expect(getLayerRoot("overlay")).toBe(overlay);+ expect(getLayerRoot("agent")).toBe(agent);+ expect(getLayerRoot("critical")).toBe(critical);++ expect(document.body.children).toHaveLength(3);+ expect(document.querySelectorAll(`#${LAYER_ROOT_ID.overlay}`)).toHaveLength(+ 1+ );+ expect(document.querySelectorAll(`#${LAYER_ROOT_ID.agent}`)).toHaveLength(+ 1+ );+ expect(+ document.querySelectorAll(`#${LAYER_ROOT_ID.critical}`)+ ).toHaveLength(1);+ });++ test("keeps the critical layer above the legacy Naive overlay stack", () => {+ expect(LAYER_Z_INDEX.critical).toBeGreaterThan(6000);+ });+});diff --git a/frontend/src/react/components/ui/layer.ts b/frontend/src/react/components/ui/layer.tsnew file mode 100644index 0000000000..2633da04da--- /dev/null+++ b/frontend/src/react/components/ui/layer.ts@@ -0,0 +1,140 @@+import { useLayoutEffect } from "react";++export const LAYER_ROOT_ID = {+ overlay: "bb-react-layer-overlay",+ agent: "bb-react-layer-agent",+ critical: "bb-react-layer-critical",+} as const;++export const LAYER_Z_INDEX = {+ overlay: 50,+ agent: 60,+ // Legacy Naive overlays start at 2000 and notifications/messages go higher,+ // so forced re-auth must sit above that during the Vue->React migration.+ critical: 7000,+} as const;++export type LayerFamily = keyof typeof LAYER_ROOT_ID;++const ORDERED_FAMILIES: LayerFamily[] = ["overlay", "agent", "critical"];+const LAYER_ACCESSIBLE_ATTRIBUTES = [+ "aria-hidden",+ "inert",+ "data-base-ui-inert",+] as const;+const HIGHER_LAYER_FAMILIES: Record<LayerFamily, LayerFamily[]> = {+ overlay: ["agent", "critical"],+ agent: ["critical"],+ critical: [],+};++const getExistingLayerRoot = (family: LayerFamily) =>+ document.getElementById(LAYER_ROOT_ID[family]) as HTMLDivElement | null;++const hasActiveLayerContent = (family: LayerFamily) =>+ (getExistingLayerRoot(family)?.childElementCount ?? 0) > 0;++const ensureRoot = (family: LayerFamily) => {+ const id = LAYER_ROOT_ID[family];+ const existing = document.getElementById(id);+ if (existing) {+ return existing as HTMLDivElement;+ }++ const root = document.createElement("div");+ root.id = id;+ root.dataset.bbLayerFamily = family;+ root.style.position = "relative";+ root.style.zIndex = String(LAYER_Z_INDEX[family]);+ root.style.isolation = "isolate";++ const nextFamily = ORDERED_FAMILIES.slice(+ ORDERED_FAMILIES.indexOf(family) + 1+ ).find((candidate) => document.getElementById(LAYER_ROOT_ID[candidate]));++ if (nextFamily) {+ document.body.insertBefore(+ root,+ document.getElementById(LAYER_ROOT_ID[nextFamily])+ );+ } else {+ document.body.appendChild(root);+ }++ return root as HTMLDivElement;+};++export const getLayerRoot = (family: LayerFamily) => ensureRoot(family);++export const usePreserveHigherLayerAccess = (family: LayerFamily) => {+ useLayoutEffect(() => {+ const preserveableRoots = HIGHER_LAYER_FAMILIES[family]+ .map((higherFamily) => ({+ family: higherFamily,+ root: getExistingLayerRoot(higherFamily),+ }))+ .filter(+ (entry): entry is { family: LayerFamily; root: HTMLDivElement } =>+ entry.root instanceof HTMLDivElement+ );++ if (preserveableRoots.length === 0) {+ return;+ }++ const shouldRevealRoot = (targetFamily: LayerFamily) =>+ HIGHER_LAYER_FAMILIES[targetFamily].every(+ (higherFamily) => !hasActiveLayerContent(higherFamily)+ );++ const revealRoot = (targetFamily: LayerFamily, root: HTMLDivElement) => {+ if (!shouldRevealRoot(targetFamily)) {+ return;+ }++ for (const attribute of LAYER_ACCESSIBLE_ATTRIBUTES) {+ root.removeAttribute(attribute);+ }+ };++ preserveableRoots.forEach(({ family: targetFamily, root }) => {+ revealRoot(targetFamily, root);+ });++ const observer = new MutationObserver((records) => {+ for (const record of records) {+ if (+ record.attributeName &&+ LAYER_ACCESSIBLE_ATTRIBUTES.includes(+ record.attributeName as (typeof LAYER_ACCESSIBLE_ATTRIBUTES)[number]+ ) &&+ record.target instanceof HTMLDivElement+ ) {+ const targetFamily = record.target.dataset.bbLayerFamily as+ | LayerFamily+ | undefined;+ if (targetFamily) {+ revealRoot(targetFamily, record.target);+ }+ }+ }+ });++ for (const { root } of preserveableRoots) {+ observer.observe(root, {+ attributes: true,+ attributeFilter: [...LAYER_ACCESSIBLE_ATTRIBUTES],+ });+ }++ return () => {+ observer.disconnect();+ };+ }, [family]);+};++// Backdrops and popups share one intra-family stack level so nested modal+// layers can rely on portal mount order: child backdrop above parent surface,+// child popup above child backdrop.+export const LAYER_SURFACE_CLASS = "z-10";+export const LAYER_BACKDROP_CLASS = "z-10";diff --git a/frontend/src/react/components/ui/select.tsx b/frontend/src/react/components/ui/select.tsxindex 1c4be27083..2e14c4007e 100644--- a/frontend/src/react/components/ui/select.tsx+++ b/frontend/src/react/components/ui/select.tsx@@ -2,6 +2,7 @@ import { Select as BaseSelect } from "@base-ui/react/select";import { Check, ChevronDown } from "lucide-react";import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";// ---- Root ----const Select = BaseSelect.Root;@@ -36,13 +37,6 @@ function SelectTrigger({const SelectValue = BaseSelect.Value;// ---- Portal + Positioner + Popup -----// The `z-50` on the Positioner matches the z-index used by Dialog/AlertDialog-// (see ui/dialog.tsx). It must not be removed — Dialog's backdrop/popup are-// hardcoded at z-50, so a Select without an explicit z-index renders *behind*-// any open Dialog regardless of DOM portal order (z-auto loses to z-50).-// Within the same z-layer, stacking falls back to DOM order, which correctly-// puts later-mounted portals (e.g. a Select opened inside a Dialog) on top.-// See BYT-9226 and PR #19824 for the original regression.function SelectContent({className,children,@@ -50,8 +44,8 @@ function SelectContent({...props}: ComponentProps<typeof BaseSelect.Popup>) {return (- <BaseSelect.Portal>- <BaseSelect.Positioner sideOffset={4} className="z-50">+ <BaseSelect.Portal container={getLayerRoot("overlay")}>+ <BaseSelect.Positioner sideOffset={4} className={LAYER_SURFACE_CLASS}><BaseSelect.Popupref={ref}className={cn(diff --git a/frontend/src/react/components/ui/sheet.tsx b/frontend/src/react/components/ui/sheet.tsxindex 646733a65d..2dc33cff02 100644--- a/frontend/src/react/components/ui/sheet.tsx+++ b/frontend/src/react/components/ui/sheet.tsx@@ -3,6 +3,12 @@ import { cva, type VariantProps } from "class-variance-authority";import { X } from "lucide-react";import type { ComponentProps } from "react";import { cn } from "@/react/lib/utils";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+ usePreserveHigherLayerAccess,+} from "./layer";// ---- Root ----// A side sheet is a Dialog whose Popup is pinned to the right edge of the@@ -18,11 +24,6 @@ const SheetTrigger = BaseDialog.Trigger;const SheetClose = BaseDialog.Close;// ---- Backdrop -----// Dialog, Select, Tooltip, AlertDialog, DropdownMenu all share `z-50`. Within-// that layer, stacking falls back to DOM portal mount order — later mounts-// win — which correctly places a Select/Tooltip opened *inside* a Sheet on-// top of the sheet backdrop. Do not bump Sheet above z-50 (or other overlays-// below) without updating all siblings together. See BYT-9226 / PR #19824.function SheetOverlay({className,ref,@@ -32,7 +33,7 @@ function SheetOverlay({<BaseDialog.Backdropref={ref}className={cn(- "fixed inset-0 z-50 bg-overlay/50",+ `fixed inset-0 ${LAYER_BACKDROP_CLASS} bg-overlay/50`,"data-[starting-style]:opacity-0 data-[ending-style]:opacity-0","transition-opacity duration-200",className@@ -81,12 +82,18 @@ function SheetContent({ref,...props}: SheetContentProps) {+ usePreserveHigherLayerAccess("overlay");+return (- <BaseDialog.Portal>+ <BaseDialog.Portal container={getLayerRoot("overlay")}><SheetOverlay /><BaseDialog.Popupref={ref}- className={cn(sheetContentVariants({ width }), className)}+ className={cn(+ sheetContentVariants({ width }),+ LAYER_SURFACE_CLASS,+ className+ )}{...props}>{children}diff --git a/frontend/src/react/components/ui/tooltip.test.tsx b/frontend/src/react/components/ui/tooltip.test.tsxindex ed7b31c38d..107965882b 100644--- a/frontend/src/react/components/ui/tooltip.test.tsx+++ b/frontend/src/react/components/ui/tooltip.test.tsx@@ -13,9 +13,8 @@ describe("Tooltip", () => {document.body.innerHTML = "";});- test("applies the overlay z-layer to the tooltip positioner", async () => {+ test("mounts tooltip content into the overlay layer root", async () => {vi.useFakeTimers();-const container = document.createElement("div");document.body.appendChild(container);const root = createRoot(container);@@ -36,9 +35,9 @@ describe("Tooltip", () => {vi.advanceTimersByTime(100);});- expect(document.body.textContent).toContain("Tip content");- const positioner = document.body.querySelector('[role="presentation"]');- expect(positioner?.className).toContain("z-50");+ const overlayRoot = document.getElementById("bb-react-layer-overlay");+ expect(overlayRoot).toBeInstanceOf(HTMLDivElement);+ expect(overlayRoot?.textContent).toContain("Tip content");act(() => {root.unmount();diff --git a/frontend/src/react/components/ui/tooltip.tsx b/frontend/src/react/components/ui/tooltip.tsxindex cc1a608041..040ef534ef 100644--- a/frontend/src/react/components/ui/tooltip.tsx+++ b/frontend/src/react/components/ui/tooltip.tsx@@ -1,5 +1,6 @@import { Tooltip as BaseTooltip } from "@base-ui/react/tooltip";import type { ReactNode } from "react";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";interface TooltipProps {readonly content: ReactNode;@@ -24,8 +25,12 @@ export function Tooltip({<BaseTooltip.Trigger render={<span className="inline-flex" />}>{children}</BaseTooltip.Trigger>- <BaseTooltip.Portal>- <BaseTooltip.Positioner side={side} sideOffset={4} className="z-50">+ <BaseTooltip.Portal container={getLayerRoot("overlay")}>+ <BaseTooltip.Positioner+ side={side}+ sideOffset={4}+ className={LAYER_SURFACE_CLASS}+ ><BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">{content}<BaseTooltip.Arrow className="fill-main" />@@ -58,8 +63,12 @@ export function BlockTooltip({<BaseTooltip.Trigger render={<div className="flex-1 min-w-0" />}>{children}</BaseTooltip.Trigger>- <BaseTooltip.Portal>- <BaseTooltip.Positioner side={side} sideOffset={4} className="z-50">+ <BaseTooltip.Portal container={getLayerRoot("overlay")}>+ <BaseTooltip.Positioner+ side={side}+ sideOffset={4}+ className={LAYER_SURFACE_CLASS}+ ><BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">{content}<BaseTooltip.Arrow className="fill-main" />diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 86b6f827a3..e7932e15d7 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -95,6 +95,7 @@"status": "Status"}},+ "auth.token-expired-title": "Token expired","banner": {"external-url": "Bytebase has not configured --external-url"},@@ -366,6 +367,7 @@"common.line": "Line","common.load-more": "Load more","common.loading": "Loading",+ "common.logout": "Logout","common.members": "Members","common.minutes": "Minutes","common.n-more": "{{n}} more",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 78e9777e5f..9948e88312 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -95,6 +95,7 @@"status": "Estado"}},+ "auth.token-expired-title": "Token expirado","banner": {"external-url": "Bytebase no ha configurado --external-url"},@@ -366,6 +367,7 @@"common.line": "Línea","common.load-more": "Cargar más","common.loading": "Cargando",+ "common.logout": "Cerrar sesión","common.members": "Miembros","common.minutes": "Minutos","common.n-more": "{{n}} más",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 2df96113c3..39d6eeb0bb 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -95,6 +95,7 @@"status": "ステータス"}},+ "auth.token-expired-title": "トークンの期限切れ","banner": {"external-url": "Bytebase は --extern-url を設定していません"},@@ -366,6 +367,7 @@"common.line": "行","common.load-more": "さらに読み込む","common.loading": "読み込み中",+ "common.logout": "サインアウト","common.members": "メンバー","common.minutes": "分","common.n-more": "あと {{n}} 件",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 0b31ed5eb2..400aba6517 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -95,6 +95,7 @@"status": "Trạng thái"}},+ "auth.token-expired-title": "Mã thông báo đã hết hạn","banner": {"external-url": "Bytebase chưa được cấu hình --external-url"},@@ -366,6 +367,7 @@"common.line": "Dòng","common.load-more": "Tải thêm","common.loading": "Đang tải",+ "common.logout": "Đăng xuất","common.members": "Thành viên","common.minutes": "Phút","common.n-more": "còn {{n}}",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex e7d278ac93..30740fa870 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -95,6 +95,7 @@"status": "状态"}},+ "auth.token-expired-title": "令牌已过期","banner": {"external-url": "Bytebase 还没有配置 --external-url"},@@ -366,6 +367,7 @@"common.line": "行","common.load-more": "加载更多","common.loading": "加载中",+ "common.logout": "登出","common.members": "成员","common.minutes": "分钟","common.n-more": "还有 {{n}} 个",diff --git a/frontend/src/react/mount.test.ts b/frontend/src/react/mount.test.tsnew file mode 100644index 0000000000..f31c7fdf37--- /dev/null+++ b/frontend/src/react/mount.test.ts@@ -0,0 +1,14 @@+import { describe, expect, test } from "vitest";+import { resolveReactPagePath } from "./mount";++describe("resolveReactPagePath", () => {+ test("resolves the session expired surface entry", () => {+ expect(resolveReactPagePath("SessionExpiredSurface")).toBe(+ "./components/auth/SessionExpiredSurface.tsx"+ );+ });++ test("does not resolve auth test modules as runtime pages", () => {+ expect(resolveReactPagePath("SessionExpiredSurface.test")).toBeUndefined();+ });+});diff --git a/frontend/src/react/mount.ts b/frontend/src/react/mount.tsindex 8e0cb3e9f0..94f9619f81 100644--- a/frontend/src/react/mount.ts+++ b/frontend/src/react/mount.ts@@ -6,11 +6,15 @@ const pluginComponentLoaders = import.meta.glob("./plugins/agent/components/AgentWindow.tsx");const workspacePageLoaders = import.meta.glob("./pages/workspace/*.tsx");+const authComponentLoaders = import.meta.glob(+ "./components/auth/SessionExpiredSurface.tsx"+);const pageLoaders = {...settingsPageLoaders,...projectPageLoaders,...pluginComponentLoaders,...workspacePageLoaders,+ ...authComponentLoaders,};// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc@@ -50,17 +54,28 @@ const pageDirs = ["./pages/project","./plugins/agent/components","./pages/workspace",+ "./components/auth",];-async function loadPage(name: string): Promise<ReactComponent> {- const hit = cachedPages.get(name);- if (hit) return hit;- let loader: (() => Promise<Record<string, unknown>>) | undefined;+export function resolveReactPagePath(name: string): string | undefined {for (const dir of pageDirs) {const path = `${dir}/${name}.tsx`;- loader = pageLoaders[path] as typeof loader;- if (loader) break;+ if (path in pageLoaders) {+ return path;+ }}+ return undefined;+}++async function loadPage(name: string): Promise<ReactComponent> {+ const hit = cachedPages.get(name);+ if (hit) return hit;+ const path = resolveReactPagePath(name);+ const loader = path+ ? (pageLoaders[path] as+ | (() => Promise<Record<string, unknown>>)+ | undefined)+ : undefined;if (!loader) throw new Error(`Unknown React page: ${name}`);const mod = await loader();const Component = mod[name] as ReactComponent;diff --git a/frontend/src/react/plugins/agent/components/AgentInput.test.tsx b/frontend/src/react/plugins/agent/components/AgentInput.test.tsxindex 1b20bf2343..607a4a124d 100644--- a/frontend/src/react/plugins/agent/components/AgentInput.test.tsx+++ b/frontend/src/react/plugins/agent/components/AgentInput.test.tsx@@ -2,6 +2,7 @@ import type { ReactElement } from "react";import { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type { DomRefSuggestion } from "../dom";import { createAgentStore, useAgentStore } from "../store/agent";(@@ -13,7 +14,9 @@ const mocks = vi.hoisted(() => ({t: (key: string) => key,})),routerPush: vi.fn(),- lazyExtractDomRefSuggestions: vi.fn(async () => []),+ lazyExtractDomRefSuggestions: vi.fn<() => Promise<DomRefSuggestion[]>>(+ async () => []+ ),runAgentLoop: vi.fn(),isAgentAIConfigurationError: vi.fn(() => false),buildOutboundHistory: vi.fn(() => []),@@ -90,6 +93,7 @@ vi.mock("../logic/tools", () => ({const renderIntoContainer = (element: ReactElement) => {const container = document.createElement("div");+ document.body.appendChild(container);const root = createRoot(container);return {@@ -102,6 +106,7 @@ const renderIntoContainer = (element: ReactElement) => {unmount: () =>act(() => {root.unmount();+ container.remove();}),};};@@ -114,6 +119,35 @@ const setTextareaValue = (textarea: HTMLTextAreaElement, value: string) => {descriptor?.set?.call(textarea, value);};+const stubAnimationFrames = () => {+ let nextFrameId = 0;+ const callbacks = new Map<number, FrameRequestCallback>();++ vi.stubGlobal(+ "requestAnimationFrame",+ vi.fn((callback: FrameRequestCallback) => {+ const frameId = ++nextFrameId;+ callbacks.set(frameId, callback);+ return frameId;+ })+ );+ vi.stubGlobal(+ "cancelAnimationFrame",+ vi.fn((frameId: number) => {+ callbacks.delete(frameId);+ })+ );++ return async () => {+ const currentCallbacks = [...callbacks.values()];+ callbacks.clear();++ await act(async () => {+ currentCallbacks.forEach((callback) => callback(performance.now()));+ });+ };+};+beforeEach(async () => {vi.stubGlobal("localStorage", createMockStorage());useAgentStore.setState(createAgentStore().getState(), true);@@ -145,6 +179,106 @@ afterEach(() => {});describe("AgentInput", () => {+ test("mounts mention suggestions into the agent layer root", async () => {+ const suggestions: DomRefSuggestion[] = [+ {+ ref: "button.submit",+ tag: "BUTTON",+ role: "button",+ label: "Submit",+ value: "",+ },+ ];+ mocks.lazyExtractDomRefSuggestions.mockResolvedValue(suggestions);++ const { render, unmount } = renderIntoContainer(<AgentInput />);++ render();++ const textarea = document.body.querySelector(+ "textarea"+ ) as HTMLTextAreaElement;++ await act(async () => {+ setTextareaValue(textarea, "@");+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });++ const agentRoot = document.getElementById("bb-react-layer-agent");+ expect(agentRoot?.querySelector("[data-agent-mention-list]")).toBeTruthy();++ unmount();+ });++ test("repositions mention suggestions when the textarea rect changes", async () => {+ const suggestions: DomRefSuggestion[] = [+ {+ ref: "button.submit",+ tag: "BUTTON",+ role: "button",+ label: "Submit",+ value: "",+ },+ ];+ mocks.lazyExtractDomRefSuggestions.mockResolvedValue(suggestions);+ const flushAnimationFrame = stubAnimationFrames();++ const { render, unmount } = renderIntoContainer(<AgentInput />);++ render();++ const textarea = document.body.querySelector(+ "textarea"+ ) as HTMLTextAreaElement;++ let rect = {+ bottom: 234,+ height: 34,+ left: 100,+ right: 400,+ top: 200,+ width: 300,+ x: 100,+ y: 200,+ toJSON: () => "",+ };+ vi.spyOn(textarea, "getBoundingClientRect").mockImplementation(+ () => rect as DOMRect+ );++ await act(async () => {+ setTextareaValue(textarea, "@");+ textarea.setSelectionRange(1, 1);+ textarea.dispatchEvent(new Event("input", { bubbles: true }));+ });++ const mentionList = document.body.querySelector(+ "[data-agent-mention-list]"+ ) as HTMLDivElement;+ expect(mentionList.style.left).toBe("100px");+ expect(mentionList.style.top).toBe("196px");+ expect(mentionList.style.width).toBe("300px");++ rect = {+ ...rect,+ bottom: 294,+ left: 160,+ right: 440,+ top: 260,+ width: 280,+ x: 160,+ y: 260,+ };++ await flushAnimationFrame();++ expect(mentionList.style.left).toBe("160px");+ expect(mentionList.style.top).toBe("256px");+ expect(mentionList.style.width).toBe("280px");++ unmount();+ });+test("shows a single-line overlay placeholder and hides it when typing", () => {const { container, render, unmount } = renderIntoContainer(<AgentInput />);diff --git a/frontend/src/react/plugins/agent/components/AgentInput.tsx b/frontend/src/react/plugins/agent/components/AgentInput.tsxindex 0b48c4813f..647c8119da 100644--- a/frontend/src/react/plugins/agent/components/AgentInput.tsx+++ b/frontend/src/react/plugins/agent/components/AgentInput.tsx@@ -1,7 +1,17 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type CSSProperties,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { Button } from "@/react/components/ui/button";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";import { router } from "@/router";import type { DomRefSuggestion } from "../dom";import { lazyExtractDomRefSuggestions } from "../dom";@@ -70,6 +80,16 @@ const getCurrentPageSnapshot = () => ({title: document.title,});+const buildMentionListStyle = (rect: DOMRect): CSSProperties => ({+ left: rect.left,+ top: rect.top - 4,+ transform: "translateY(-100%)",+ width: rect.width,+});++const getMentionListStyleKey = (rect: DOMRect) =>+ `${rect.left}:${rect.top}:${rect.width}`;+// ---------------------------------------------------------------------------// Component// ---------------------------------------------------------------------------@@ -101,9 +121,12 @@ export function AgentInput() {>([]);const [isMentionOpen, setIsMentionOpen] = useState(false);const [highlightIndex, setHighlightIndex] = useState(0);+ const [mentionListStyle, setMentionListStyle] =+ useState<CSSProperties | null>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);const mentionListRef = useRef<HTMLDivElement>(null);+ const mentionListStyleKeyRef = useRef<string | null>(null);// Derived valuesconst isInterrupted = Boolean(currentChat?.interrupted);@@ -155,6 +178,44 @@ export function AgentInput() {// Show/hide mention popoverconst showMention = isMentionOpen && mentionOptions.length > 0;+ useLayoutEffect(() => {+ if (!showMention) {+ mentionListStyleKeyRef.current = null;+ setMentionListStyle(null);+ return;+ }++ let isCancelled = false;+ let frameId = 0;++ const updateMentionListPosition = () => {+ const rect = textareaRef.current?.getBoundingClientRect();+ if (!rect) {+ if (mentionListStyleKeyRef.current !== null) {+ mentionListStyleKeyRef.current = null;+ setMentionListStyle(null);+ }+ } else {+ const nextStyleKey = getMentionListStyleKey(rect);+ if (nextStyleKey !== mentionListStyleKeyRef.current) {+ mentionListStyleKeyRef.current = nextStyleKey;+ setMentionListStyle(buildMentionListStyle(rect));+ }+ }++ if (!isCancelled) {+ frameId = requestAnimationFrame(updateMentionListPosition);+ }+ };++ updateMentionListPosition();++ return () => {+ isCancelled = true;+ cancelAnimationFrame(frameId);+ };+ }, [showMention]);+// Reset highlight when options changeuseEffect(() => {setHighlightIndex(0);@@ -712,48 +773,53 @@ export function AgentInput() {/>{/* Mention popover */}- {showMention && (- <div- ref={mentionListRef}- className="absolute bottom-full left-0 z-50 mb-1 max-h-80 w-full overflow-y-auto rounded-xs border bg-background shadow-lg"- >- {mentionOptions.map((option, index) => {- const meta = formatDomRefSuggestionMeta(option.suggestion);- return (- <div- key={option.value}- data-mention-option- className={`cursor-pointer px-3 py-2 ${- index === highlightIndex- ? "bg-accent/10"- : "hover:bg-control-bg"- }`}- onMouseDown={(e) => {- e.preventDefault();- selectMention(option);- }}- onMouseEnter={() => setHighlightIndex(index)}- >- <div className="flex flex-col text-sm">- <div className="flex items-center gap-x-2 text-main">- <span className="font-medium">- [{option.suggestion.ref}]- </span>- <span className="truncate">- {option.suggestion.label}- </span>- </div>- {meta && (- <div className="mt-1 text-xs text-control-light">- {meta}+ {showMention &&+ mentionListStyle &&+ createPortal(+ <div+ ref={mentionListRef}+ data-agent-mention-list+ className={`fixed ${LAYER_SURFACE_CLASS} max-h-80 overflow-y-auto rounded-xs border bg-background shadow-lg`}+ style={mentionListStyle}+ >+ {mentionOptions.map((option, index) => {+ const meta = formatDomRefSuggestionMeta(option.suggestion);+ return (+ <div+ key={option.value}+ data-mention-option+ className={`cursor-pointer px-3 py-2 ${+ index === highlightIndex+ ? "bg-accent/10"+ : "hover:bg-control-bg"+ }`}+ onMouseDown={(e) => {+ e.preventDefault();+ selectMention(option);+ }}+ onMouseEnter={() => setHighlightIndex(index)}+ >+ <div className="flex flex-col text-sm">+ <div className="flex items-center gap-x-2 text-main">+ <span className="font-medium">+ [{option.suggestion.ref}]+ </span>+ <span className="truncate">+ {option.suggestion.label}+ </span></div>- )}+ {meta && (+ <div className="mt-1 text-xs text-control-light">+ {meta}+ </div>+ )}+ </div></div>- </div>- );- })}- </div>- )}+ );+ })}+ </div>,+ getLayerRoot("agent")+ )}</div>{loading ? (diff --git a/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx b/frontend/src/react/plugins/agent/components/AgentWindow.test.tsxindex 1dfdd3f0cf..9d91eb268d 100644--- a/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx+++ b/frontend/src/react/plugins/agent/components/AgentWindow.test.tsx@@ -128,12 +128,137 @@ beforeEach(async () => {});afterEach(() => {+ vi.useRealTimers();vi.unstubAllGlobals();document.body.innerHTML = "";});describe("AgentWindow", () => {- test("selects the next archived chat after deleting the current archived chat", () => {+ test("mounts the agent shell into the agent layer root", () => {+ const { render, unmount } = renderIntoContainer(<AgentWindow />);++ render();++ const agentRoot = document.getElementById("bb-react-layer-agent");+ expect(agentRoot).toBeInstanceOf(HTMLDivElement);+ expect(agentRoot?.querySelector("[data-agent-window]")).toBeInstanceOf(+ HTMLDivElement+ );++ unmount();+ });++ test("mounts agent menu and delete dialog into the agent layer root", async () => {+ const archivedChat = useAgentStore.getState().createChat({+ title: "Archived chat",+ archived: true,+ select: false,+ });++ useAgentStore.setState({+ chats: useAgentStore.getState().chats.map((chat) => {+ if (chat.id === archivedChat.id) {+ return { ...chat, updatedTs: 2000 };+ }+ return chat;+ }),+ });++ const { render, unmount } = renderIntoContainer(<AgentWindow />);++ render();++ const moreButton = document.body.querySelector(+ "[aria-label='common.more']"+ ) as HTMLButtonElement | null;++ act(() => {+ moreButton?.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });++ const agentRoot = document.getElementById("bb-react-layer-agent");+ const overlayRoot = document.getElementById("bb-react-layer-overlay");++ expect(+ agentRoot?.querySelector("[data-agent-dropdown-menu-content]")+ ).toBeInstanceOf(HTMLDivElement);+ expect(+ agentRoot?.querySelector("[data-agent-chat-list-mode]")+ ).toBeInstanceOf(HTMLDivElement);+ expect(+ overlayRoot?.querySelector("[data-agent-dropdown-menu-content]") ?? null+ ).toBeNull();++ const archivedModeButton = document.body.querySelector(+ "[data-agent-chat-list-mode]"+ ) as HTMLDivElement | null;++ await act(async () => {+ archivedModeButton?.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ await Promise.resolve();+ });++ const deleteButton = document.body.querySelector(+ "[data-agent-delete-chat]"+ ) as HTMLButtonElement | null;++ await act(async () => {+ deleteButton?.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ await Promise.resolve();+ });++ expect(+ agentRoot?.querySelector("[data-agent-dialog-content]")+ ).toBeInstanceOf(HTMLDivElement);+ expect(+ agentRoot?.textContent?.includes("agent.delete-chat-confirmation")+ ).toBe(true);+ expect(+ overlayRoot?.querySelector("[data-agent-dialog-content]") ?? null+ ).toBeNull();++ unmount();+ });++ test("mounts agent tooltip content into the agent layer root", async () => {+ vi.useFakeTimers();++ const { render, unmount } = renderIntoContainer(<AgentWindow />);++ render();++ const trigger = document.body.querySelector(+ "[aria-label='agent.new-chat']"+ ) as HTMLButtonElement | null;++ expect(trigger).toBeInstanceOf(HTMLButtonElement);++ await act(async () => {+ trigger?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));+ vi.advanceTimersByTime(100);+ });++ const agentRoot = document.getElementById("bb-react-layer-agent");+ const overlayRoot = document.getElementById("bb-react-layer-overlay");++ expect(+ agentRoot?.querySelector("[data-agent-tooltip-content]")+ ).toBeInstanceOf(HTMLDivElement);+ expect(agentRoot?.textContent).toContain("agent.new-chat");+ expect(+ overlayRoot?.querySelector("[data-agent-tooltip-content]") ?? null+ ).toBeNull();++ unmount();+ });++ test("selects the next archived chat after deleting the current archived chat", async () => {const activeChatId = useAgentStore.getState().currentChatId!;const firstArchivedChat = useAgentStore.getState().createChat({title: "First archived",@@ -180,10 +305,11 @@ describe("AgentWindow", () => {"[data-agent-chat-list-mode]") as HTMLDivElement | null;- act(() => {+ await act(async () => {archivedModeButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));+ await Promise.resolve();});const deleteButtons = Array.from(diff --git a/frontend/src/react/plugins/agent/components/AgentWindow.tsx b/frontend/src/react/plugins/agent/components/AgentWindow.tsxindex e970696982..5848b3a520 100644--- a/frontend/src/react/plugins/agent/components/AgentWindow.tsx+++ b/frontend/src/react/plugins/agent/components/AgentWindow.tsx@@ -11,23 +11,8 @@ import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/react/components/HumanizeTs";import { Button } from "@/react/components/ui/button";-import {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogTitle,- DialogTrigger,-} from "@/react/components/ui/dialog";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/react/components/ui/dropdown-menu";import { Input } from "@/react/components/ui/input";-import { Tooltip } from "@/react/components/ui/tooltip";+import { getLayerRoot } from "@/react/components/ui/layer";import { cn } from "@/react/lib/utils";import type { AgentChat as AgentChatRecord } from "../logic/types";import {@@ -49,6 +34,22 @@ import {RESIZE_POINTER_MEDIA_QUERY,supportsWindowBorderResize,} from "./resize-capability";+import {+ AgentDialog,+ AgentDialogClose,+ AgentDialogContent,+ AgentDialogDescription,+ AgentDialogTitle,+ AgentDialogTrigger,+} from "./ui/AgentDialog";+import {+ AgentDropdownMenu,+ AgentDropdownMenuContent,+ AgentDropdownMenuItem,+ AgentDropdownMenuSeparator,+ AgentDropdownMenuTrigger,+} from "./ui/AgentDropdownMenu";+import { AgentTooltip } from "./ui/AgentTooltip";import {type ResizeBounds,type ResizeDirection,@@ -888,7 +889,7 @@ export function AgentWindow() {return createPortal(<divdata-agent-window- className="fixed bottom-4 right-4 z-40 flex size-10 cursor-pointer items-center justify-center rounded-full bg-accent text-accent-text shadow-lg hover:bg-accent-hover"+ className="fixed bottom-4 right-4 flex size-10 cursor-pointer items-center justify-center rounded-full bg-accent text-accent-text shadow-lg hover:bg-accent-hover"onClick={() => useAgentStore.getState().restore()}><svg@@ -904,7 +905,7 @@ export function AgentWindow() {/></svg></div>,- document.body+ getLayerRoot("agent"));}@@ -912,27 +913,29 @@ export function AgentWindow() {<divref={windowRef}data-agent-window- className="fixed z-40 overflow-visible"+ className="fixed overflow-visible"style={windowStyle}>- <Dialog+ <AgentDialogopen={isDeleteAllArchivedChatsDialogOpen}onOpenChange={setIsDeleteAllArchivedChatsDialogOpen}>- <DialogContent className="max-w-sm p-6">- <DialogTitle className="sr-only">{t("common.confirm")}</DialogTitle>- <DialogDescription>+ <AgentDialogContent className="max-w-sm p-6">+ <AgentDialogTitle className="sr-only">+ {t("common.confirm")}+ </AgentDialogTitle>+ <AgentDialogDescription>{t("agent.delete-all-chats-confirmation")}- </DialogDescription>+ </AgentDialogDescription><div className="mt-6 flex justify-end gap-x-2">- <DialogClose+ <AgentDialogCloserender={<Button variant="outline" type="button">{t("common.cancel")}</Button>}/>- <DialogClose+ <AgentDialogCloserender={<Button type="button" variant="destructive">{t("common.confirm")}@@ -941,8 +944,8 @@ export function AgentWindow() {onClick={deleteAllArchivedChats}/></div>- </DialogContent>- </Dialog>+ </AgentDialogContent>+ </AgentDialog><div className="flex size-full flex-col overflow-hidden rounded-lg border border-block-border bg-background shadow-xl">{/* Header */}<div@@ -1008,7 +1011,7 @@ export function AgentWindow() {className="flex items-center gap-x-2"data-agent-chat-sidebar-actions>- <Tooltip content={t("agent.new-chat")}>+ <AgentTooltip content={t("agent.new-chat")}><Buttonvariant="outline"size="icon"@@ -1019,10 +1022,10 @@ export function AgentWindow() {><Plus className="size-4" aria-hidden="true" /></Button>- </Tooltip>- <DropdownMenu>- <Tooltip content={t("common.more")}>- <DropdownMenuTrigger+ </AgentTooltip>+ <AgentDropdownMenu>+ <AgentTooltip content={t("common.more")}>+ <AgentDropdownMenuTriggerclassName="inline-flex size-7 items-center justify-center rounded-xs border border-control-border bg-transparent text-control-light outline-hidden hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent disabled:pointer-events-none disabled:opacity-50"aria-label={t("common.more")}onClick={(event) => event.stopPropagation()}@@ -1031,12 +1034,12 @@ export function AgentWindow() {className="size-4"aria-hidden="true"/>- </DropdownMenuTrigger>- </Tooltip>- <DropdownMenuContent>+ </AgentDropdownMenuTrigger>+ </AgentTooltip>+ <AgentDropdownMenuContent>{showArchivedOnly ? (<>- <DropdownMenuItem+ <AgentDropdownMenuItemdata-agent-unarchive-all-chatsdisabled={isUnarchiveAllDisabled}onClick={(event) => {@@ -1045,8 +1048,8 @@ export function AgentWindow() {}}>{t("agent.unarchive-all-chats")}- </DropdownMenuItem>- <DropdownMenuItem+ </AgentDropdownMenuItem>+ <AgentDropdownMenuItemdata-agent-delete-all-chatsclassName="text-error data-highlighted:bg-red-50"disabled={isDeleteAllDisabled}@@ -1056,10 +1059,10 @@ export function AgentWindow() {}}>{t("agent.delete-all-chats")}- </DropdownMenuItem>+ </AgentDropdownMenuItem></>) : (- <DropdownMenuItem+ <AgentDropdownMenuItemdata-agent-archive-all-chatsdisabled={isArchiveAllDisabled}onClick={(event) => {@@ -1068,10 +1071,10 @@ export function AgentWindow() {}}>{t("agent.archive-all-chats")}- </DropdownMenuItem>+ </AgentDropdownMenuItem>)}- <DropdownMenuSeparator />- <DropdownMenuItem+ <AgentDropdownMenuSeparator />+ <AgentDropdownMenuItemdata-agent-chat-list-modeonClick={(event) => {event.stopPropagation();@@ -1081,9 +1084,9 @@ export function AgentWindow() {{showArchivedOnly? t("agent.active-only-chats"): t("agent.archived-only-chats")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ </AgentDropdownMenuItem>+ </AgentDropdownMenuContent>+ </AgentDropdownMenu></div></div></div>@@ -1228,7 +1231,7 @@ export function AgentWindow() {))}</div>,- document.body+ getLayerRoot("agent"));}@@ -1254,8 +1257,8 @@ function ConfirmDialog({if (triggerDataAttr) triggerProps[triggerDataAttr] = true;return (- <Dialog>- <DialogTrigger+ <AgentDialog>+ <AgentDialogTriggerrender={triggerVariant === "icon" ? (<Button@@ -1276,23 +1279,27 @@ function ConfirmDialog({}>{triggerVariant === "icon" ? (- <Tooltip content={triggerLabel}>{children}</Tooltip>+ <AgentTooltip content={triggerLabel}>{children}</AgentTooltip>) : (triggerLabel)}- </DialogTrigger>- <DialogContent className="max-w-sm p-6">- <DialogTitle className="sr-only">{t("common.confirm")}</DialogTitle>- <DialogDescription className="mb-4">{message}</DialogDescription>+ </AgentDialogTrigger>+ <AgentDialogContent className="max-w-sm p-6">+ <AgentDialogTitle className="sr-only">+ {t("common.confirm")}+ </AgentDialogTitle>+ <AgentDialogDescription className="mb-4">+ {message}+ </AgentDialogDescription><div className="flex justify-end gap-x-2">- <DialogClose+ <AgentDialogCloserender={<button className="rounded-xs border px-3 py-1.5 text-sm font-medium text-control-light hover:bg-control-bg">{t("common.cancel")}</button>}/>- <DialogClose+ <AgentDialogCloserender={<buttonclassName="rounded-xs bg-accent px-3 py-1.5 text-sm font-medium text-accent-text hover:bg-accent-hover"@@ -1303,8 +1310,8 @@ function ConfirmDialog({}/></div>- </DialogContent>- </Dialog>+ </AgentDialogContent>+ </AgentDialog>);}@@ -1327,7 +1334,7 @@ function SidebarIconButton({if (dataAttr) dataProps[dataAttr] = true;return (- <Tooltip content={tooltip}>+ <AgentTooltip content={tooltip}><Buttonvariant="ghost"size="icon"@@ -1341,6 +1348,6 @@ function SidebarIconButton({>{children}</Button>- </Tooltip>+ </AgentTooltip>);}diff --git a/frontend/src/react/plugins/agent/components/ui/AgentDialog.tsx b/frontend/src/react/plugins/agent/components/ui/AgentDialog.tsxnew file mode 100644index 0000000000..d0dd116c4b--- /dev/null+++ b/frontend/src/react/plugins/agent/components/ui/AgentDialog.tsx@@ -0,0 +1,86 @@+import { Dialog as BaseDialog } from "@base-ui/react/dialog";+import type { ComponentProps } from "react";+import {+ getLayerRoot,+ LAYER_BACKDROP_CLASS,+ LAYER_SURFACE_CLASS,+} from "@/react/components/ui/layer";+import { cn } from "@/react/lib/utils";++export const AgentDialog = BaseDialog.Root;++export const AgentDialogTrigger = BaseDialog.Trigger;++function AgentDialogOverlay({+ className,+ ref,+ ...props+}: ComponentProps<typeof BaseDialog.Backdrop>) {+ return (+ <BaseDialog.Backdrop+ ref={ref}+ className={cn(+ `fixed inset-0 ${LAYER_BACKDROP_CLASS} bg-overlay/50`,+ className+ )}+ {...props}+ />+ );+}++export function AgentDialogContent({+ className,+ children,+ ref,+ ...props+}: ComponentProps<typeof BaseDialog.Popup>) {+ return (+ <BaseDialog.Portal container={getLayerRoot("agent")}>+ <AgentDialogOverlay />+ <BaseDialog.Popup+ ref={ref}+ data-agent-dialog-content+ className={cn(+ `fixed left-1/2 top-1/2 ${LAYER_SURFACE_CLASS} -translate-x-1/2 -translate-y-1/2`,+ "w-[calc(100vw-8rem)] max-w-3xl 2xl:max-w-[55vw]",+ "max-h-[calc(100vh-10rem)] overflow-y-auto",+ "rounded-sm bg-background shadow-lg",+ className+ )}+ {...props}+ >+ {children}+ </BaseDialog.Popup>+ </BaseDialog.Portal>+ );+}++export function AgentDialogTitle({+ className,+ ref,+ ...props+}: ComponentProps<typeof BaseDialog.Title>) {+ return (+ <BaseDialog.Title+ ref={ref}+ className={cn("text-lg font-semibold", className)}+ {...props}+ />+ );+}++export function AgentDialogDescription({+ className,+ ref,+ ...props+}: ComponentProps<typeof BaseDialog.Description>) {+ return (+ <BaseDialog.Description+ ref={ref}+ className={cn("text-sm text-control-light", className)}+ {...props}+ />+ );+}++export const AgentDialogClose = BaseDialog.Close;diff --git a/frontend/src/react/plugins/agent/components/ui/AgentDropdownMenu.tsx b/frontend/src/react/plugins/agent/components/ui/AgentDropdownMenu.tsxnew file mode 100644index 0000000000..150adb378e--- /dev/null+++ b/frontend/src/react/plugins/agent/components/ui/AgentDropdownMenu.tsx@@ -0,0 +1,85 @@+import { Menu as BaseMenu } from "@base-ui/react/menu";+import type { ComponentProps } from "react";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";+import { cn } from "@/react/lib/utils";++export function AgentDropdownMenu({+ modal = false,+ ...props+}: ComponentProps<typeof BaseMenu.Root>) {+ return <BaseMenu.Root modal={modal} {...props} />;+}++export const AgentDropdownMenuTrigger = BaseMenu.Trigger;++export function AgentDropdownMenuContent({+ className,+ children,+ sideOffset = 4,+ align = "end",+ ref,+ ...props+}: ComponentProps<typeof BaseMenu.Popup> & {+ sideOffset?: ComponentProps<typeof BaseMenu.Positioner>["sideOffset"];+ align?: ComponentProps<typeof BaseMenu.Positioner>["align"];+}) {+ return (+ <BaseMenu.Portal container={getLayerRoot("agent")}>+ <BaseMenu.Positioner+ sideOffset={sideOffset}+ align={align}+ className={LAYER_SURFACE_CLASS}+ >+ <BaseMenu.Popup+ ref={ref}+ data-agent-dropdown-menu-content+ className={cn(+ "min-w-[10rem] overflow-hidden rounded-sm border border-control-border bg-background py-1 shadow-md",+ "focus:outline-hidden",+ className+ )}+ {...props}+ >+ {children}+ </BaseMenu.Popup>+ </BaseMenu.Positioner>+ </BaseMenu.Portal>+ );+}++export function AgentDropdownMenuItem({+ className,+ children,+ ref,+ ...props+}: ComponentProps<typeof BaseMenu.Item>) {+ return (+ <BaseMenu.Item+ ref={ref}+ className={cn(+ "relative flex cursor-pointer items-center gap-x-2 px-3 py-2 text-sm select-none",+ "hover:bg-control-bg focus:bg-control-bg outline-hidden",+ "data-highlighted:bg-control-bg",+ "data-disabled:pointer-events-none data-disabled:opacity-50",+ className+ )}+ {...props}+ >+ {children}+ </BaseMenu.Item>+ );+}++export function AgentDropdownMenuSeparator({+ className,+ ref,+ ...props+}: ComponentProps<typeof BaseMenu.Separator>) {+ return (+ <BaseMenu.Separator+ ref={ref}+ className={cn("-mx-1 my-1 h-px bg-control-border", className)}+ {...props}+ />+ );+}diff --git a/frontend/src/react/plugins/agent/components/ui/AgentTooltip.tsx b/frontend/src/react/plugins/agent/components/ui/AgentTooltip.tsxnew file mode 100644index 0000000000..321e703a7f--- /dev/null+++ b/frontend/src/react/plugins/agent/components/ui/AgentTooltip.tsx@@ -0,0 +1,46 @@+import { Tooltip as BaseTooltip } from "@base-ui/react/tooltip";+import type { ReactNode } from "react";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";++interface TooltipProps {+ readonly content: ReactNode;+ readonly children: ReactNode;+ readonly side?: "top" | "bottom" | "left" | "right";+ readonly delayDuration?: number;+}++export function AgentTooltip({+ content,+ children,+ side = "top",+ delayDuration = 100,+}: TooltipProps) {+ if (!content) {+ return <>{children}</>;+ }++ return (+ <BaseTooltip.Provider delay={delayDuration}>+ <BaseTooltip.Root>+ <BaseTooltip.Trigger render={<span className="inline-flex" />}>+ {children}+ </BaseTooltip.Trigger>+ <BaseTooltip.Portal container={getLayerRoot("agent")}>+ <BaseTooltip.Positioner+ side={side}+ sideOffset={4}+ className={LAYER_SURFACE_CLASS}+ >+ <BaseTooltip.Popup+ data-agent-tooltip-content+ className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md"+ >+ {content}+ <BaseTooltip.Arrow className="fill-main" />+ </BaseTooltip.Popup>+ </BaseTooltip.Positioner>+ </BaseTooltip.Portal>+ </BaseTooltip.Root>+ </BaseTooltip.Provider>+ );+}