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(frontend): separate self-service account settings from admin recovery (#21193)
Danny Xufd4ef828e687
diff --git a/frontend/src/app/router/guard.test.ts b/frontend/src/app/router/guard.test.tsindex fb65c50a86..88160855f1 100644--- a/frontend/src/app/router/guard.test.ts+++ b/frontend/src/app/router/guard.test.ts@@ -50,6 +50,8 @@ vi.mock("@/modules/ai/store", () => ({import { buildSigninRedirectQuery, rootGuard } from "./guard";import {+ ACCOUNT_ROUTE,+ ACCOUNT_ROUTE_TWO_FACTOR,AUTH_2FA_SETUP_MODULE,AUTH_OAUTH_CALLBACK_MODULE,AUTH_PASSWORD_RESET_MODULE,@@ -246,6 +248,15 @@ describe("rootGuard", () => {expect(run(PROJECT_V1_ROUTE_DASHBOARD, "/projects/p1")).toBeNull();});+ // Personal account routes live outside the /setting tree, so they need+ // their own entry in the allowlist. Without it a full page load of /account+ // lands on 404 while in-app navigation still appears to work.+ test("allows an authenticated user on their account page", () => {+ session.isLoggedIn = true;+ expect(run(ACCOUNT_ROUTE, "/account")).toBeNull();+ expect(run(ACCOUNT_ROUTE_TWO_FACTOR, "/account/two-factor")).toBeNull();+ });+test("unknown named route falls back to 404", () => {session.isLoggedIn = true;expect(location(run("some.unknown.route", "/whatever"))).toBe("/404");diff --git a/frontend/src/app/router/guard.ts b/frontend/src/app/router/guard.tsindex 1a0e7dd2fd..e421ea0c05 100644--- a/frontend/src/app/router/guard.ts+++ b/frontend/src/app/router/guard.ts@@ -7,6 +7,7 @@ import {workspaceCacheScope,} from "@/utils/storage-keys";import {+ ACCOUNT_ROUTE,AUTH_2FA_SETUP_MODULE,AUTH_MFA_MODULE,AUTH_OAUTH_CALLBACK_MODULE,@@ -78,6 +79,7 @@ export function buildSigninRedirectQuery(url: URL): Record<string, string> {// Route-name prefixes that an authenticated user may always access.const ALLOWED_ROUTE_PATTERNS = [+ ACCOUNT_ROUTE,ENVIRONMENT_V1_ROUTE_DASHBOARD,INSTANCE_ROUTE_DASHBOARD,PROJECT_V1_ROUTE_DASHBOARD,diff --git a/frontend/src/app/router/handles.ts b/frontend/src/app/router/handles.tsindex 82ea0fd9b7..847bbbf4c1 100644--- a/frontend/src/app/router/handles.ts+++ b/frontend/src/app/router/handles.ts@@ -4,7 +4,6 @@export const WORKSPACE_ROOT_MODULE = "workspace.root";export const WORKSPACE_ROUTE_LANDING = "workspace.landing";export const WORKSPACE_ROUTE_MY_ISSUES = "workspace.my-issues";-export const WORKSPACE_ROUTE_USER_PROFILE = "workspace.user-profile";export const DATABASE_ROUTE_DASHBOARD = "workspace.database";export const INSTANCE_ROUTE_DASHBOARD = "workspace.instance";export const PROJECT_V1_ROUTE_DASHBOARD = "workspace.project";@@ -61,8 +60,8 @@ export const SQL_EDITOR_QUERY_HISTORY_MODULE = "sql-editor.query-history";// --- dashboard/workspaceSetting.ts ---export const SETTING_ROUTE = "setting";export const SETTING_ROUTE_WORKSPACE = `${SETTING_ROUTE}.workspace`;-export const SETTING_ROUTE_PROFILE = `${SETTING_ROUTE}.profile`;-export const SETTING_ROUTE_PROFILE_TWO_FACTOR = `${SETTING_ROUTE_PROFILE}.two-factor`;+export const ACCOUNT_ROUTE = "account";+export const ACCOUNT_ROUTE_TWO_FACTOR = `${ACCOUNT_ROUTE}.two-factor`;export const SETTING_ROUTE_WORKSPACE_GENERAL = `${SETTING_ROUTE_WORKSPACE}.general`;export const SETTING_ROUTE_WORKSPACE_SUBSCRIPTION = `${SETTING_ROUTE_WORKSPACE}.subscription`;diff --git a/frontend/src/app/router/index.ts b/frontend/src/app/router/index.tsindex ca6660ab35..6fb4cf6682 100644--- a/frontend/src/app/router/index.ts+++ b/frontend/src/app/router/index.ts@@ -33,7 +33,7 @@ export {PROJECT_V1_ROUTE_DATABASE_DETAIL,PROJECT_V1_ROUTE_DATABASES,PROJECT_V1_ROUTE_DETAIL,- SETTING_ROUTE_PROFILE,+ ACCOUNT_ROUTE,SETTING_ROUTE_WORKSPACE_GENERAL,SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,SQL_EDITOR_DATABASE_MODULE,@@ -55,7 +55,6 @@ export {WORKSPACE_ROUTE_SEMANTIC_TYPES,WORKSPACE_ROUTE_SERVICE_ACCOUNTS,WORKSPACE_ROUTE_SQL_REVIEW,- WORKSPACE_ROUTE_USER_PROFILE,WORKSPACE_ROUTE_USERS,WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "./handles";diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsxindex 7064ec3d81..e9c06daa81 100644--- a/frontend/src/app/router/routes/dashboard.tsx+++ b/frontend/src/app/router/routes/dashboard.tsx@@ -4,6 +4,8 @@ import { DashboardLayout } from "@/app/layouts/DashboardLayout";import { RouteErrorPage } from "@/app/RouteErrorPage";import { rootGuard } from "@/app/router/guard";import {+ ACCOUNT_ROUTE,+ ACCOUNT_ROUTE_TWO_FACTOR,DATABASE_ROUTE_DASHBOARD,ENVIRONMENT_V1_ROUTE_DASHBOARD,INSTANCE_ROUTE_CREATE,@@ -46,8 +48,6 @@ import {PROJECT_V1_ROUTE_WEBHOOK_DETAIL,PROJECT_V1_ROUTE_WEBHOOKS,PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,- SETTING_ROUTE_PROFILE,- SETTING_ROUTE_PROFILE_TWO_FACTOR,SETTING_ROUTE_WORKSPACE,SETTING_ROUTE_WORKSPACE_GENERAL,SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,@@ -73,7 +73,6 @@ import {WORKSPACE_ROUTE_SQL_REVIEW,WORKSPACE_ROUTE_SQL_REVIEW_CREATE,WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,- WORKSPACE_ROUTE_USER_PROFILE,WORKSPACE_ROUTE_USERS,WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "@/app/router/handles";@@ -158,14 +157,6 @@ const workspaceLevelRoutes: RouteObject[] = [(m) => m.EnvironmentsPage),},- {- path: "users/:principalEmail",- handle: { name: WORKSPACE_ROUTE_USER_PROFILE },- lazy: lazyPage(- () => import("@/routes/workspace/ProfilePage"),- (m) => m.ProfilePage- ),- },{path: "403",handle: { name: WORKSPACE_ROUTE_403 },@@ -433,29 +424,33 @@ const workspaceLevelRoutes: RouteObject[] = [},];-// Workspace settings routes (`/setting/**`), SettingRouteShell layout.+// Personal account routes (`/account/**`). Separate from `/setting/**` so+// "my account" is not a sibling of the workspace's own settings.+const accountRoutes: RouteObject[] = [+ {+ path: "account",+ handle: { name: ACCOUNT_ROUTE },+ lazy: lazyPage(+ () => import("@/routes/workspace/AccountSettingsPage"),+ (m) => m.AccountSettingsPage+ ),+ },+ {+ path: "account/two-factor",+ handle: { name: ACCOUNT_ROUTE_TWO_FACTOR },+ lazy: lazyPage(+ () => import("@/routes/workspace/TwoFactorSetupPage"),+ (m) => m.TwoFactorSetupPage+ ),+ },+];+const workspaceSettingRoutes: RouteObject[] = [{path: "setting",handle: { name: SETTING_ROUTE_WORKSPACE },element: <RouteGroupOutlet />,children: [- {- path: "profile",- handle: { name: SETTING_ROUTE_PROFILE },- lazy: lazyPage(- () => import("@/routes/workspace/ProfilePage"),- (m) => m.ProfilePage- ),- },- {- path: "profile/two-factor",- handle: { name: SETTING_ROUTE_PROFILE_TWO_FACTOR },- lazy: lazyPage(- () => import("@/routes/workspace/TwoFactorSetupPage"),- (m) => m.TwoFactorSetupPage- ),- },{path: "general",handle: {@@ -1002,6 +997,7 @@ export const dashboardRoutes: RouteObject[] = [errorElement: <RouteErrorPage inline />,children: [...workspaceLevelRoutes,+ ...accountRoutes,...workspaceSettingRoutes,...environmentV1Routes,...instanceRoutes,diff --git a/frontend/src/components/DashboardSidebar.test.tsx b/frontend/src/components/DashboardSidebar.test.tsxindex 1a554f56f0..eccac28da8 100644--- a/frontend/src/components/DashboardSidebar.test.tsx+++ b/frontend/src/components/DashboardSidebar.test.tsx@@ -148,7 +148,6 @@ vi.mock("@/app/router", () => ({WORKSPACE_ROUTE_SEMANTIC_TYPES: "workspace.semantic-types",WORKSPACE_ROUTE_SERVICE_ACCOUNTS: "workspace.service-accounts",WORKSPACE_ROUTE_SQL_REVIEW: "workspace.sql-review",- WORKSPACE_ROUTE_USER_PROFILE: "workspace.user-profile",WORKSPACE_ROUTE_USERS: "workspace.users",WORKSPACE_ROUTE_WORKLOAD_IDENTITIES: "workspace.workload-identities",}));diff --git a/frontend/src/components/DashboardSidebar.tsx b/frontend/src/components/DashboardSidebar.tsxindex 6683bdd1ee..b2c80850d9 100644--- a/frontend/src/components/DashboardSidebar.tsx+++ b/frontend/src/components/DashboardSidebar.tsx@@ -38,7 +38,6 @@ import {WORKSPACE_ROUTE_SEMANTIC_TYPES,WORKSPACE_ROUTE_SERVICE_ACCOUNTS,WORKSPACE_ROUTE_SQL_REVIEW,- WORKSPACE_ROUTE_USER_PROFILE,WORKSPACE_ROUTE_USERS,WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "@/app/router";@@ -72,12 +71,6 @@ function getItemClass(item: SidebarItem, currentRouteName: string): string[] {if (isActive) {return ["router-link-active", "bg-link-hover"];}- if (- item.name === WORKSPACE_ROUTE_USERS &&- currentRouteName === WORKSPACE_ROUTE_USER_PROFILE- ) {- return ["router-link-active", "bg-link-hover"];- }return [];}diff --git a/frontend/src/components/IssueTable.tsx b/frontend/src/components/IssueTable.tsxindex 8d47d4c7b4..ba6873c0af 100644--- a/frontend/src/components/IssueTable.tsx+++ b/frontend/src/components/IssueTable.tsx@@ -4,10 +4,7 @@ import { memo, useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { issueServiceClientConnect } from "@/api";import { router } from "@/app/router";-import {- PROJECT_V1_ROUTE_DETAIL,- WORKSPACE_ROUTE_USER_PROFILE,-} from "@/app/router/handles";+import { PROJECT_V1_ROUTE_DETAIL } from "@/app/router/handles";import {AdvancedSearch,type ScopeOption,@@ -19,6 +16,7 @@ import { HumanizeTs } from "@/components/HumanizeTs";import { RouterLink } from "@/components/RouterLink";import { SelectionActionBar } from "@/components/SelectionActionBar";import { TimeRangePicker } from "@/components/TimeRangePicker";+import { UserHoverCard } from "@/components/UserHoverCard";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import {@@ -47,6 +45,8 @@ import { cn } from "@/lib/utils";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import {+ AccountType,+ getAccountTypeByEmail,getTimeForPbTimestampProtoEs,isValidProjectName,unknownUser,@@ -773,18 +773,23 @@ export const IssueListItem = memo(function IssueListItem({{t("common.created")}<HumanizeTs ts={createTimeTs} /><span>·</span>- <RouterLink- className="hover:underline"- to={{- name: WORKSPACE_ROUTE_USER_PROFILE,- params: { principalEmail: creator.email },- }}- onClick={(e) => {- e.stopPropagation();- }}- >- {creator.title}- </RouterLink>+ {getAccountTypeByEmail(creator.email) === AccountType.USER ? (+ <UserHoverCard+ email={creator.email}+ fallbackTitle={creator.title}+ >+ <span+ className="cursor-default"+ onClick={(e) => {+ e.stopPropagation();+ }}+ >+ {creator.title}+ </span>+ </UserHoverCard>+ ) : (+ <span>{creator.title}</span>+ )}{showProject && issueProject && (<><span>·</span>diff --git a/frontend/src/components/UserCell.test.tsx b/frontend/src/components/UserCell.test.tsxindex 38175ee295..dbe67068aa 100644--- a/frontend/src/components/UserCell.test.tsx+++ b/frontend/src/components/UserCell.test.tsx@@ -111,10 +111,7 @@ describe("UserCell", () => {title="Dev User"subtitle="[email protected]"nameLink={{- to: {- name: "workspace.user-profile",- params: { principalEmail: "[email protected]" },- },+ to: { name: "workspace.groups" },}}/></div>@@ -122,9 +119,7 @@ describe("UserCell", () => {const link = container.querySelector("a");expect(link).toBeInstanceOf(HTMLAnchorElement);- expect(link?.getAttribute("data-route-name")).toBe(- "workspace.user-profile"- );+ expect(link?.getAttribute("data-route-name")).toBe("workspace.groups");expect(link?.textContent).toBe("Dev User");act(() => {diff --git a/frontend/src/components/UserCell.tsx b/frontend/src/components/UserCell.tsxindex 5429e77395..5577b363c1 100644--- a/frontend/src/components/UserCell.tsx+++ b/frontend/src/components/UserCell.tsx@@ -1,6 +1,7 @@import type { ReactNode } from "react";import type { RouteTarget } from "@/app/router";import { RouterLink } from "@/components/RouterLink";+import { UserHoverCard } from "@/components/UserHoverCard";import { Button } from "@/components/ui/button";import { cn } from "@/lib/utils";import { UserAvatar } from "./UserAvatar";@@ -23,6 +24,12 @@ interface UserCellProps {onClick?: () => void;to?: RouteTarget;};+ /**+ * Email of the person this cell names. When set, the name gains a hover card+ * showing who they are. Used where a name is mentioned in passing and there+ * is no page to send the reader to.+ */+ hoverEmail?: string;/** Inline badges rendered after the name. */badges?: ReactNode;/** Extra className on the outer wrapper. */@@ -37,6 +44,7 @@ export function UserCell({avatar,nameClassName,nameLink,+ hoverEmail,badges,className,}: UserCellProps) {@@ -86,13 +94,21 @@ export function UserCell({</span>);+ const hoverableNameEl = hoverEmail ? (+ <UserHoverCard email={hoverEmail} fallbackTitle={title}>+ {nameEl}+ </UserHoverCard>+ ) : (+ nameEl+ );+return (<div className={cn("flex items-center gap-x-3", className)}>{showAvatar &&(avatar ?? <UserAvatar title={title || subtitle || "?"} size={size} />)}<div className="flex flex-col"><div className="flex items-center gap-x-1.5">- {nameEl}+ {hoverableNameEl}{badges}</div>{subtitle && (diff --git a/frontend/src/components/UserHoverCard.test.tsx b/frontend/src/components/UserHoverCard.test.tsxnew file mode 100644index 0000000000..d38a63dff9--- /dev/null+++ b/frontend/src/components/UserHoverCard.test.tsx@@ -0,0 +1,151 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { State } from "@/types/proto-es/v1/common_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const alice = {+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Alice",+ state: State.ACTIVE,+ profile: {+ source: "Entra ID",+ lastLoginTime: { seconds: 1n, nanos: 0 },+ lastChangePasswordTime: { seconds: 1n, nanos: 0 },+ },+ groups: ["groups/[email protected]"],+};++const mocks = vi.hoisted(() => ({+ getOrFetchUserByIdentifier: vi.fn(async () => alice),+ getUserByIdentifier: vi.fn(() => alice as unknown),+}));++vi.mock("@/stores/app", () => {+ const buildState = () => ({+ getOrFetchUserByIdentifier: mocks.getOrFetchUserByIdentifier,+ getUserByIdentifier: mocks.getUserByIdentifier,+ });+ const useAppStore = (selector: (state: unknown) => unknown) =>+ selector(buildState());+ useAppStore.getState = () => buildState();+ return { useAppStore };+});++// Render the card body inline; the point of these tests is what the card says,+// not Base UI's hover timing.+vi.mock("@/components/ui/preview-card", () => ({+ PreviewCard: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ PreviewCardTrigger: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ PreviewCardContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="card">{children}</div>+ ),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: () => {} },+}));++let UserHoverCard: typeof import("./UserHoverCard").UserHoverCard;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: async () => {+ await act(async () => {+ root.render(element);+ });+ },+ unmount: () => act(() => root.unmount()),+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.getUserByIdentifier.mockReturnValue(alice);+ ({ UserHoverCard } = await import("./UserHoverCard"));+});++describe("UserHoverCard", () => {+ test("answers who the person is", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <UserHoverCard email="[email protected]">+ <span>Alice</span>+ </UserHoverCard>+ );+ await render();++ const card = container.querySelector('[data-testid="card"]');+ expect(card?.textContent).toContain("Alice");+ expect(card?.textContent).toContain("[email protected]");++ unmount();+ });++ test("leaves out activity timestamps, roles and groups", async () => {+ // Reading a user record needs no special permission, so anything shown+ // here is shown to every member of the workspace. Activity timestamps in+ // particular would expose everyone's login pattern workspace-wide.+ const { container, render, unmount } = renderIntoContainer(+ <UserHoverCard email="[email protected]">+ <span>Alice</span>+ </UserHoverCard>+ );+ await render();++ const text = container.querySelector('[data-testid="card"]')?.textContent;+ expect(text).not.toContain("Entra ID");+ expect(text).not.toContain("[email protected]");+ expect(text).not.toContain("last-sign-in");+ expect(text).not.toContain("last-password-change");++ unmount();+ });++ test("marks a deactivated account", async () => {+ mocks.getUserByIdentifier.mockReturnValue({+ ...alice,+ state: State.DELETED,+ });++ const { container, render, unmount } = renderIntoContainer(+ <UserHoverCard email="[email protected]">+ <span>Alice</span>+ </UserHoverCard>+ );+ await render();++ expect(+ container.querySelector('[data-testid="card"]')?.textContent+ ).toContain("common.deactivated");++ unmount();+ });++ test("does not fetch until the card actually opens", async () => {+ // The card hangs off every name in a table; fetching eagerly would issue+ // one request per row.+ const { render, unmount } = renderIntoContainer(+ <UserHoverCard email="[email protected]">+ <span>Alice</span>+ </UserHoverCard>+ );+ await render();++ expect(mocks.getOrFetchUserByIdentifier).not.toHaveBeenCalled();++ unmount();+ });+});diff --git a/frontend/src/components/UserHoverCard.tsx b/frontend/src/components/UserHoverCard.tsxnew file mode 100644index 0000000000..f2011a7b41--- /dev/null+++ b/frontend/src/components/UserHoverCard.tsx@@ -0,0 +1,90 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { UserAvatar } from "@/components/UserAvatar";+import { Badge } from "@/components/ui/badge";+import {+ PreviewCard,+ PreviewCardContent,+ PreviewCardTrigger,+} from "@/components/ui/preview-card";+import { useAppStore } from "@/stores/app";+import { State } from "@/types/proto-es/v1/common_pb";++interface UserHoverCardProps {+ /** Email identifying the user. The card fetches by this on open. */+ email: string;+ /** Name already known to the caller, shown until the fetch resolves. */+ fallbackTitle?: string;+ children: ReactNode;+}++/**+ * Identity at a glance for a name or avatar mentioned in passing.+ *+ * Deliberately limited to who the person is: display name, email, and whether+ * the account is still active. Roles, groups and activity timestamps are not+ * here — they answer a different question, and last-login in particular would+ * expose every member's activity pattern to every other member, since reading+ * a user record needs no special permission. Administering an account happens+ * on the Users page.+ */+export function UserHoverCard({+ email,+ fallbackTitle,+ children,+}: UserHoverCardProps) {+ const { t } = useTranslation();+ const getOrFetchUserByIdentifier = useAppStore(+ (state) => state.getOrFetchUserByIdentifier+ );+ const user = useAppStore((state) => state.getUserByIdentifier(email));++ // Fetch on open rather than on mount: the card hangs off every name in a+ // table, so fetching eagerly would issue one request per row. The store+ // returns a cached user without a request, so re-asking on each open costs+ // nothing and lets a card that failed once recover on the next hover.+ const handleOpenChange = (open: boolean) => {+ if (!open) return;+ void getOrFetchUserByIdentifier({ identifier: email, silent: true });+ };++ const title = user?.title || fallbackTitle || email;+ const isDeleted = user?.state === State.DELETED;++ return (+ <PreviewCard onOpenChange={handleOpenChange}>+ <PreviewCardTrigger+ render={+ <span+ className="inline-flex items-center rounded-xs focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"+ tabIndex={0}+ />+ }+ >+ {children}+ </PreviewCardTrigger>+ {/* The card portals into the overlay root, but React events still+ propagate along the component tree — without this, selecting the+ email inside the card would trigger the enclosing row's click. */}+ <PreviewCardContent+ className="max-w-72"+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-start gap-x-3">+ <UserAvatar title={title} colorSeed={email} />+ <div className="flex min-w-0 flex-col gap-y-0.5">+ <div className="flex items-center gap-x-1.5">+ <span className="truncate font-medium text-main">{title}</span>+ {isDeleted && (+ <Badge className="shrink-0 text-xs px-1.5 py-0">+ {t("common.deactivated")}+ </Badge>+ )}+ </div>+ <span className="truncate text-xs text-control-light">{email}</span>+ </div>+ </div>+ </PreviewCardContent>+ </PreviewCard>+ );+}diff --git a/frontend/src/components/header/ProfileMenuTrigger.test.tsx b/frontend/src/components/header/ProfileMenuTrigger.test.tsxindex 31eaab0ee3..92a25d6961 100644--- a/frontend/src/components/header/ProfileMenuTrigger.test.tsx+++ b/frontend/src/components/header/ProfileMenuTrigger.test.tsx@@ -109,7 +109,7 @@ vi.mock("@/app/router", () => ({isSqlEditorRouteName: (name?: string) => name?.startsWith("sql-editor"),AUTH_SIGNIN_MODULE: "auth.signin",WORKSPACE_ROUTE_LANDING: "workspace.landing",- SETTING_ROUTE_PROFILE: "setting.profile",+ ACCOUNT_ROUTE: "account",SQL_EDITOR_HOME_MODULE: "sql-editor.home",}));diff --git a/frontend/src/components/header/ProfileMenuTrigger.tsx b/frontend/src/components/header/ProfileMenuTrigger.tsxindex 5020d066d7..296a961ac2 100644--- a/frontend/src/components/header/ProfileMenuTrigger.tsx+++ b/frontend/src/components/header/ProfileMenuTrigger.tsx@@ -2,8 +2,8 @@ import { ChevronRight } from "lucide-react";import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import {+ ACCOUNT_ROUTE,isSqlEditorRouteName,- SETTING_ROUTE_PROFILE,SQL_EDITOR_HOME_MODULE,useCurrentRoute,useNavigate,@@ -96,7 +96,7 @@ export function ProfileMenuTrigger({const handleProfileNavigate = () => {if (!link) return;setOpen(false);- void navigate.push({ name: SETTING_ROUTE_PROFILE });+ void navigate.push({ name: ACCOUNT_ROUTE });};const handleWorkspaceToggle = () => {diff --git a/frontend/src/components/ui/preview-card.tsx b/frontend/src/components/ui/preview-card.tsxnew file mode 100644index 0000000000..974692b863--- /dev/null+++ b/frontend/src/components/ui/preview-card.tsx@@ -0,0 +1,59 @@+import { PreviewCard as BasePreviewCard } from "@base-ui/react/preview-card";+import type { ComponentProps } from "react";+import { cn } from "@/lib/utils";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";++// A hover-triggered card for read-only detail about the thing under the+// cursor. Unlike Tooltip it may contain structured content, and unlike Popover+// it opens on hover intent rather than click.+//+// Base UI opens the card on focus as well as hover, but it does not make the+// trigger focusable: it renders an <a> with no href, and callers overriding+// `render` usually supply a span. Triggers must set their own tabIndex, or the+// card is reachable by mouse only.++// ---- Root ----+const PreviewCard = BasePreviewCard.Root;++// ---- Trigger ----+const PreviewCardTrigger = BasePreviewCard.Trigger;++// ---- Portal + Positioner + Popup ----+function PreviewCardContent({+ className,+ children,+ side = "top",+ align = "start",+ sideOffset = 6,+ ref,+ ...props+}: ComponentProps<typeof BasePreviewCard.Popup> & {+ side?: ComponentProps<typeof BasePreviewCard.Positioner>["side"];+ align?: ComponentProps<typeof BasePreviewCard.Positioner>["align"];+ sideOffset?: ComponentProps<typeof BasePreviewCard.Positioner>["sideOffset"];+}) {+ return (+ <BasePreviewCard.Portal container={getLayerRoot("overlay")}>+ <BasePreviewCard.Positioner+ side={side}+ align={align}+ sideOffset={sideOffset}+ className={LAYER_SURFACE_CLASS}+ >+ <BasePreviewCard.Popup+ ref={ref}+ className={cn(+ "rounded-sm border border-control-border bg-background p-3 shadow-md text-sm text-control",+ "focus:outline-hidden",+ className+ )}+ {...props}+ >+ {children}+ </BasePreviewCard.Popup>+ </BasePreviewCard.Positioner>+ </BasePreviewCard.Portal>+ );+}++export { PreviewCard, PreviewCardContent, PreviewCardTrigger };diff --git a/frontend/src/hooks/useAppState.ts b/frontend/src/hooks/useAppState.tsindex 81e3649089..3f76302b31 100644--- a/frontend/src/hooks/useAppState.ts+++ b/frontend/src/hooks/useAppState.ts@@ -38,8 +38,8 @@ export function useCurrentUser() {const user = useOptionalCurrentUser();// Stabilize the fallback identity: a fresh unknownUser() each render would// change identity while the user is unresolved, retriggering identity-keyed- // effects in callers (e.g. ProfilePage, TwoFactorSetupPage) and risking a- // render loop.+ // effects in callers (e.g. AccountSettingsPage, TwoFactorSetupPage) and+ // risking a render loop.return useMemo(() => user ?? unknownUser(), [user]);}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 71e5c3be5a..644a69cd55 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -279,6 +279,7 @@"database-group": "Database Group","databases": "Databases","deactivate": "Deactivate",+ "deactivated": "Deactivated","default": "Default","definition": "Definition","delete": "Delete",@@ -295,6 +296,7 @@"discard-changes": "Discard changes","discord": "Discord","dismiss": "Dismiss",+ "done": "Done","download": "Download","draft": "Draft","duplicate": "Duplicate",@@ -2275,6 +2277,14 @@}},"settings": {+ "account": {+ "description": "Manage your personal profile and how you sign in.",+ "email-managed": "Contact a workspace admin to change your sign-in email.",+ "password-notice": "Changing your password signs you out everywhere, including this session.",+ "security": "Security",+ "self": "Account settings",+ "update-password": "Update password"+ },"general": {"workspace": {"access-token-duration": {@@ -2558,6 +2568,29 @@"reactivate-confirm-title": "Are you sure to reactivate"},"add-member": "Add member",+ "admin": {+ "change-email": "Change email",+ "change-email-description": "Move this account from {{email}} to a new sign-in address. The user must sign in with the new address.",+ "create-user": "Create user",+ "create-user-roles-failed": "The account was created, but its roles could not be assigned. Set them from Members.",+ "deactivate": "Deactivate user",+ "deactivate-tip": "The account keeps its data but can no longer sign in. You can reactivate it later.",+ "edit-user": "Edit user",+ "email-immutable-tip": "To move this account to another address, close this panel and use Change email in the row menu.",+ "external-source": "This account is synced from {{source}}. Changes made here can be overwritten by the next sync.",+ "generate": "Generate",+ "reactivate": "Reactivate user",+ "reactivate-tip": "The account can sign in again with its existing credentials and roles.",+ "reset-mfa": "Reset 2FA",+ "reset-mfa-optional": "{{user}} loses their authenticator and recovery codes, and signs in without two-factor authentication until they enroll again.",+ "reset-mfa-recovery-first": "If they still have a recovery code they can sign in with it and enroll again themselves, without this reset.",+ "reset-mfa-required": "{{user}} loses their authenticator and recovery codes. This workspace requires two-factor authentication, so they must set up a new authenticator at next sign-in.",+ "reset-password": "Reset password",+ "reset-password-deliver": "Send this to them over a channel you trust. Bytebase does not email it.",+ "reset-password-description": "Set a new password for {{user}}. They are signed out of every session and must sign in again with it.",+ "reset-password-issued": "New password for {{user}}. It is shown once and cannot be retrieved later.",+ "saas-read-only": "User profiles are owned by the account holder in the cloud. Manage workspace access from Members instead."+ },"all-users": "All users","assign-role": "Assign role","cannot-revoke-self": "You cannot revoke yourself",@@ -2657,13 +2690,11 @@"password-mismatch": "New password mismatch","phone": "Phone","phone-tips": "Be sure to include the country code +1xxxxxx",- "role": "Role","setup-failed": "Failed to update profile.","setup-first-project": "Setup 1st project","setup-skip": "I'll do this later","setup-success": "Profile updated.","setup-title": "Welcome! Set up your workspace",- "subscription": "(Upgrade to enable role management)","workspace-name": "Workspace name","workspace-name-placeholder": "Enter workspace name"},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 66cbe1808e..d723b48ba3 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -279,6 +279,7 @@"database-group": "Grupo de bases de datos","databases": "Bases de datos","deactivate": "Desactivar",+ "deactivated": "Desactivado","default": "Predeterminado","definition": "Definición","delete": "Eliminar",@@ -295,6 +296,7 @@"discard-changes": "Descartar cambios","discord": "Discord","dismiss": "Descartar",+ "done": "Listo","download": "Descargar","draft": "Borrador","duplicate": "Duplicar",@@ -2275,6 +2277,14 @@}},"settings": {+ "account": {+ "description": "Gestiona tu perfil personal y cómo inicias sesión.",+ "email-managed": "Contacta con un administrador del espacio de trabajo para cambiar tu correo de inicio de sesión.",+ "password-notice": "Al cambiar la contraseña se cerrará la sesión en todos los dispositivos, incluido este.",+ "security": "Seguridad",+ "self": "Configuración de la cuenta",+ "update-password": "Actualizar contraseña"+ },"general": {"workspace": {"access-token-duration": {@@ -2558,6 +2568,29 @@"reactivate-confirm-title": "¿Estás seguro de que deseas reactivar?"},"add-member": "Agregar miembro",+ "admin": {+ "change-email": "Cambiar correo electrónico",+ "change-email-description": "Cambia la dirección de inicio de sesión de esta cuenta desde {{email}}. El usuario deberá iniciar sesión con la nueva dirección.",+ "create-user": "Crear usuario",+ "create-user-roles-failed": "La cuenta se creó, pero no se pudieron asignar sus roles. Configúralos desde Miembros.",+ "deactivate": "Desactivar usuario",+ "deactivate-tip": "La cuenta conserva sus datos pero ya no puede iniciar sesión. Puedes reactivarla más tarde.",+ "edit-user": "Editar usuario",+ "email-immutable-tip": "Para mover esta cuenta a otra dirección, cierra este panel y usa Cambiar correo electrónico en el menú de la fila.",+ "external-source": "Esta cuenta se sincroniza desde {{source}}. Los cambios hechos aquí pueden sobrescribirse en la próxima sincronización.",+ "generate": "Generar",+ "reactivate": "Reactivar usuario",+ "reactivate-tip": "La cuenta puede volver a iniciar sesión con sus credenciales y roles actuales.",+ "reset-mfa": "Restablecer 2FA",+ "reset-mfa-optional": "{{user}} pierde su autenticador y sus códigos de recuperación, e iniciará sesión sin verificación en dos pasos hasta que vuelva a registrarse.",+ "reset-mfa-recovery-first": "Si aún conserva un código de recuperación, puede iniciar sesión con él y volver a registrarse sin este restablecimiento.",+ "reset-mfa-required": "{{user}} pierde su autenticador y sus códigos de recuperación. Este espacio de trabajo exige verificación en dos pasos, así que deberá configurar un autenticador nuevo al iniciar sesión.",+ "reset-password": "Restablecer contraseña",+ "reset-password-deliver": "Envíasela por un canal de confianza. Bytebase no la envía por correo.",+ "reset-password-description": "Establece una nueva contraseña para {{user}}. Se cerrarán todas sus sesiones y deberá iniciar sesión de nuevo con ella.",+ "reset-password-issued": "Nueva contraseña de {{user}}. Se muestra una sola vez y no se puede recuperar después.",+ "saas-read-only": "En la nube, los perfiles pertenecen al titular de la cuenta. Gestiona el acceso al espacio de trabajo desde Miembros."+ },"all-users": "Todos los usuarios","assign-role": "Asignar rol","cannot-revoke-self": "No puede revocarse a sí mismo",@@ -2657,13 +2690,11 @@"password-mismatch": "Nueva contraseña no coincide","phone": "Número de móvil","phone-tips": "Asegúrese de incluir el código del país +1xxxxxx",- "role": "Rol","setup-failed": "Error al actualizar el perfil.","setup-first-project": "Configurar el primer proyecto","setup-skip": "Lo haré después","setup-success": "Perfil actualizado.","setup-title": "¡Bienvenido! Configure su espacio de trabajo",- "subscription": "(Actualice para habilitar la gestión de roles)","workspace-name": "Nombre del espacio de trabajo","workspace-name-placeholder": "Ingrese el nombre del espacio de trabajo"},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e64ff24a5d..5f42da6c5e 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -279,6 +279,7 @@"database-group": "データベースグループ","databases": "データベース","deactivate": "無効化",+ "deactivated": "無効","default": "デフォルト","definition": "定義","delete": "消去",@@ -295,6 +296,7 @@"discard-changes": "変更をキャンセルする","discord": "Discord","dismiss": "閉じる",+ "done": "完了","download": "ダウンロード","draft": "下書き","duplicate": "コピー",@@ -2275,6 +2277,14 @@}},"settings": {+ "account": {+ "description": "プロフィールとサインイン方法を管理します。",+ "email-managed": "サインイン用メールアドレスの変更はワークスペース管理者にご連絡ください。",+ "password-notice": "パスワードを変更すると、現在のセッションを含むすべてのセッションからサインアウトされます。",+ "security": "セキュリティ",+ "self": "アカウント設定",+ "update-password": "パスワードを更新"+ },"general": {"workspace": {"access-token-duration": {@@ -2558,6 +2568,29 @@"reactivate-confirm-title": "[OK] を有効にします"},"add-member": "メンバーを追加",+ "admin": {+ "change-email": "メールアドレスを変更",+ "change-email-description": "このアカウントのサインインアドレスを {{email}} から変更します。ユーザーは新しいアドレスでサインインします。",+ "create-user": "ユーザーを作成",+ "create-user-roles-failed": "アカウントは作成されましたが、ロールを割り当てられませんでした。メンバー画面で設定してください。",+ "deactivate": "ユーザーを無効化",+ "deactivate-tip": "データは保持されますが、サインインできなくなります。後で再度有効化できます。",+ "edit-user": "ユーザーを編集",+ "email-immutable-tip": "アドレスを変更するには、このパネルを閉じて、行のメニューから「メールアドレスを変更」を使用してください。",+ "external-source": "このアカウントは {{source}} から同期されています。ここでの変更は次回の同期で上書きされる場合があります。",+ "generate": "生成",+ "reactivate": "ユーザーを有効化",+ "reactivate-tip": "既存の認証情報とロールで再びサインインできます。",+ "reset-mfa": "2要素認証をリセット",+ "reset-mfa-optional": "{{user}} は現在の認証アプリとリカバリコードを失い、再登録するまで2要素認証なしでサインインします。",+ "reset-mfa-recovery-first": "リカバリコードが残っていれば、本人がそれでサインインして再登録できます。リセットは不要です。",+ "reset-mfa-required": "{{user}} は現在の認証アプリとリカバリコードを失います。このワークスペースは2要素認証が必須のため、次回サインイン時に認証アプリの再設定が必要です。",+ "reset-password": "パスワードをリセット",+ "reset-password-deliver": "信頼できる方法で本人に伝えてください。Bytebase はメールを送信しません。",+ "reset-password-description": "{{user}} に新しいパスワードを設定します。すべてのセッションからサインアウトされ、新しいパスワードで再度サインインする必要があります。",+ "reset-password-issued": "{{user}} の新しいパスワードです。一度しか表示されず、後から確認することはできません。",+ "saas-read-only": "クラウドではアカウント情報は本人が管理します。ワークスペースのアクセス権はメンバー画面で管理してください。"+ },"all-users": "すべてのユーザー","assign-role": "ロールを割り当て","cannot-revoke-self": "自分自身を取り消すことはできません",@@ -2657,13 +2690,11 @@"password-mismatch": "新しいパスワードが一致しません","phone": "電話番号","phone-tips": "国コードを必ず含めてください +81xxxxxx",- "role": "ロール","setup-failed": "プロフィールの更新に失敗しました。","setup-first-project": "最初のプロジェクトを設定","setup-skip": "後で設定する","setup-success": "プロフィールが更新されました。","setup-title": "ようこそ!ワークスペースを設定してください",- "subscription": "(有料プランにアップグレードするとキャラクター管理が可能になります)","workspace-name": "ワークスペース名","workspace-name-placeholder": "ワークスペース名を入力"},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 3753732b25..9085d32941 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -279,6 +279,7 @@"database-group": "Nhóm cơ sở dữ liệu","databases": "Cơ sở dữ liệu","deactivate": "Hủy kích hoạt",+ "deactivated": "Đã vô hiệu hóa","default": "Mặc định","definition": "Định nghĩa","delete": "Xóa",@@ -295,6 +296,7 @@"discard-changes": "Hủy thay đổi","discord": "Discord","dismiss": "Loại bỏ",+ "done": "Xong","download": "Tải xuống","draft": "Bản nháp","duplicate": "Nhân bản",@@ -2275,6 +2277,14 @@}},"settings": {+ "account": {+ "description": "Quản lý hồ sơ cá nhân và cách bạn đăng nhập.",+ "email-managed": "Liên hệ quản trị viên workspace để đổi email đăng nhập.",+ "password-notice": "Đổi mật khẩu sẽ đăng xuất bạn khỏi mọi phiên, kể cả phiên hiện tại.",+ "security": "Bảo mật",+ "self": "Cài đặt tài khoản",+ "update-password": "Cập nhật mật khẩu"+ },"general": {"workspace": {"access-token-duration": {@@ -2558,6 +2568,29 @@"reactivate-confirm-title": "Bạn có chắc muốn kích hoạt lại?"},"add-member": "Thêm thành viên",+ "admin": {+ "change-email": "Đổi email",+ "change-email-description": "Chuyển địa chỉ đăng nhập của tài khoản này từ {{email}} sang địa chỉ mới. Người dùng phải đăng nhập bằng địa chỉ mới.",+ "create-user": "Tạo người dùng",+ "create-user-roles-failed": "Tài khoản đã được tạo nhưng không gán được vai trò. Hãy thiết lập trong mục Thành viên.",+ "deactivate": "Vô hiệu hóa người dùng",+ "deactivate-tip": "Tài khoản vẫn giữ dữ liệu nhưng không thể đăng nhập. Bạn có thể kích hoạt lại sau.",+ "edit-user": "Sửa người dùng",+ "email-immutable-tip": "Để chuyển tài khoản sang địa chỉ khác, hãy đóng bảng này và dùng Đổi email trong menu của hàng.",+ "external-source": "Tài khoản này được đồng bộ từ {{source}}. Thay đổi ở đây có thể bị ghi đè ở lần đồng bộ tiếp theo.",+ "generate": "Tạo",+ "reactivate": "Kích hoạt lại người dùng",+ "reactivate-tip": "Tài khoản có thể đăng nhập lại với thông tin đăng nhập và vai trò hiện có.",+ "reset-mfa": "Đặt lại 2FA",+ "reset-mfa-optional": "{{user}} sẽ mất trình xác thực và mã khôi phục hiện tại, và đăng nhập không có xác thực hai bước cho tới khi đăng ký lại.",+ "reset-mfa-recovery-first": "Nếu họ vẫn còn mã khôi phục, họ có thể đăng nhập bằng mã đó và tự đăng ký lại mà không cần đặt lại.",+ "reset-mfa-required": "{{user}} sẽ mất trình xác thực và mã khôi phục hiện tại. Không gian làm việc này yêu cầu xác thực hai bước, nên họ phải thiết lập trình xác thực mới ở lần đăng nhập tới.",+ "reset-password": "Đặt lại mật khẩu",+ "reset-password-deliver": "Hãy gửi cho họ qua kênh bạn tin tưởng. Bytebase không gửi qua email.",+ "reset-password-description": "Đặt mật khẩu mới cho {{user}}. Mọi phiên đăng nhập sẽ bị đăng xuất và họ phải đăng nhập lại bằng mật khẩu này.",+ "reset-password-issued": "Mật khẩu mới của {{user}}. Chỉ hiển thị một lần và không thể xem lại.",+ "saas-read-only": "Trên bản cloud, hồ sơ tài khoản do chủ tài khoản quản lý. Hãy quản lý quyền truy cập workspace ở trang Thành viên."+ },"all-users": "Tất cả người dùng","assign-role": "Gán vai trò","cannot-revoke-self": "Bạn không thể thu hồi chính mình",@@ -2657,13 +2690,11 @@"password-mismatch": "Mật khẩu mới không khớp","phone": "Điện thoại","phone-tips": "Nhớ bao gồm mã quốc gia +1xxxxxx",- "role": "Vai trò","setup-failed": "Cập nhật hồ sơ thất bại.","setup-first-project": "Thiết lập dự án đầu tiên","setup-skip": "Để sau","setup-success": "Hồ sơ đã được cập nhật.","setup-title": "Chào mừng! Thiết lập không gian làm việc của bạn",- "subscription": "(Nâng cấp để kích hoạt quản lý vai trò)","workspace-name": "Tên không gian làm việc","workspace-name-placeholder": "Nhập tên không gian làm việc"},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 5f6e17f343..525993f484 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -279,6 +279,7 @@"database-group": "数据库分组","databases": "数据库","deactivate": "禁用",+ "deactivated": "已停用","default": "默认","definition": "定义","delete": "删除",@@ -295,6 +296,7 @@"discard-changes": "取消修改","discord": "Discord","dismiss": "关闭",+ "done": "完成","download": "下载","draft": "草稿","duplicate": "拷贝",@@ -2275,6 +2277,14 @@}},"settings": {+ "account": {+ "description": "管理您的个人资料和登录方式。",+ "email-managed": "如需修改登录邮箱,请联系工作空间管理员。",+ "password-notice": "修改密码后,所有会话(包括当前会话)都会退出登录。",+ "security": "安全",+ "self": "账号设置",+ "update-password": "更新密码"+ },"general": {"workspace": {"access-token-duration": {@@ -2558,6 +2568,29 @@"reactivate-confirm-title": "确定启用"},"add-member": "添加成员",+ "admin": {+ "change-email": "修改邮箱",+ "change-email-description": "将该账号的登录邮箱从 {{email}} 修改为新邮箱。该用户需使用新邮箱登录。",+ "create-user": "创建用户",+ "create-user-roles-failed": "账号已创建,但角色分配失败。请在成员页面中设置。",+ "deactivate": "停用用户",+ "deactivate-tip": "账号数据会保留,但无法再登录。您之后可以重新启用。",+ "edit-user": "编辑用户",+ "email-immutable-tip": "如需更换邮箱,请关闭此面板,在该行的操作菜单中选择“修改邮箱”。",+ "external-source": "该账号从 {{source}} 同步。此处的修改可能会被下次同步覆盖。",+ "generate": "生成",+ "reactivate": "启用用户",+ "reactivate-tip": "该账号可以使用原有的凭证和角色重新登录。",+ "reset-mfa": "重置两步验证",+ "reset-mfa-optional": "{{user}} 将失去当前的验证器和恢复码,在重新绑定之前将不使用两步验证登录。",+ "reset-mfa-recovery-first": "如果对方还有恢复码,可以直接用恢复码登录并自行重新绑定,无需重置。",+ "reset-mfa-required": "{{user}} 将失去当前的验证器和恢复码。此工作空间要求两步验证,因此对方下次登录时必须重新绑定验证器。",+ "reset-password": "重置密码",+ "reset-password-deliver": "请通过可信渠道发送给对方。Bytebase 不会通过邮件发送。",+ "reset-password-description": "为 {{user}} 设置新密码。该用户的所有会话都会退出登录,需要使用新密码重新登录。",+ "reset-password-issued": "{{user}} 的新密码。仅显示一次,之后无法再次查看。",+ "saas-read-only": "云端账号资料由账号本人管理。请在成员页面管理工作空间访问权限。"+ },"all-users": "全部用户","assign-role": "分配角色","cannot-revoke-self": "您不能撤销自己",@@ -2657,13 +2690,11 @@"password-mismatch": "新密码不匹配","phone": "手机号","phone-tips": "请包含国家代码前缀 +86xxxxxx",- "role": "角色","setup-failed": "更新个人资料失败。","setup-first-project": "设置第一个项目","setup-skip": "稍后再说","setup-success": "个人资料已更新。","setup-title": "欢迎!设置您的工作空间",- "subscription": "(升级到付费方案来解锁角色管理)","workspace-name": "工作空间名称","workspace-name-placeholder": "输入工作空间名称"},diff --git a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsxindex 27cceeecfe..066e987d0a 100644--- a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx+++ b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx@@ -15,6 +15,7 @@ import {import { FeatureAttention } from "@/components/FeatureAttention";import { FeatureBadge } from "@/components/FeatureBadge";import { RouterLink } from "@/components/RouterLink";+import { UserHoverCard } from "@/components/UserHoverCard";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";import { FeatureModal } from "@/components/ui/feature-modal";@@ -1028,12 +1029,9 @@ function ExemptionDetailPanel({member.member.startsWith(workloadIdentityBindingPrefix) ? (<span className="font-medium">{userEmail}</span>) : (- <RouterLink- className="normal-link font-medium"- to={`/users/${userEmail}`}- >- {userEmail}- </RouterLink>+ <UserHoverCard email={userEmail}>+ <span className="font-medium">{userEmail}</span>+ </UserHoverCard>)}</div><div className="mt-1 text-sm textinfolabel">diff --git a/frontend/src/routes/workspace/AccountSettingsPage.tsx b/frontend/src/routes/workspace/AccountSettingsPage.tsxnew file mode 100644index 0000000000..0b60f56622--- /dev/null+++ b/frontend/src/routes/workspace/AccountSettingsPage.tsx@@ -0,0 +1 @@+export { AccountSettingsPage } from "./profile/AccountSettingsPage";diff --git a/frontend/src/routes/workspace/MembersPage.test.tsx b/frontend/src/routes/workspace/MembersPage.test.tsxindex 1ea7810845..125b79643d 100644--- a/frontend/src/routes/workspace/MembersPage.test.tsx+++ b/frontend/src/routes/workspace/MembersPage.test.tsx@@ -201,7 +201,6 @@ vi.mock("@/lib/project-member/utils", () => ({vi.mock("@/app/router", () => ({useNavigate: () => vi.fn(),WORKSPACE_ROUTE_GROUPS: "groups",- WORKSPACE_ROUTE_USER_PROFILE: "user-profile",}));vi.mock("@/modules/cel", () => ({diff --git a/frontend/src/routes/workspace/MembersPage.tsx b/frontend/src/routes/workspace/MembersPage.tsxindex 8c97304eaa..73dbaa150a 100644--- a/frontend/src/routes/workspace/MembersPage.tsx+++ b/frontend/src/routes/workspace/MembersPage.tsx@@ -20,10 +20,7 @@ import React, {} from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";-import {- WORKSPACE_ROUTE_GROUPS,- WORKSPACE_ROUTE_USER_PROFILE,-} from "@/app/router";+import { WORKSPACE_ROUTE_GROUPS } from "@/app/router";import { AccountMultiSelect } from "@/components/AccountMultiSelect";import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/components/DatabaseResourceSelector";import { EnvironmentSelect } from "@/components/EnvironmentSelect";@@ -422,23 +419,19 @@ function MemberTable({</>) : undefined}+ hoverEmail={+ mb.type === "users" && canGetUsers+ ? mb.user?.email+ : undefined+ }nameLink={- mb.type === "users" && canGetUsers && mb.user?.email+ mb.type === "groups" && canGetGroups? {to: {- name: WORKSPACE_ROUTE_USER_PROFILE,- params: {- principalEmail: mb.user.email,- },+ name: WORKSPACE_ROUTE_GROUPS,},}- : mb.type === "groups" && canGetGroups- ? {- to: {- name: WORKSPACE_ROUTE_GROUPS,- },- }- : undefined+ : undefined}badges={<>@@ -542,18 +535,7 @@ function MemberTable({subtitle={user.email}size="sm"className="pl-12"- nameLink={- canGetUsers- ? {- to: {- name: WORKSPACE_ROUTE_USER_PROFILE,- params: {- principalEmail: user.email,- },- },- }- : undefined- }+ hoverEmail={canGetUsers ? user.email : undefined}badges={user.name === currentUser.name ? (<Badge className="text-xs">diff --git a/frontend/src/routes/workspace/ProfilePage.tsx b/frontend/src/routes/workspace/ProfilePage.tsxdeleted file mode 100644index cce0bd9bc1..0000000000--- a/frontend/src/routes/workspace/ProfilePage.tsx+++ /dev/null@@ -1 +0,0 @@-export { ProfilePage } from "./profile/ProfilePage";diff --git a/frontend/src/routes/workspace/UsersPage.tsx b/frontend/src/routes/workspace/UsersPage.tsxindex c915aca672..e58055638c 100644--- a/frontend/src/routes/workspace/UsersPage.tsx+++ b/frontend/src/routes/workspace/UsersPage.tsx@@ -1,41 +1,16 @@import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { isEqual } from "lodash-es";-import {- CircleAlert,- CircleCheck,- Eye,- EyeOff,- Plus,- Settings,- Trash2,- Undo2,-} from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Plus, Settings } from "lucide-react";+import { useCallback, useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { router } from "@/app/router";-import {- WORKSPACE_ROUTE_GROUPS,- WORKSPACE_ROUTE_USER_PROFILE,-} from "@/app/router/handles";+import { WORKSPACE_ROUTE_GROUPS } from "@/app/router/handles";import { ComponentPermissionGuard } from "@/components/ComponentPermissionGuard";import { FeatureBadge } from "@/components/FeatureBadge";-import { RoleSelect } from "@/components/RoleSelect";import { UserCell } from "@/components/UserCell";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";-import { FormError, FormField, FormTitle } from "@/components/ui/form";-import { Input } from "@/components/ui/input";import { SearchInput } from "@/components/ui/search-input";-import {- Sheet,- SheetBody,- SheetContent,- SheetFooter,- SheetHeader,- SheetTitle,-} from "@/components/ui/sheet";import { listRowStateClassName } from "@/components/ui/styles.stylex";import {Table,@@ -45,33 +20,26 @@ import {TableHeader,TableRow,} from "@/components/ui/table";-import { Tooltip } from "@/components/ui/tooltip";import {WorkspacePageLayout,WorkspacePageToolbar,} from "@/components/WorkspacePageLayout";import { useCurrentUser } from "@/hooks/useAppState";import { PagedTableFooter, usePagedData } from "@/hooks/usePagedData";-import { cn } from "@/lib/utils";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import { getUserFullNameByType } from "@/stores/modules/v1/common";-import {- AccountType,- getAccountTypeByEmail,- getUserEmailInBinding,-} from "@/types";-import { PresetRoleType } from "@/types/iam";+import { AccountType, getAccountTypeByEmail } from "@/types";import { State } from "@/types/proto-es/v1/common_pb";import type { Group } from "@/types/proto-es/v1/group_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";-import {- UpdateUserRequestSchema,- UserSchema,-} from "@/types/proto-es/v1/user_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";import { AADSyncSheet } from "./shared/AADSyncSheet";+import { EditUserSheet } from "./users/EditUserSheet";+import { UserFormSheet } from "./users/UserFormSheet";+import { UserRowMenu } from "./users/UserRowMenu";// ============================================================// UserTable@@ -80,12 +48,12 @@ import { AADSyncSheet } from "./shared/AADSyncSheet";function UserTable({users,onUserUpdated,- onUserSelected,+ onUserEdit,onGroupSelected,}: {users: User[];- onUserUpdated: (user: User) => void;- onUserSelected?: (user: User) => void;+ onUserUpdated: (user: User, replaces?: User) => void;+ onUserEdit?: (user: User) => void;onGroupSelected?: (group: Group) => void;}) {const { t } = useTranslation();@@ -120,11 +88,6 @@ function UserTable({const accountType = getAccountTypeByEmail(user.email);const fullName = getUserFullNameByType(user);- const confirmed = window.confirm(- t("settings.members.action.deactivate-confirm-title")- );- if (!confirmed) return;-try {if (accountType === AccountType.SERVICE_ACCOUNT) {await deleteServiceAccount(fullName);@@ -142,8 +105,10 @@ function UserTable({style: "SUCCESS",title: t("common.updated"),});- } catch {- // error already shown by store+ } catch (error) {+ // The store already surfaced the error; rethrow so the confirm dialog+ // stays open instead of dismissing as if the change had landed.+ throw error;}};@@ -168,31 +133,8 @@ function UserTable({style: "SUCCESS",title: t("common.updated"),});- } catch {- // error already shown by store- }- };-- const handleView = (user: User) => {- const accountType = getAccountTypeByEmail(user.email);- if (accountType === AccountType.USER && onUserSelected) {- onUserSelected(user);- } else {- router.push({- name: WORKSPACE_ROUTE_USER_PROFILE,- params: { principalEmail: user.email },- });- }- };-- const getDeletePermission = (accountType: AccountType) => {- switch (accountType) {- case AccountType.SERVICE_ACCOUNT:- return "bb.serviceAccounts.delete";- case AccountType.WORKLOAD_IDENTITY:- return "bb.workloadIdentities.delete";- default:- return "bb.users.delete";+ } catch (error) {+ throw error;}};@@ -207,17 +149,6 @@ function UserTable({}};- const getUndeletePermission = (accountType: AccountType) => {- switch (accountType) {- case AccountType.SERVICE_ACCOUNT:- return "bb.serviceAccounts.undelete";- case AccountType.WORKLOAD_IDENTITY:- return "bb.workloadIdentities.undelete";- default:- return "bb.users.undelete";- }- };-const getAccountTypeLabel = (accountType: AccountType) => {switch (accountType) {case AccountType.SERVICE_ACCOUNT:@@ -263,41 +194,15 @@ function UserTable({);return (- <TableRow- key={user.name}- className={cn(- canView &&- "cursor-pointer focus-visible:outline-none focus-visible:bg-control-bg",- canView && listRowStateClassName- )}- tabIndex={canView ? 0 : undefined}- role={canView ? "button" : undefined}- aria-label={canView ? user.title || user.email : undefined}- onClick={canView ? () => handleView(user) : undefined}- onKeyDown={- canView- ? (e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- handleView(user);- }- }- : undefined- }- >+ <TableRow key={user.name} className={listRowStateClassName}>{/* Account column */}<TableCell className="py-2"><UserCelltitle={user.title}subtitle={user.email}- nameLink={- canView- ? {- to: {- name: WORKSPACE_ROUTE_USER_PROFILE,- params: { principalEmail: user.email },- },- }+ hoverEmail={+ canView && accountType === AccountType.USER+ ? user.email: undefined}nameClassName={@@ -344,54 +249,18 @@ function UserTable({/></TableCell>- {/* Operations column — destructive/secondary actions only.- The row itself is clickable to open the detail sheet. */}+ {/* Operations column — the overflow menu is the row's only+ affordance, so a row has exactly one place to act from. */}<TableCell className="py-2">- <div className="flex justify-end gap-x-1">- {!isDeleted &&- hasWorkspacePermissionV2(- getDeletePermission(accountType)- ) &&- !isSelf && (- <Tooltip- content={t(- "settings.members.action.deactivate-confirm-title"- )}- >- <Button- appearance="secondary"- size="sm"- className="text-error hover:text-error"- onClick={(e) => {- e.stopPropagation();- handleDeactivate(user);- }}- >- <Trash2 className="h-4 w-4" />- </Button>- </Tooltip>- )}- {isDeleted &&- hasWorkspacePermissionV2(- getUndeletePermission(accountType)- ) && (- <Tooltip- content={t(- "settings.members.action.reactivate-confirm-title"- )}- >- <Button- appearance="secondary"- size="sm"- onClick={(e) => {- e.stopPropagation();- handleRestore(user);- }}- >- <Undo2 className="h-4 w-4" />- </Button>- </Tooltip>- )}+ <div className="flex justify-end">+ <UserRowMenu+ user={user}+ isSelf={isSelf}+ onUserUpdated={onUserUpdated}+ onEdit={(u) => onUserEdit?.(u)}+ onDeactivate={handleDeactivate}+ onReactivate={handleRestore}+ /></div></TableCell></TableRow>@@ -449,469 +318,6 @@ function UserGroupsCell({);}-// ============================================================-// CreateUserDrawer-// ============================================================--function extractUserTitle(email: string): string {- const atIndex = email.indexOf("@");- return atIndex !== -1 ? email.substring(0, atIndex) : email;-}--interface CreateUserSheetProps {- open: boolean;- user: User | undefined;- onClose: () => void;- onCreated: (user: User) => void;- onUpdated: (user: User) => void;-}--// Outer wrapper — renders the Sheet container. The actual form lives in-// `UserForm` below, keyed by entity so it remounts cleanly every time a-// different entity is selected, and gated by `open` so it unmounts on close.-// This guarantees that useState initializers always see the latest `user`-// prop and that there's no stale state between opens.-function CreateUserSheet(props: CreateUserSheetProps) {- const { open, user, onClose } = props;- // Freeze the entity while open=false so the inner form stays visually- // stable during the Sheet's close animation; see the long comment on- // CreateWorkloadIdentitySheet for the full rationale.- const openEntityRef = useRef(user);- if (open) {- openEntityRef.current = user;- }- const stableUser = openEntityRef.current;- return (- <Sheet open={open} onOpenChange={(next) => !next && onClose()}>- <SheetContent width="standard">- <UserForm- key={stableUser?.name ?? "new"}- user={stableUser}- onClose={props.onClose}- onCreated={props.onCreated}- onUpdated={props.onUpdated}- />- </SheetContent>- </Sheet>- );-}--function UserForm({- user,- onClose,- onCreated,- onUpdated,-}: Omit<CreateUserSheetProps, "open">) {- const { t } = useTranslation();- const createUser = useAppStore((state) => state.createUser);- const updateUser = useAppStore((state) => state.updateUser);- const patchWorkspaceIamPolicy = useAppStore(- (state) => state.patchWorkspaceIamPolicy- );- const passwordRestriction = useAppStore(- (s) => s.getWorkspaceProfile().passwordRestriction- );- const enforceIdentityDomain = useAppStore(- (s) => s.getWorkspaceProfile().enforceIdentityDomain- );- const workspaceDomains = useAppStore((s) => s.getWorkspaceProfile().domains);-- const isEditMode =- !!user && user.name !== "" && !user.name.endsWith("/unknown");-- const allowUpdate =- !isEditMode || hasWorkspacePermissionV2("bb.users.update");-- // Capture initial values on mount. Because the parent keys this component- // by user, it remounts fresh every time a different user is edited, so- // these initial values always reflect the latest `user` prop.- //- // The empty deps array is intentional: we want the initial baseline- // frozen at mount so dirty tracking compares against it. If we added- // `userMapToRoles` to deps, a Pinia store refresh mid-edit would move- // the baseline and incorrectly classify untouched fields as dirty- // (or vice versa). Since the outer CreateUserSheet wrapper remounts- // this component whenever the edited user changes, "mount-only" is the- // right scope for the baseline.- const initialRoles = useMemo(() => {- if (!user || !isEditMode) {- return [PresetRoleType.WORKSPACE_MEMBER];- }- // Read a one-shot snapshot of the workspace role map at mount. The parent- // page loads the workspace IAM policy, so it is populated by the time an- // edit sheet opens; reading via getState keeps this baseline mount-only.- const roles = useAppStore- .getState()- .workspaceUserMapToRoles()- .get(getUserFullNameByType(user));- return roles ? [...roles] : [];- }, []);- const initialTitle = user?.title ?? "";- const initialEmail = user?.email ?? "";- const initialPhone = user?.phone ?? "";-- const [title, setTitle] = useState(initialTitle);- const [email, setEmail] = useState(initialEmail);- const [phone, setPhone] = useState(initialPhone);- const [password, setPassword] = useState("");- const [passwordConfirm, setPasswordConfirm] = useState("");- const [roles, setRoles] = useState<string[]>(initialRoles);- const [isRequesting, setIsRequesting] = useState(false);- const [showPassword, setShowPassword] = useState(false);-- // Password validation- const passwordChecks = useMemo(() => {- const minLength = passwordRestriction?.minLength ?? 8;- const checks: { text: string; matched: boolean }[] = [- {- text: t("settings.general.workspace.password-restriction.min-length", {- min: minLength,- }),- matched: password.length >= minLength,- },- ];- if (passwordRestriction?.requireNumber) {- checks.push({- text: t(- "settings.general.workspace.password-restriction.require-number"- ),- matched: /[0-9]+/.test(password),- });- }- if (passwordRestriction?.requireUppercaseLetter) {- checks.push({- text: t(- "settings.general.workspace.password-restriction.require-uppercase-letter"- ),- matched: /[A-Z]+/.test(password),- });- } else if (passwordRestriction?.requireLetter) {- checks.push({- text: t(- "settings.general.workspace.password-restriction.require-letter"- ),- matched: /[a-zA-Z]+/.test(password),- });- }- if (passwordRestriction?.requireSpecialCharacter) {- checks.push({- text: t(- "settings.general.workspace.password-restriction.require-special-character"- ),- matched: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(password),- });- }- return checks;- }, [password, passwordRestriction, t]);-- const passwordHint =- password.length > 0 && passwordChecks.some((c) => !c.matched);- const passwordMismatch = password.length > 0 && password !== passwordConfirm;-- const emailDomainValid = useMemo(() => {- if (isEditMode) return true;- if (!enforceIdentityDomain || workspaceDomains.length === 0) return true;- const atIdx = email.indexOf("@");- if (atIdx < 0) return false;- const domain = email.slice(atIdx + 1);- return workspaceDomains.includes(domain);- }, [email, isEditMode, enforceIdentityDomain, workspaceDomains]);-- const isFormValid =- email.length > 0 && emailDomainValid && !passwordHint && !passwordMismatch;-- // Dirty tracking — in edit mode the Update button is disabled unless- // something actually changed. Create mode is always "dirty".- const isDirty = useMemo(() => {- if (!isEditMode) return true;- if (title !== initialTitle) return true;- if (phone !== initialPhone) return true;- if (password.length > 0) return true;- if (!isEqual([...initialRoles].sort(), [...roles].sort())) return true;- return false;- }, [- isEditMode,- title,- phone,- password,- roles,- initialTitle,- initialPhone,- initialRoles,- ]);-- const allowConfirm = isFormValid && isDirty;-- const hasPermission = hasWorkspacePermissionV2(- isEditMode ? "bb.users.update" : "bb.users.create"- );-- const handleSubmit = async () => {- if (!allowConfirm || !hasPermission) return;- setIsRequesting(true);- try {- if (isEditMode) {- await handleUpdate();- } else {- await handleCreate();- }- } catch {- // error shown by store- } finally {- setIsRequesting(false);- }- };-- const handleCreate = async () => {- // Empty password is valid on create; backend will generate a random password.- const createdUser = await createUser({- ...create(UserSchema, {}),- title: title || extractUserTitle(email),- email,- phone,- password,- });- if (roles.length > 0) {- try {- await patchWorkspaceIamPolicy([- {- member: getUserEmailInBinding(createdUser.email),- roles,- },- ]);- } catch {- // do nothing- }- }- onCreated(createdUser);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.created"),- });- onClose();- };-- const handleUpdate = async () => {- if (!user) return;-- const updateMask: string[] = [];- const payload = create(UserSchema, {- ...user,- title,- phone,- password,- });- if (title !== user.title) updateMask.push("title");- if (phone !== user.phone) updateMask.push("phone");- if (password) updateMask.push("password");-- let updatedUser: User = user;-- if (updateMask.length > 0) {- updatedUser = await updateUser(- create(UpdateUserRequestSchema, {- user: payload,- updateMask: create(FieldMaskSchema, { paths: updateMask }),- })- );- }-- if (!isEqual([...initialRoles].sort(), [...roles].sort())) {- await patchWorkspaceIamPolicy([- {- member: getUserEmailInBinding(updatedUser.email),- roles,- },- ]);- }-- onUpdated(updatedUser);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- onClose();- };-- return (- <>- <SheetHeader>- <SheetTitle>{t("common.user")}</SheetTitle>- </SheetHeader>-- <SheetBody>- <div className="flex flex-col gap-y-6">- {/* Name */}- <FormField>- <FormTitle id="user-form-name-title">{t("common.name")}</FormTitle>- <Input- id="user-form-name"- aria-labelledby="user-form-name-title"- value={title}- onChange={(e) => setTitle(e.target.value)}- placeholder={t("common.name")}- maxLength={200}- disabled={!allowUpdate}- />- </FormField>-- {/* Email */}- <FormField>- <FormTitle id="user-form-email-title">- {t("common.email")}- <span className="ml-0.5 text-error">*</span>- </FormTitle>- <Input- id="user-form-email"- aria-labelledby="user-form-email-title"- type="email"- value={email}- onChange={(e) => setEmail(e.target.value)}- disabled={isEditMode}- />- </FormField>-- {/* Roles */}- {hasWorkspacePermissionV2("bb.workspaces.setIamPolicy") && (- <FormField>- <FormTitle>{t("settings.members.table.roles")}</FormTitle>- <RoleSelect value={roles} onChange={setRoles} disabled={false} />- </FormField>- )}-- {/* Phone */}- <FormField>- <FormTitle id="user-form-phone-title">- {t("settings.profile.phone")}- </FormTitle>- <span className="text-sm text-control-placeholder">- {t("settings.profile.phone-tips")}- </span>- <Input- id="user-form-phone"- aria-labelledby="user-form-phone-title"- type="tel"- value={phone}- onChange={(e) => setPhone(e.target.value)}- autoComplete="new-password"- disabled={!allowUpdate}- />- </FormField>-- {/* Password */}- <div className="flex flex-col gap-y-6">- <FormField>- <FormTitle id="user-form-password-title">- {t("settings.profile.password")}- </FormTitle>- <span- className={`flex items-center gap-x-1 text-sm text-control-placeholder ${- passwordHint ? "text-error" : ""- }`}- >- {t("settings.profile.password-hint")}- <Tooltip- content={- <ul className="list-none text-sm">- {passwordChecks.map((check, i) => (- <li key={i} className="flex gap-x-1 items-center">- {check.matched ? (- <CircleCheck className="w-4 text-green-400" />- ) : (- <CircleAlert className="w-4 text-red-400" />- )}- {check.text}- </li>- ))}- </ul>- }- >- <CircleAlert className="w-4 cursor-help" />- </Tooltip>- </span>- <div className="relative flex w-full items-center">- <Input- id="user-form-password"- aria-labelledby="user-form-password-title"- type={showPassword ? "text" : "password"}- value={password}- onChange={(e) => setPassword(e.target.value)}- autoComplete="new-password"- placeholder={t("common.sensitive-placeholder")}- disabled={!allowUpdate}- className={passwordHint ? "border-error" : ""}- />- <button- type="button"- className="absolute right-3 cursor-pointer"- onClick={() => setShowPassword(!showPassword)}- >- {showPassword ? (- <Eye className="w-4 h-4" />- ) : (- <EyeOff className="w-4 h-4" />- )}- </button>- </div>- </FormField>-- <FormField>- <FormTitle id="user-form-password-confirm-title">- {t("settings.profile.password-confirm")}- </FormTitle>- <div className="relative flex w-full items-center">- <Input- id="user-form-password-confirm"- aria-labelledby="user-form-password-confirm-title"- type={showPassword ? "text" : "password"}- value={passwordConfirm}- onChange={(e) => setPasswordConfirm(e.target.value)}- autoComplete="new-password"- placeholder={t(- "settings.profile.password-confirm-placeholder"- )}- disabled={!allowUpdate}- className={passwordMismatch ? "border-error" : ""}- />- <button- type="button"- className="absolute right-3 cursor-pointer"- onClick={() => setShowPassword(!showPassword)}- >- {showPassword ? (- <Eye className="w-4 h-4" />- ) : (- <EyeOff className="w-4 h-4" />- )}- </button>- </div>- {passwordMismatch && (- <FormError className="pl-1">- {t("settings.profile.password-mismatch")}- </FormError>- )}- </FormField>- </div>- </div>- </SheetBody>-- <SheetFooter>- <Button appearance="outline" onClick={onClose}>- {t("common.cancel")}- </Button>- <Button- disabled={!allowConfirm || !hasPermission || isRequesting}- onClick={handleSubmit}- >- {isEditMode ? t("common.update") : t("common.create")}- </Button>- </SheetFooter>- </>- );-}-// ============================================================// UsersPage (main)// ============================================================@@ -976,7 +382,10 @@ export function UsersPage() {fetchList: fetchInactiveUsers,});- const handleActiveUserUpdated = (user: User) => {+ const handleActiveUserUpdated = (user: User, replaces?: User) => {+ if (replaces && replaces.name !== user.name) {+ activeUsers.removeCache(replaces);+ }if (user.state === State.DELETED) {// Deactivated: remove from active list, add to inactive listactiveUsers.removeCache(user);@@ -986,7 +395,10 @@ export function UsersPage() {}};- const handleInactiveUserUpdated = (user: User) => {+ const handleInactiveUserUpdated = (user: User, replaces?: User) => {+ if (replaces && replaces.name !== user.name) {+ inactiveUsers.removeCache(replaces);+ }if (user.state === State.ACTIVE) {// Restored: remove from inactive list, add to active listinactiveUsers.removeCache(user);@@ -1024,10 +436,7 @@ export function UsersPage() {</Button><Buttondisabled={!hasWorkspacePermissionV2("bb.users.create")}- onClick={() => {- setEditingUser(create(UserSchema, { title: "" }));- setShowCreateUserDrawer(true);- }}+ onClick={() => setShowCreateUserDrawer(true)}><Plus className="h-4 w-4 mr-1" />{t("common.create")}@@ -1046,10 +455,7 @@ export function UsersPage() {<UserTableusers={activeUsers.dataList}onUserUpdated={handleActiveUserUpdated}- onUserSelected={(user) => {- setEditingUser(user);- setShowCreateUserDrawer(true);- }}+ onUserEdit={(user) => setEditingUser(user)}onGroupSelected={handleGroupSelected}/><PagedTableFooter@@ -1097,10 +503,7 @@ export function UsersPage() {<UserTableusers={inactiveUsers.dataList}onUserUpdated={handleInactiveUserUpdated}- onUserSelected={(user) => {- setEditingUser(user);- setShowCreateUserDrawer(true);- }}+ onUserEdit={(user) => setEditingUser(user)}onGroupSelected={handleGroupSelected}/><PagedTableFooter@@ -1117,21 +520,25 @@ export function UsersPage() {)}</div>- <CreateUserSheet+ <UserFormSheetopen={showCreateUserDrawer}- user={editingUser}- onClose={() => {- setShowCreateUserDrawer(false);- setEditingUser(undefined);- }}+ onClose={() => setShowCreateUserDrawer(false)}onCreated={(user) => {activeUsers.updateCache([user]);}}+ />++ <EditUserSheet+ open={!!editingUser}+ user={editingUser}+ onClose={() => setEditingUser(undefined)}onUpdated={(user) => {- activeUsers.updateCache([user]);+ // updateCache appends when the name is absent, so writing to both+ // lists would file an active user into the inactive one as well.if (user.state === State.DELETED) {- activeUsers.removeCache(user);inactiveUsers.updateCache([user]);+ } else {+ activeUsers.updateCache([user]);}}}/>diff --git a/frontend/src/routes/workspace/profile/ProfilePage.test.tsx b/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsxsimilarity index 61%rename from frontend/src/routes/workspace/profile/ProfilePage.test.tsxrename to frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsxindex 564d6d049c..7e38eed4e2 100644--- a/frontend/src/routes/workspace/profile/ProfilePage.test.tsx+++ b/frontend/src/routes/workspace/profile/AccountSettingsPage.test.tsx@@ -26,18 +26,11 @@ const updatedCurrentUser = {const mocks = vi.hoisted(() => ({useCurrentUser: vi.fn(() => legacyCurrentUser),- useAuthStore: vi.fn(() => ({- updateCurrentUserNameForEmailChange: vi.fn(),- })),getWorkspaceRolesByName: vi.fn(() => new Set<string>()),- fetchWorkspaceIamPolicy: vi.fn(async () => undefined),hasFeature: vi.fn(() => true),pushNotification: vi.fn(),- getUserByIdentifier: vi.fn(),- getOrFetchUserByIdentifier: vi.fn(),- updateUser: vi.fn(async () => updatedCurrentUser),+ updateUser: vi.fn(async (_request: unknown) => updatedCurrentUser),updateEmail: vi.fn(),- routerReplace: vi.fn(),routerPush: vi.fn(),migrateUserStorage: vi.fn(),setDocumentTitle: vi.fn(),@@ -54,17 +47,13 @@ vi.mock("@/hooks/useUnsavedChangesGuard", () => ({vi.mock("@/stores/app", () => {const buildState = () => ({- getUserByIdentifier: mocks.getUserByIdentifier,- getOrFetchUserByIdentifier: mocks.getOrFetchUserByIdentifier,updateUser: mocks.updateUser,updateEmail: mocks.updateEmail,updateCurrentUserNameForEmailChange: () => {},roleList: [],workspacePolicy: undefined,getWorkspaceRolesByName: mocks.getWorkspaceRolesByName,- fetchWorkspaceIamPolicy: mocks.fetchWorkspaceIamPolicy,hasFeature: () => mocks.hasFeature(),- // Migrated off the Pinia actuator/setting store mocks.isSaaSMode: () => false,getWorkspaceProfile: () => ({passwordRestriction: undefined,@@ -80,14 +69,14 @@ vi.mock("@/stores/app", () => {vi.mock("@/stores", () => ({hasFeature: mocks.hasFeature,pushNotification: mocks.pushNotification,- useAuthStore: mocks.useAuthStore,}));vi.mock("@/app/router", async (importOriginal) => ({...(await importOriginal<typeof import("@/app/router")>()),router: {- replace: mocks.routerReplace,push: mocks.routerPush,+ replace: vi.fn(),+ resolve: () => ({ href: "#" }),},}));@@ -138,7 +127,11 @@ vi.mock("@/components/ui/input", () => ({}));vi.mock("@/components/ui/dialog", () => ({- Dialog: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ // Honor `open` — a mock that renders closed dialogs would hide the very+ // thing these tests check, namely that password fields are not sitting in+ // the page waiting to be swept up by the profile Save.+ Dialog: ({ open, children }: { open?: boolean; children: React.ReactNode }) =>+ open ? <>{children}</> : null,DialogContent: ({ children }: { children: React.ReactNode }) => (<div>{children}</div>),@@ -190,12 +183,9 @@ vi.mock("./UserPasswordSection", () => ({UserPasswordSection: () => <div data-testid="password-section" />,}));-vi.mock(- "@/routes/workspace/two-factor/RegenerateRecoveryCodesView",- () => ({- RegenerateRecoveryCodesView: () => <div data-testid="recovery-codes" />,- })-);+vi.mock("@/routes/workspace/two-factor/RegenerateRecoveryCodesView", () => ({+ RegenerateRecoveryCodesView: () => <div data-testid="recovery-codes" />,+}));vi.mock("react-i18next", () => ({useTranslation: () => ({@@ -204,7 +194,7 @@ vi.mock("react-i18next", () => ({initReactI18next: { type: "3rdParty", init: () => {} },}));-let ProfilePage: typeof import("./ProfilePage").ProfilePage;+let AccountSettingsPage: typeof import("./AccountSettingsPage").AccountSettingsPage;const renderIntoContainer = (element: ReactElement) => {const container = document.createElement("div");@@ -224,44 +214,93 @@ const renderIntoContainer = (element: ReactElement) => {};};+const findButton = (container: HTMLElement, text: string) =>+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === text+ );++const setInputValue = async (input: HTMLInputElement, value: string) => {+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ )?.set?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+};+beforeEach(async () => {vi.clearAllMocks();- ({ ProfilePage } = await import("./ProfilePage"));+ ({ AccountSettingsPage } = await import("./AccountSettingsPage"));});-describe("ProfilePage", () => {- test("renders the updated self profile from the update response", async () => {- const { container, render, unmount } = renderIntoContainer(<ProfilePage />);+describe("AccountSettingsPage", () => {+ test("saves the display name and renders the update response", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <AccountSettingsPage />+ );await render();- expect(container.textContent).toContain("Old Alice");+ const titleInput = container.querySelector("input")!;+ expect(titleInput.value).toBe("Old Alice");++ // Nothing changed yet, so the profile section save is inert.+ expect(findButton(container, "common.save")?.disabled).toBe(true);++ await setInputValue(titleInput, "New Alice");+ expect(findButton(container, "common.save")?.disabled).toBe(false);- const edit = [...container.querySelectorAll("button")].find(- (button) => button.textContent === "common.edit"- );await act(async () => {- edit?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ findButton(container, "common.save")?.dispatchEvent(+ new MouseEvent("click", { bubbles: true })+ );+ await Promise.resolve();});- const titleInput = container.querySelector("input")!;- await act(async () => {- Object.getOwnPropertyDescriptor(- HTMLInputElement.prototype,- "value"- )?.set?.call(titleInput, "New Alice");- titleInput.dispatchEvent(new Event("input", { bubbles: true }));+ expect(mocks.updateUser).toHaveBeenCalledTimes(1);+ expect(mocks.updateUser.mock.calls[0][0]).toMatchObject({+ updateMask: { paths: ["title"] },});+ expect(container.querySelector("input")!.value).toBe("New Alice");++ unmount();+ });++ test("does not let you change your own sign-in email", async () => {+ // Moving an account to another address changes the identity someone signs+ // in with. That is an administrative act, done from the Users directory,+ // not something to self-serve — even as an admin on your own account.+ mocks.hasWorkspacePermissionV2.mockReturnValue(true);- const save = [...container.querySelectorAll("button")].find(- (button) => button.textContent === "common.save"+ const { container, render, unmount } = renderIntoContainer(+ <AccountSettingsPage />);- await act(async () => {- save?.dispatchEvent(new MouseEvent("click", { bubbles: true }));- await Promise.resolve();- });+ await render();++ expect(findButton(container, "settings.account.change-email")).toBeUndefined();+ expect(container.textContent).toContain("settings.account.email-managed");++ unmount();+ });++ test("password is behind its own dialog, not a field in the profile form", async () => {+ const { container, render, unmount } = renderIntoContainer(+ <AccountSettingsPage />+ );++ await render();- expect(mocks.updateUser).toHaveBeenCalled();- expect(container.textContent).toContain("New Alice");+ // Changing a password signs the user out everywhere, so it must not be+ // reachable as a field the profile Save happens to sweep up. Until the+ // dialog is opened there are no password inputs on the page at all.+ expect(+ container.querySelector('[data-testid="password-section"]')+ ).toBeNull();++ // The page offers it as a deliberate, separately-confirmed action.+ const trigger = findButton(container, "settings.account.update-password");+ expect(trigger).not.toBeNull();+ expect(trigger?.disabled).toBe(false);unmount();});diff --git a/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsxnew file mode 100644index 0000000000..140a3c874e--- /dev/null+++ b/frontend/src/routes/workspace/profile/AccountSettingsPage.tsx@@ -0,0 +1,483 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import type { ConnectError } from "@connectrpc/connect";+import { Ellipsis } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { router } from "@/app/router";+import { ACCOUNT_ROUTE_TWO_FACTOR } from "@/app/router/handles";+import { FeatureBadge } from "@/components/FeatureBadge";+import { LearnMoreLink } from "@/components/LearnMoreLink";+import { getAvatarColor, getInitials } from "@/components/UserAvatar";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { FeatureModal } from "@/components/ui/feature-modal";+import { Input } from "@/components/ui/input";+import { WorkspacePageLayout } from "@/components/WorkspacePageLayout";+import { useCurrentUser } from "@/hooks/useAppState";+import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";+import { RegenerateRecoveryCodesView } from "@/routes/workspace/two-factor/RegenerateRecoveryCodesView";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import { AccountType, getAccountTypeByEmail } from "@/types";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";+import { hasWorkspacePermissionV2, setDocumentTitle } from "@/utils";+import { SettingsCard, SettingsRow } from "./SettingsCard";+import { getPasswordErrors, UserPasswordSection } from "./UserPasswordSection";++/**+ * Account settings for the signed-in user.+ *+ * Everything here is something a person does to their *own* account: rename+ * themselves, change how they are reached, rotate their password, enroll a+ * second factor. Administering somebody else's account is a different job, done+ * from the Users directory's row menu.+ */+export function AccountSettingsPage() {+ const { t } = useTranslation();++ const legacyCurrentUser = useCurrentUser();+ const [currentUser, setCurrentUser] = useState(legacyCurrentUser);++ const updateUser = useAppStore((state) => state.updateUser);+ const passwordRestriction = useAppStore(+ (s) => s.getWorkspaceProfile().passwordRestriction+ );+ const requireMfa = useAppStore((s) => s.getWorkspaceProfile().requireMfa);+ const has2FAFeature = useAppStore((s) =>+ s.hasFeature(PlanFeature.FEATURE_TWO_FA)+ );++ const user = currentUser;+ const isEndUser = getAccountTypeByEmail(user.email) === AccountType.USER;+ // Email is a workspace-managed identity: the server gates UpdateEmail on+ // bb.users.updateEmail, so most people see it as a read-only fact here.+ const isMFAEnabled = user.mfaEnabled;++ // --- Profile section ---+ const [title, setTitle] = useState(user.title);+ const [phone, setPhone] = useState(user.phone);+ const [savingProfile, setSavingProfile] = useState(false);++ // --- Password section ---+ const [password, setPassword] = useState("");+ const [passwordConfirm, setPasswordConfirm] = useState("");+ const [savingPassword, setSavingPassword] = useState(false);++ // --- Password + 2FA dialogs ---+ const [showChangePassword, setShowChangePassword] = useState(false);+ const [showFeatureModal, setShowFeatureModal] = useState(false);+ const [showDisable2FAConfirm, setShowDisable2FAConfirm] = useState(false);+ const [showRegenerateView, setShowRegenerateView] = useState(false);+ const [disabling2FA, setDisabling2FA] = useState(false);++ useEffect(() => {+ setCurrentUser(legacyCurrentUser);+ }, [legacyCurrentUser]);++ // Re-seed the editable fields only when the signed-in account changes, not+ // on every store write: any self-update reissues `legacyCurrentUser`, and+ // resetting here would discard edits typed while a save was in flight.+ useEffect(() => {+ setTitle(legacyCurrentUser.title);+ setPhone(legacyCurrentUser.phone);+ }, [legacyCurrentUser.name]);++ useEffect(() => {+ setDocumentTitle(t("settings.account.self"));+ }, [t]);++ const profileDirty = title !== user.title || phone !== user.phone;+ const passwordErrors = useMemo(+ () => getPasswordErrors(password, passwordConfirm, passwordRestriction),+ [password, passwordConfirm, passwordRestriction]+ );+ const allowSavePassword =+ password.length > 0 &&+ !passwordErrors.hasHint &&+ !passwordErrors.hasMismatch;++ useUnsavedChangesGuard(profileDirty);++ const notifyError = useCallback((error: unknown) => {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: (error as ConnectError).message,+ });+ }, []);++ const notifyUpdated = useCallback(() => {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ }, [t]);++ const handleSaveProfile = useCallback(async () => {+ if (!profileDirty) return;+ const paths: string[] = [];+ if (title !== user.title) paths.push("title");+ if (phone !== user.phone) paths.push("phone");+ setSavingProfile(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { ...user, title, phone },+ updateMask: create(FieldMaskSchema, { paths }),+ })+ );+ setCurrentUser(updated);+ notifyUpdated();+ } catch (error) {+ notifyError(error);+ } finally {+ setSavingProfile(false);+ }+ }, [+ profileDirty,+ title,+ phone,+ user,+ updateUser,+ notifyUpdated,+ notifyError,+ ]);++ const handleUpdatePassword = useCallback(async () => {+ if (!allowSavePassword) return;+ setSavingPassword(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { ...user, password },+ updateMask: create(FieldMaskSchema, { paths: ["password"] }),+ })+ );+ setCurrentUser(updated);+ setPassword("");+ setPasswordConfirm("");+ setShowChangePassword(false);+ notifyUpdated();+ } catch (error) {+ notifyError(error);+ } finally {+ setSavingPassword(false);+ }+ }, [+ allowSavePassword,+ password,+ user,+ updateUser,+ notifyUpdated,+ notifyError,+ ]);++ const handleEnable2FA = useCallback(() => {+ if (!has2FAFeature) {+ setShowFeatureModal(true);+ return;+ }+ router.push({ name: ACCOUNT_ROUTE_TWO_FACTOR });+ }, [has2FAFeature]);++ const handleRequestDisable2FA = useCallback(() => {+ // A workspace-wide 2FA requirement outranks the individual preference;+ // only an admin who can relax the policy may turn their own factor off.+ if (requireMfa && !hasWorkspacePermissionV2("bb.policies.update")) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("two-factor.messages.cannot-disable"),+ });+ return;+ }+ setShowDisable2FAConfirm(true);+ }, [requireMfa, t]);++ const handleDisable2FA = useCallback(async () => {+ if (disabling2FA) return;+ setDisabling2FA(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { name: user.name, mfaEnabled: false },+ updateMask: create(FieldMaskSchema, { paths: ["mfa_enabled"] }),+ })+ );+ setCurrentUser(updated);+ setShowDisable2FAConfirm(false);+ setShowRegenerateView(false);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("two-factor.messages.2fa-disabled"),+ });+ } catch (error) {+ notifyError(error);+ } finally {+ setDisabling2FA(false);+ }+ }, [disabling2FA, user.name, updateUser, notifyError, t]);++ return (+ <WorkspacePageLayout>+ <div className="mx-auto flex w-full max-w-2xl flex-col gap-y-8">+ <div className="flex items-center gap-x-4">+ <div+ className="flex size-11 shrink-0 items-center justify-center rounded-full text-base font-bold text-white"+ style={{ backgroundColor: getAvatarColor(user.email) }}+ >+ {getInitials(title || user.email)}+ </div>+ <div className="flex min-w-0 flex-col gap-y-0.5">+ <h1 className="text-xl font-medium text-main">+ {t("settings.account.self")}+ </h1>+ <p className="text-sm text-control-light">+ {t("settings.account.description")}+ </p>+ </div>+ </div>++ {/* Who you are. Email leads because it identifies the account; the two+ fields you can actually change follow it.++ Workspace role is deliberately absent. It is not actionable here,+ it is already on the members page, and rendering it made a personal+ settings page read the entire workspace IAM policy — the full+ membership graph — to draw one badge. */}+ <div className="flex flex-col gap-y-3">+ <SettingsCard>+ <SettingsRow+ label={t("settings.profile.email")}+ description={t("settings.account.email-managed")}+ >+ <span className="text-sm text-main">{user.email}</span>+ </SettingsRow>++ <SettingsRow label={t("settings.profile.display-name")}>+ <Input+ value={title}+ autoComplete="off"+ maxLength={200}+ className="w-56"+ placeholder={t("settings.profile.display-name-placeholder")}+ onChange={(e) => setTitle(e.target.value)}+ />+ </SettingsRow>++ {isEndUser && (+ <SettingsRow+ label={t("settings.profile.phone")}+ description={t("settings.profile.phone-tips")}+ >+ <Input+ value={phone}+ type="tel"+ autoComplete="off"+ className="w-56"+ onChange={(e) => setPhone(e.target.value)}+ />+ </SettingsRow>+ )}+ </SettingsCard>++ <div className="flex justify-end">+ <Button+ disabled={!profileDirty || savingProfile}+ onClick={handleSaveProfile}+ >+ {t("common.save")}+ </Button>+ </div>+ </div>++ {/* How you prove it is you. Password and two-factor answer the same+ question, so they share a group rather than getting a heading each. */}+ {isEndUser && (+ <div className="flex flex-col gap-y-3">+ <h2 className="text-sm font-medium text-main">+ {t("settings.account.security")}+ </h2>+ <SettingsCard>+ <SettingsRow+ label={t("settings.profile.password")}+ description={t("settings.account.password-notice")}+ >+ <Button+ appearance="outline"+ onClick={() => setShowChangePassword(true)}+ >+ {t("settings.account.update-password")}+ </Button>+ </SettingsRow>++ <SettingsRow+ align="start"+ label={+ <span className="flex items-center">+ {t("two-factor.self")}+ <FeatureBadge+ feature={PlanFeature.FEATURE_TWO_FA}+ className="ml-2 inline-flex text-accent"+ />+ </span>+ }+ description={+ <>+ {t("two-factor.description")}{" "}+ <LearnMoreLink+ href="https://docs.bytebase.com/administration/2fa?source=console"+ className="ml-1 text-accent"+ />+ </>+ }+ >+ {isMFAEnabled && (+ <Button+ variant="destructive"+ onClick={handleRequestDisable2FA}+ >+ {t("common.disable")}+ </Button>+ )}+ <Button appearance="outline" onClick={handleEnable2FA}>+ {isMFAEnabled ? t("common.edit") : t("common.enable")}+ </Button>+ </SettingsRow>++ {isMFAEnabled && (+ <SettingsRow+ align="start"+ label={t("two-factor.recovery-codes.self")}+ description={t("two-factor.recovery-codes.description")}+ >+ {!showRegenerateView && (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={t("common.more")}+ className="cursor-pointer rounded-xs p-1 outline-hidden hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent"+ >+ <Ellipsis className="size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="min-w-36">+ <DropdownMenuItem+ className="py-1.5"+ onClick={() => setShowRegenerateView(true)}+ >+ {t("common.regenerate")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </SettingsRow>+ )}+ </SettingsCard>++ {/* Gated on MFA too: disabling the second factor while this panel+ is open would otherwise leave it stranded on screen, offering+ to regenerate recovery codes the account no longer has. */}+ {isMFAEnabled && showRegenerateView && (+ <RegenerateRecoveryCodesView+ recoveryCodes={currentUser.tempRecoveryCodes}+ onClose={() => setShowRegenerateView(false)}+ />+ )}+ </div>+ )}++ <FeatureModal+ open={showFeatureModal}+ feature={PlanFeature.FEATURE_TWO_FA}+ onOpenChange={setShowFeatureModal}+ />++ {/* Change my email */}+ <Dialog+ open={showChangePassword}+ onOpenChange={(next) => {+ setShowChangePassword(next);+ if (!next) {+ setPassword("");+ setPasswordConfirm("");+ }+ }}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>{t("settings.account.update-password")}</DialogTitle>+ <DialogDescription>+ {t("settings.account.password-notice")}+ </DialogDescription>+ <div className="mt-4">+ <UserPasswordSection+ password={password}+ passwordConfirm={passwordConfirm}+ onPasswordChange={setPassword}+ onPasswordConfirmChange={setPasswordConfirm}+ passwordRestriction={passwordRestriction}+ required={false}+ />+ </div>+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ disabled={savingPassword}+ onClick={() => setShowChangePassword(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={!allowSavePassword || savingPassword}+ onClick={handleUpdatePassword}+ >+ {t("settings.account.update-password")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>++ {/* Disable my 2FA */}+ <Dialog+ open={showDisable2FAConfirm}+ onOpenChange={setShowDisable2FAConfirm}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>{t("two-factor.disable.self")}</DialogTitle>+ <DialogDescription>+ {t("two-factor.disable.description")}+ </DialogDescription>+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ onClick={() => setShowDisable2FAConfirm(false)}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant="destructive"+ disabled={disabling2FA}+ onClick={handleDisable2FA}+ >+ {t("common.disable")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ </WorkspacePageLayout>+ );+}diff --git a/frontend/src/routes/workspace/profile/ProfilePage.tsx b/frontend/src/routes/workspace/profile/ProfilePage.tsxdeleted file mode 100644index 8ba9b4d95f..0000000000--- a/frontend/src/routes/workspace/profile/ProfilePage.tsx+++ /dev/null@@ -1,645 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import type { ConnectError } from "@connectrpc/connect";-import { cloneDeep, isEqual } from "lodash-es";-import { Ellipsis, ShieldAlert } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useTranslation } from "react-i18next";-import { router } from "@/app/router";-import {- SETTING_ROUTE_PROFILE_TWO_FACTOR,- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,- WORKSPACE_ROUTE_404,- WORKSPACE_ROUTE_USER_PROFILE,-} from "@/app/router/handles";-import { FeatureBadge } from "@/components/FeatureBadge";-import { LearnMoreLink } from "@/components/LearnMoreLink";-import { RouterLink } from "@/components/RouterLink";-import { getAvatarColor, getInitials } from "@/components/UserAvatar";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogTitle,-} from "@/components/ui/dialog";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { FeatureModal } from "@/components/ui/feature-modal";-import { Input } from "@/components/ui/input";-import { useCurrentUser } from "@/hooks/useAppState";-import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";-import { displayRoleTitleFromList } from "@/lib/role";-import { RegenerateRecoveryCodesView } from "@/routes/workspace/two-factor/RegenerateRecoveryCodesView";-import { hasFeature, pushNotification } from "@/stores";-import { useAppStore } from "@/stores/app";-import {- AccountType,- ALL_USERS_USER_EMAIL,- getAccountTypeByEmail,- isValidUserName,- unknownUser,-} from "@/types";-import { State } from "@/types/proto-es/v1/common_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";-import { hasWorkspacePermissionV2, setDocumentTitle, sortRoles } from "@/utils";-import { migrateUserStorage } from "@/utils/storage-migrate";-import { EmailInput } from "./EmailInput";-import { getPasswordErrors, UserPasswordSection } from "./UserPasswordSection";--interface ProfilePageProps {- principalEmail?: string;-}--export function ProfilePage({ principalEmail }: ProfilePageProps) {- const { t } = useTranslation();-- const updateCurrentUserNameForEmailChange = useAppStore(- (state) => state.updateCurrentUserNameForEmailChange- );- const getOrFetchUserByIdentifier = useAppStore(- (state) => state.getOrFetchUserByIdentifier- );- const updateUser = useAppStore((state) => state.updateUser);- const updateEmail = useAppStore((state) => state.updateEmail);- const roleList = useAppStore((state) => state.roleList);- const workspacePolicy = useAppStore((state) => state.workspacePolicy);- const getWorkspaceRolesByName = useAppStore(- (state) => state.getWorkspaceRolesByName- );-- // --- Reactive Vue state ---- const legacyCurrentUser = useCurrentUser();- const [currentUser, setCurrentUser] = useState(legacyCurrentUser);- const principalUser = useAppStore((state) =>- principalEmail ? state.getUserByIdentifier(principalEmail) : undefined- );-- const user = principalEmail ? (principalUser ?? unknownUser()) : currentUser;-- const userRoles = useMemo(- () => [...getWorkspaceRolesByName(user.name)],- // Recompute when the policy changes; getWorkspaceRolesByName reads it.- [getWorkspaceRolesByName, user.name, workspacePolicy]- );-- const passwordRestriction = useAppStore(- (s) => s.getWorkspaceProfile().passwordRestriction- );-- const isSaaSMode = useAppStore((s) => s.isSaaSMode());-- const has2FAFeature = useAppStore((s) =>- s.hasFeature(PlanFeature.FEATURE_TWO_FA)- );-- const requireMfa = useAppStore((s) => s.getWorkspaceProfile().requireMfa);-- const tempRecoveryCodes = currentUser.tempRecoveryCodes;-- // --- Derived values ---- const isSelf = currentUser.name === user.name;-- const allowGet = isSelf || hasWorkspacePermissionV2("bb.users.get");-- const allowEdit = useMemo(() => {- if (- user.email === ALL_USERS_USER_EMAIL ||- getAccountTypeByEmail(user.email) !== AccountType.USER- ) {- return false;- }- if (user.state !== State.ACTIVE) {- return false;- }- if (isSelf) {- return true;- }- return !isSaaSMode && hasWorkspacePermissionV2("bb.users.update");- }, [user, isSelf, isSaaSMode]);-- const allowEditEmail = hasWorkspacePermissionV2("bb.users.updateEmail");-- const isMFAEnabled = user.mfaEnabled;- const showRegenerateRecoveryCodes =- isMFAEnabled && user.name === currentUser.name;-- // --- Local state ---- const [editing, setEditing] = useState(false);- const [editingUser, setEditingUser] = useState<User | undefined>(undefined);- const [passwordConfirm, setPasswordConfirm] = useState("");- const [saving, setSaving] = useState(false);- const [showFeatureModal, setShowFeatureModal] = useState(false);- const [showDisable2FAConfirm, setShowDisable2FAConfirm] = useState(false);- const [showRegenerateView, setShowRegenerateView] = useState(false);-- const editNameRef = useRef<HTMLInputElement>(null);-- // --- Password validity ---- const passwordErrors = useMemo(() => {- if (!editingUser) return { hasHint: false, hasMismatch: false };- return getPasswordErrors(- editingUser.password ?? "",- passwordConfirm,- passwordRestriction- );- }, [editingUser, passwordConfirm, passwordRestriction]);-- const allowSaveEdit = useMemo(() => {- if (!editingUser) return false;- return (- !isEqual(user, editingUser) &&- !passwordErrors.hasHint &&- !passwordErrors.hasMismatch- );- }, [user, editingUser, passwordErrors]);-- // --- Effects ----- useEffect(() => {- setCurrentUser(legacyCurrentUser);- }, [legacyCurrentUser]);-- // On mount: validate account type and fetch user- useEffect(() => {- if (principalEmail) {- const userType = getAccountTypeByEmail(principalEmail);- if (userType !== AccountType.USER) {- router.replace({ name: WORKSPACE_ROUTE_404 });- return;- }- (async () => {- const fetched = await getOrFetchUserByIdentifier({- identifier: principalEmail,- fallback: false,- });- if (!isValidUserName(fetched.name)) {- router.replace({ name: WORKSPACE_ROUTE_404 });- }- })();- }- }, [principalEmail]);-- // Keyboard shortcuts — refs are assigned after callbacks are defined below- const saveEditRef = useRef<() => void>(() => {});- const cancelEditRef = useRef<() => void>(() => {});-- // Route change guard- useUnsavedChangesGuard(editing && allowSaveEdit);-- // Document title- useEffect(() => {- setDocumentTitle(user.title);- }, [user.title]);-- // --- Actions ---- const editUser = useCallback(() => {- setEditingUser(cloneDeep(user));- setEditing(true);- setPasswordConfirm("");- setTimeout(() => editNameRef.current?.focus(), 0);- }, [user]);-- const cancelEdit = useCallback(() => {- setEditingUser(undefined);- setEditing(false);- }, []);-- const updateEditingUser = useCallback(- <K extends keyof User>(field: K, value: User[K]) => {- setEditingUser((prev) => {- if (!prev) return prev;- return { ...prev, [field]: value };- });- },- []- );-- const saveEdit = useCallback(async () => {- if (!editingUser) return;-- const emailChanged = editingUser.email !== user.email;- const updateMaskPaths: string[] = [];-- if (editingUser.title !== user.title) {- updateMaskPaths.push("title");- }- if (editingUser.phone !== user.phone) {- updateMaskPaths.push("phone");- }- if (editingUser.password !== "") {- updateMaskPaths.push("password");- }-- setSaving(true);- try {- if (emailChanged) {- const oldEmail = user.email;- const updatedUser = await updateEmail(oldEmail, editingUser.email);- migrateUserStorage(oldEmail, editingUser.email);- if (isSelf) {- updateCurrentUserNameForEmailChange(updatedUser.name);- setCurrentUser(updatedUser);- }- }-- if (updateMaskPaths.length > 0) {- const updatedUser = await updateUser(- create(UpdateUserRequestSchema, {- user: editingUser,- updateMask: create(FieldMaskSchema, {- paths: updateMaskPaths,- }),- regenerateRecoveryCodes: false,- regenerateTempMfaSecret: false,- })- );- if (isSelf) {- setCurrentUser(updatedUser);- }- }-- if (emailChanged || updateMaskPaths.length > 0) {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: (error as ConnectError).message || "Failed to update user",- });- return;- } finally {- setSaving(false);- }-- setEditingUser(undefined);- setEditing(false);-- if (emailChanged && principalEmail) {- router.replace({- name: WORKSPACE_ROUTE_USER_PROFILE,- params: { principalEmail: editingUser.email },- });- }- }, [editingUser, user, isSelf, principalEmail, t]);-- // Assign refs for keyboard shortcuts now that callbacks are defined- saveEditRef.current = saveEdit;- cancelEditRef.current = cancelEdit;-- useEffect(() => {- const handler = (e: KeyboardEvent) => {- if (e.isComposing) return;- if (editing) {- if (e.code === "Escape") {- cancelEditRef.current();- } else if (e.code === "Enter" && e.metaKey) {- if (allowSaveEdit) {- saveEditRef.current();- }- }- }- };- document.addEventListener("keydown", handler);- return () => document.removeEventListener("keydown", handler);- }, [editing, allowSaveEdit]);-- const enable2FA = useCallback(() => {- if (!has2FAFeature) {- setShowFeatureModal(true);- return;- }- router.push({ name: SETTING_ROUTE_PROFILE_TWO_FACTOR });- }, [has2FAFeature]);-- const disable2FA = useCallback(() => {- if (requireMfa && !hasWorkspacePermissionV2("bb.policies.update")) {- pushNotification({- module: "bytebase",- style: "WARN",- title: t("two-factor.messages.cannot-disable"),- });- } else {- setShowDisable2FAConfirm(true);- }- }, [requireMfa, t]);-- const handleDisable2FA = useCallback(async () => {- const updatedUser = await updateUser(- create(UpdateUserRequestSchema, {- user: {- name: user.name,- mfaEnabled: false,- },- updateMask: create(FieldMaskSchema, {- paths: ["mfa_enabled"],- }),- })- );- if (isSelf) {- setCurrentUser(updatedUser);- }- setShowDisable2FAConfirm(false);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("two-factor.messages.2fa-disabled"),- });- }, [user.name, t]);-- // --- No permission ---- if (!allowGet) {- return (- <main className="pt-4 flex-1 h-full relative pb-8 focus:outline-hidden xl:order-last px-4">- <div- role="alert"- className="relative w-full rounded-xs border px-4 py-3 text-sm flex gap-x-3 items-start border-error/30 bg-error/5 text-error"- >- <ShieldAlert className="h-5 w-5 shrink-0 mt-0.5" />- <div className="flex flex-col gap-2">- <h5 className="font-medium leading-tight">- {t("common.missing-permission")}- </h5>- <div>- {t("common.required-permission")}- <ul className="list-disc pl-4">- <li>bb.users.get</li>- </ul>- </div>- </div>- </div>- </main>- );- }-- // --- Main render ---- return (- <main- className="pt-4 flex-1 h-full relative pb-8 focus:outline-hidden xl:order-last"- tabIndex={0}- >- <div>- {/* Profile header */}- <div>- <div className="-mt-4 h-32 bg-accent lg:h-48" />- <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">- <div className="-mt-20 sm:flex sm:items-end sm:gap-x-5">- {/* Large avatar */}- <div- className="rounded-full flex items-center justify-center text-white font-bold shrink-0 h-32 w-32 text-4xl ring-4 ring-white"- style={{ backgroundColor: getAvatarColor(user.title) }}- >- {getInitials(user.title)}- </div>- <div className="mt-6 sm:flex-1 sm:min-w-0 sm:flex sm:items-center sm:justify-end sm:gap-x-6 sm:pb-1">- <div className="mt-6 flex flex-row justify-stretch gap-x-2">- {allowEdit && (- <>- {editing ? (- <>- <Button- appearance="secondary"- disabled={saving}- onClick={cancelEdit}- >- {t("common.cancel")}- </Button>- <Button- disabled={!allowSaveEdit || saving}- onClick={saveEdit}- >- {t("common.save")}- </Button>- </>- ) : (- <Button appearance="outline" onClick={editUser}>- {t("common.edit")}- </Button>- )}- </>- )}- </div>- </div>- </div>- <div className="block mt-6 min-w-0 flex-1">- {editing ? (- <Input- ref={editNameRef}- autoComplete="off"- value={editingUser?.title ?? ""}- className="w-64 text-lg"- onChange={(e) => updateEditingUser("title", e.target.value)}- />- ) : (- <h1 className="pb-1.5 text-2xl font-bold text-main truncate">- {user.title}- </h1>- )}- </div>- </div>- </div>-- {/* Description list */}- <div className="mt-6 mb-2 max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">- <dl className="grid grid-cols-1 gap-x-4 gap-y-8 sm:grid-cols-3">- {/* Role */}- <div className="sm:col-span-1">- <dt className="text-sm font-medium text-control-light">- {t("settings.profile.role")}- </dt>- <dd className="mt-1 text-sm text-main">- <div className="flex flex-row justify-start items-start flex-wrap gap-2">- {sortRoles(userRoles).map((role) => (- <span- key={role}- className="inline-flex items-center rounded-full px-3 py-0.5 text-sm font-medium bg-control-bg text-control"- >- {displayRoleTitleFromList(role, roleList)}- </span>- ))}- </div>- {!hasFeature(PlanFeature.FEATURE_IAM) && (- <RouterLink- to={{ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION }}- className="normal-link"- >- {t("settings.profile.subscription")}- </RouterLink>- )}- </dd>- </div>-- {/* Email */}- <div className="sm:col-span-1">- <dt className="text-sm font-medium text-control-light">- {t("settings.profile.email")}- </dt>- <dd className="mt-1 text-sm text-main">- {editing && allowEditEmail ? (- <EmailInput- value={editingUser?.email ?? ""}- onChange={(val) => updateEditingUser("email", val)}- />- ) : (- user.email- )}- </dd>- </div>-- {/* Phone */}- {getAccountTypeByEmail(user.email) === AccountType.USER && (- <div className="sm:col-span-1">- <dt className="text-sm font-medium text-control-light">- {t("settings.profile.phone")}- </dt>- <dd className="mt-1 text-sm text-main">- {editing ? (- <Input- value={editingUser?.phone ?? ""}- placeholder={t("settings.profile.phone-tips")}- autoComplete="off"- type="tel"- onChange={(e) =>- updateEditingUser("phone", e.target.value)- }- />- ) : (- user.phone- )}- </dd>- </div>- )}-- {/* Password */}- {editing && editingUser && (- <div className="col-span-2">- <UserPasswordSection- password={editingUser.password ?? ""}- passwordConfirm={passwordConfirm}- onPasswordChange={(val) => updateEditingUser("password", val)}- onPasswordConfirmChange={setPasswordConfirm}- passwordRestriction={passwordRestriction}- />- </div>- )}- </dl>- </div>-- {/* 2FA section */}- {allowEdit && (- <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 border-t mt-16 pt-8 pb-4">- <div className="w-full flex flex-row justify-between items-center">- <span className="text-lg font-medium flex flex-row justify-start items-center">- {t("two-factor.self")}- <FeatureBadge- feature={PlanFeature.FEATURE_TWO_FA}- className="ml-2 text-accent inline-flex"- />- </span>- <div className="flex gap-x-2">- {isMFAEnabled && (- <Button variant="destructive" onClick={disable2FA}>- {t("common.disable")}- </Button>- )}- {user.email === currentUser.email && (- <Button appearance="outline" onClick={enable2FA}>- {isMFAEnabled ? t("common.edit") : t("common.enable")}- </Button>- )}- </div>- </div>- <p className="mt-4 text-sm text-gray-500">- {t("two-factor.description")}{" "}- <LearnMoreLink- href="https://docs.bytebase.com/administration/2fa?source=console"- className="text-accent ml-1"- />- </p>-- {showRegenerateRecoveryCodes && (- <>- <div className="w-full flex flex-row justify-between items-center mt-8">- <span className="text-lg font-medium">- {t("two-factor.recovery-codes.self")}- </span>- {!showRegenerateView && (- <DropdownMenu>- <DropdownMenuTrigger- aria-label={t("common.more")}- className="p-1 rounded-xs hover:bg-control-bg cursor-pointer outline-hidden focus-visible:ring-2 focus-visible:ring-accent"- >- <Ellipsis className="w-8" />- </DropdownMenuTrigger>- <DropdownMenuContent className="min-w-36">- <DropdownMenuItem- className="py-1.5"- onClick={() => setShowRegenerateView(true)}- >- {t("common.regenerate")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- <p className="mt-4 text-sm text-gray-500">- {t("two-factor.recovery-codes.description")}- </p>- {showRegenerateView && (- <RegenerateRecoveryCodesView- recoveryCodes={tempRecoveryCodes}- onClose={() => setShowRegenerateView(false)}- />- )}- </>- )}- </div>- )}- </div>-- {/* 2FA paywall — uses the shared `FeatureModal` so copy stays in- sync with subscription dynamic content (title, description,- required-plan / trial line) instead of a hand-written Dialog. */}- <FeatureModal- open={showFeatureModal}- feature={PlanFeature.FEATURE_TWO_FA}- onOpenChange={setShowFeatureModal}- />-- {/* Disable 2FA confirm dialog */}- <Dialog- open={showDisable2FAConfirm}- onOpenChange={setShowDisable2FAConfirm}- >- <DialogContent className="p-6">- <DialogTitle>{t("two-factor.disable.self")}</DialogTitle>- <DialogDescription className="mt-2">- {t("two-factor.disable.description")}- </DialogDescription>- <div className="mt-4 flex justify-end gap-x-2">- <Button- appearance="outline"- onClick={() => setShowDisable2FAConfirm(false)}- >- {t("common.cancel")}- </Button>- <Button variant="destructive" onClick={handleDisable2FA}>- {t("common.disable")}- </Button>- </div>- </DialogContent>- </Dialog>- </main>- );-}diff --git a/frontend/src/routes/workspace/profile/SettingsCard.tsx b/frontend/src/routes/workspace/profile/SettingsCard.tsxnew file mode 100644index 0000000000..fe61a401d4--- /dev/null+++ b/frontend/src/routes/workspace/profile/SettingsCard.tsx@@ -0,0 +1,71 @@+import type { ReactNode } from "react";+import { cn } from "@/lib/utils";++/**+ * A bordered group of settings rows.+ *+ * Grouping into a card does the work that section headings and whitespace were+ * doing badly: the border says where a group starts and ends, so the rows+ * inside can sit close together without reading as one undifferentiated list.+ */+export function SettingsCard({+ children,+ className,+}: {+ children: ReactNode;+ className?: string;+}) {+ return (+ <div+ className={cn(+ "divide-y divide-control-border rounded-md border border-control-border bg-background",+ className+ )}+ >+ {children}+ </div>+ );+}++/**+ * One setting: what it is on the left, its value or control on the right.+ *+ * The label column carries the reading weight and the control column stays+ * narrow, so a text input does not stretch to the width of the page just+ * because the page is wide.+ */+export function SettingsRow({+ label,+ description,+ children,+ align = "center",+}: {+ label: ReactNode;+ description?: ReactNode;+ children?: ReactNode;+ /** "start" when the control is taller than one line. */+ align?: "center" | "start";+}) {+ return (+ <div+ className={cn(+ "flex flex-col gap-y-2 px-4 py-3.5 sm:flex-row sm:gap-x-6",+ align === "center" ? "sm:items-center" : "sm:items-start"+ )}+ >+ <div className="flex min-w-0 flex-1 flex-col gap-y-0.5">+ <span className="text-sm font-medium text-main">{label}</span>+ {description && (+ <span className="text-xs leading-relaxed text-control-light">+ {description}+ </span>+ )}+ </div>+ {children && (+ <div className="flex shrink-0 items-center gap-x-2 sm:justify-end">+ {children}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/routes/workspace/profile/UserPasswordSection.tsx b/frontend/src/routes/workspace/profile/UserPasswordSection.tsxindex 18ffbbd0eb..3757cb6a79 100644--- a/frontend/src/routes/workspace/profile/UserPasswordSection.tsx+++ b/frontend/src/routes/workspace/profile/UserPasswordSection.tsx@@ -56,6 +56,11 @@ interface UserPasswordSectionProps {onPasswordConfirmChange: (value: string) => void;passwordRestriction?: WorkspaceProfileSetting_PasswordRestriction;disabled?: boolean;+ /**+ * Marks the fields as required. False on a standalone "change password"+ * surface, where leaving both fields empty simply means "don't change it".+ */+ required?: boolean;}export function UserPasswordSection({@@ -65,6 +70,7 @@ export function UserPasswordSection({onPasswordConfirmChange,passwordRestriction,disabled,+ required = true,}: UserPasswordSectionProps) {const { t } = useTranslation();const [showPassword, setShowPassword] = useState(false);@@ -128,8 +134,8 @@ export function UserPasswordSection({<div><div><label className="block text-sm font-medium leading-5 text-control">- {t("settings.profile.password")}{" "}- <span className="text-error">*</span>+ {t("settings.profile.password")}+ {required && <span className="ml-0.5 text-error">*</span>}</label><spanclassName={`flex items-center gap-x-1 text-sm ${@@ -187,8 +193,8 @@ export function UserPasswordSection({{/* Confirm field */}<div><label className="block text-sm font-medium leading-5 text-control">- {t("settings.profile.password-confirm")}{" "}- <span className="text-error">*</span>+ {t("settings.profile.password-confirm")}+ {required && <span className="ml-0.5 text-error">*</span>}</label><div className="w-full mt-1 flex flex-col justify-start items-start"><div className="w-full relative flex flex-row items-center">diff --git a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsxindex 975df20800..1b3dd22986 100644--- a/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx+++ b/frontend/src/routes/workspace/two-factor/TwoFactorSetupPage.tsx@@ -5,10 +5,7 @@ import { QRCodeSVG } from "qrcode.react";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { router } from "@/app/router";-import {- AUTH_2FA_SETUP_MODULE,- SETTING_ROUTE_PROFILE,-} from "@/app/router/handles";+import { ACCOUNT_ROUTE, AUTH_2FA_SETUP_MODULE } from "@/app/router/handles";import { LearnMoreLink } from "@/components/LearnMoreLink";import { Button } from "@/components/ui/button";import { OtpInput } from "@/components/ui/otp-input";@@ -180,7 +177,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {cancelAction();} else {router.replace({- name: SETTING_ROUTE_PROFILE,+ name: ACCOUNT_ROUTE,});}}, [cancelAction]);@@ -206,7 +203,7 @@ export function TwoFactorSetupPage({ cancelAction }: TwoFactorSetupPageProps) {if (router.currentRoute.value.name === AUTH_2FA_SETUP_MODULE) {router.replace({ path: "/" });} else {- router.replace({ name: SETTING_ROUTE_PROFILE });+ router.replace({ name: ACCOUNT_ROUTE });}}, [currentUser.name, t, updateUser]);diff --git a/frontend/src/routes/workspace/users/EditUserSheet.tsx b/frontend/src/routes/workspace/users/EditUserSheet.tsxnew file mode 100644index 0000000000..8cfed7feda--- /dev/null+++ b/frontend/src/routes/workspace/users/EditUserSheet.tsx@@ -0,0 +1,171 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import type { ConnectError } from "@connectrpc/connect";+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Alert } from "@/components/ui/alert";+import { Button } from "@/components/ui/button";+import { FormField, FormTitle } from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";++interface EditUserSheetProps {+ open: boolean;+ user: User | undefined;+ onClose: () => void;+ onUpdated: (user: User) => void;+}++/**+ * Edit the two fields on a user record that are ordinary profile data.+ *+ * Email, password, two-factor and account state are deliberately absent: each+ * carries a consequence of its own and confirms separately from the row menu.+ */+export function EditUserSheet({+ open,+ user,+ onClose,+ onUpdated,+}: EditUserSheetProps) {+ // Freeze the entity while closing so the form stays stable through the+ // sheet's exit animation.+ const openEntityRef = useRef(user);+ if (open) {+ openEntityRef.current = user;+ }+ const stableUser = openEntityRef.current;++ return (+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>+ <SheetContent width="narrow">+ <EditUserForm+ key={stableUser?.name ?? "none"}+ user={stableUser}+ onClose={onClose}+ onUpdated={onUpdated}+ />+ </SheetContent>+ </Sheet>+ );+}++function EditUserForm({+ user,+ onClose,+ onUpdated,+}: Omit<EditUserSheetProps, "open">) {+ const { t } = useTranslation();+ const updateUser = useAppStore((state) => state.updateUser);++ const initialTitle = user?.title ?? "";+ const initialPhone = user?.phone ?? "";+ const [title, setTitle] = useState(initialTitle);+ const [phone, setPhone] = useState(initialPhone);+ const [saving, setSaving] = useState(false);++ const isDirty = title !== initialTitle || phone !== initialPhone;++ const handleSubmit = async () => {+ if (!user) return;+ const paths: string[] = [];+ if (title !== initialTitle) paths.push("title");+ if (phone !== initialPhone) paths.push("phone");+ if (paths.length === 0) return;++ setSaving(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { ...user, title, phone },+ updateMask: create(FieldMaskSchema, { paths }),+ })+ );+ onUpdated(updated);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ onClose();+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: (error as ConnectError).message || t("common.error"),+ });+ } finally {+ setSaving(false);+ }+ };++ return (+ <>+ <SheetHeader>+ <SheetTitle>{t("settings.members.admin.edit-user")}</SheetTitle>+ </SheetHeader>++ <SheetBody>+ <div className="flex flex-col gap-y-6">+ {user?.profile?.source && (+ <Alert+ title={t("settings.members.admin.external-source", {+ source: user.profile.source,+ })}+ />+ )}++ <FormField>+ <FormTitle id="edit-user-name-title">{t("common.name")}</FormTitle>+ <Input+ id="edit-user-name"+ aria-labelledby="edit-user-name-title"+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ maxLength={200}+ />+ </FormField>++ <FormField>+ <FormTitle id="edit-user-phone-title">+ {t("settings.profile.phone")}+ </FormTitle>+ <span className="text-sm text-control-placeholder">+ {t("settings.profile.phone-tips")}+ </span>+ <Input+ id="edit-user-phone"+ aria-labelledby="edit-user-phone-title"+ type="tel"+ value={phone}+ autoComplete="off"+ onChange={(e) => setPhone(e.target.value)}+ />+ </FormField>++ <Alert title={t("settings.members.admin.email-immutable-tip")} />+ </div>+ </SheetBody>++ <SheetFooter>+ <Button appearance="outline" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button disabled={!isDirty || saving} onClick={handleSubmit}>+ {t("common.update")}+ </Button>+ </SheetFooter>+ </>+ );+}diff --git a/frontend/src/routes/workspace/users/UserFormSheet.tsx b/frontend/src/routes/workspace/users/UserFormSheet.tsxnew file mode 100644index 0000000000..a25cdc4125--- /dev/null+++ b/frontend/src/routes/workspace/users/UserFormSheet.tsx@@ -0,0 +1,360 @@+import { create } from "@bufbuild/protobuf";+import type { ConnectError } from "@connectrpc/connect";+import { CircleAlert, CircleCheck, Eye, EyeOff } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { RoleSelect } from "@/components/RoleSelect";+import { Button } from "@/components/ui/button";+import { FormError, FormField, FormTitle } from "@/components/ui/form";+import { Input } from "@/components/ui/input";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";+import { Tooltip } from "@/components/ui/tooltip";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import { getUserEmailInBinding } from "@/types";+import { PresetRoleType } from "@/types/iam";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import { UserSchema } from "@/types/proto-es/v1/user_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";++function extractUserTitle(email: string): string {+ const atIndex = email.indexOf("@");+ return atIndex !== -1 ? email.substring(0, atIndex) : email;+}++export interface UserFormSheetProps {+ open: boolean;+ onClose: () => void;+ onCreated: (user: User) => void;+}++// Provisioning a new account: email, an optional starting password, and the+// roles it should carry. Changing an account that already exists is a+// different job with different consequences — see the Users row menu.+export function UserFormSheet(props: UserFormSheetProps) {+ const { open, onClose } = props;+ return (+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>+ <SheetContent width="standard">+ <UserForm onClose={props.onClose} onCreated={props.onCreated} />+ </SheetContent>+ </Sheet>+ );+}++function UserForm({ onClose, onCreated }: Omit<UserFormSheetProps, "open">) {+ const { t } = useTranslation();+ const createUser = useAppStore((state) => state.createUser);+ const patchWorkspaceIamPolicy = useAppStore(+ (state) => state.patchWorkspaceIamPolicy+ );+ const passwordRestriction = useAppStore(+ (s) => s.getWorkspaceProfile().passwordRestriction+ );+ const enforceIdentityDomain = useAppStore(+ (s) => s.getWorkspaceProfile().enforceIdentityDomain+ );+ const workspaceDomains = useAppStore((s) => s.getWorkspaceProfile().domains);++ const [title, setTitle] = useState("");+ const [email, setEmail] = useState("");+ const [phone, setPhone] = useState("");+ const [password, setPassword] = useState("");+ const [passwordConfirm, setPasswordConfirm] = useState("");+ const [roles, setRoles] = useState<string[]>([+ PresetRoleType.WORKSPACE_MEMBER,+ ]);+ const [isRequesting, setIsRequesting] = useState(false);+ const [showPassword, setShowPassword] = useState(false);++ // Password validation+ const passwordChecks = useMemo(() => {+ const minLength = passwordRestriction?.minLength ?? 8;+ const checks: { text: string; matched: boolean }[] = [+ {+ text: t("settings.general.workspace.password-restriction.min-length", {+ min: minLength,+ }),+ matched: password.length >= minLength,+ },+ ];+ if (passwordRestriction?.requireNumber) {+ checks.push({+ text: t(+ "settings.general.workspace.password-restriction.require-number"+ ),+ matched: /[0-9]+/.test(password),+ });+ }+ if (passwordRestriction?.requireUppercaseLetter) {+ checks.push({+ text: t(+ "settings.general.workspace.password-restriction.require-uppercase-letter"+ ),+ matched: /[A-Z]+/.test(password),+ });+ } else if (passwordRestriction?.requireLetter) {+ checks.push({+ text: t(+ "settings.general.workspace.password-restriction.require-letter"+ ),+ matched: /[a-zA-Z]+/.test(password),+ });+ }+ if (passwordRestriction?.requireSpecialCharacter) {+ checks.push({+ text: t(+ "settings.general.workspace.password-restriction.require-special-character"+ ),+ matched: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(password),+ });+ }+ return checks;+ }, [password, passwordRestriction, t]);++ const passwordHint =+ password.length > 0 && passwordChecks.some((c) => !c.matched);+ const passwordMismatch =+ (password.length > 0 || passwordConfirm.length > 0) &&+ password !== passwordConfirm;++ const emailDomainValid = useMemo(() => {+ if (!enforceIdentityDomain || workspaceDomains.length === 0) return true;+ const atIdx = email.indexOf("@");+ if (atIdx < 0) return false;+ const domain = email.slice(atIdx + 1);+ return workspaceDomains.includes(domain);+ }, [email, enforceIdentityDomain, workspaceDomains]);++ const isFormValid =+ email.length > 0 && emailDomainValid && !passwordHint && !passwordMismatch;++ const allowConfirm = isFormValid;++ const hasPermission = hasWorkspacePermissionV2("bb.users.create");++ const handleSubmit = async () => {+ if (!allowConfirm || !hasPermission) return;+ setIsRequesting(true);+ try {+ await handleCreate();+ } catch {+ // error shown by store+ } finally {+ setIsRequesting(false);+ }+ };++ const handleCreate = async () => {+ // Empty password is valid on create; backend will generate a random password.+ const createdUser = await createUser({+ ...create(UserSchema, {}),+ title: title || extractUserTitle(email),+ email,+ phone,+ password,+ });+ if (roles.length > 0) {+ try {+ await patchWorkspaceIamPolicy([+ {+ member: getUserEmailInBinding(createdUser.email),+ roles,+ },+ ]);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("settings.members.admin.create-user-roles-failed"),+ description: (error as ConnectError).message,+ });+ }+ }+ onCreated(createdUser);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });+ onClose();+ };++ return (+ <>+ <SheetHeader>+ <SheetTitle>{t("settings.members.admin.create-user")}</SheetTitle>+ </SheetHeader>++ <SheetBody>+ <div className="flex flex-col gap-y-6">+ {/* Name */}+ <FormField>+ <FormTitle id="user-form-name-title">{t("common.name")}</FormTitle>+ <Input+ id="user-form-name"+ aria-labelledby="user-form-name-title"+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ placeholder={t("common.name")}+ maxLength={200}+ />+ </FormField>++ {/* Email */}+ <FormField>+ <FormTitle id="user-form-email-title">+ {t("common.email")}+ <span className="ml-0.5 text-error">*</span>+ </FormTitle>+ <Input+ id="user-form-email"+ aria-labelledby="user-form-email-title"+ type="email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ />+ </FormField>++ {/* Roles */}+ {hasWorkspacePermissionV2("bb.workspaces.setIamPolicy") && (+ <FormField>+ <FormTitle>{t("settings.members.table.roles")}</FormTitle>+ <RoleSelect value={roles} onChange={setRoles} disabled={false} />+ </FormField>+ )}++ {/* Phone */}+ <FormField>+ <FormTitle id="user-form-phone-title">+ {t("settings.profile.phone")}+ </FormTitle>+ <span className="text-sm text-control-placeholder">+ {t("settings.profile.phone-tips")}+ </span>+ <Input+ id="user-form-phone"+ aria-labelledby="user-form-phone-title"+ type="tel"+ value={phone}+ onChange={(e) => setPhone(e.target.value)}+ autoComplete="new-password"+ />+ </FormField>++ {/* Password */}+ <div className="flex flex-col gap-y-6">+ <FormField>+ <FormTitle id="user-form-password-title">+ {t("settings.profile.password")}+ </FormTitle>+ <span+ className={`flex items-center gap-x-1 text-sm text-control-placeholder ${+ passwordHint ? "text-error" : ""+ }`}+ >+ {t("settings.profile.password-hint")}+ <Tooltip+ content={+ <ul className="list-none text-sm">+ {passwordChecks.map((check, i) => (+ <li key={i} className="flex gap-x-1 items-center">+ {check.matched ? (+ <CircleCheck className="w-4 text-green-400" />+ ) : (+ <CircleAlert className="w-4 text-red-400" />+ )}+ {check.text}+ </li>+ ))}+ </ul>+ }+ >+ <CircleAlert className="w-4 cursor-help" />+ </Tooltip>+ </span>+ <div className="relative flex w-full items-center">+ <Input+ id="user-form-password"+ aria-labelledby="user-form-password-title"+ type={showPassword ? "text" : "password"}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ autoComplete="new-password"+ placeholder={t("common.sensitive-placeholder")}+ className={passwordHint ? "border-error" : ""}+ />+ <button+ type="button"+ className="absolute right-3 cursor-pointer"+ onClick={() => setShowPassword(!showPassword)}+ >+ {showPassword ? (+ <Eye className="w-4 h-4" />+ ) : (+ <EyeOff className="w-4 h-4" />+ )}+ </button>+ </div>+ </FormField>++ <FormField>+ <FormTitle id="user-form-password-confirm-title">+ {t("settings.profile.password-confirm")}+ </FormTitle>+ <div className="relative flex w-full items-center">+ <Input+ id="user-form-password-confirm"+ aria-labelledby="user-form-password-confirm-title"+ type={showPassword ? "text" : "password"}+ value={passwordConfirm}+ onChange={(e) => setPasswordConfirm(e.target.value)}+ autoComplete="new-password"+ placeholder={t(+ "settings.profile.password-confirm-placeholder"+ )}+ className={passwordMismatch ? "border-error" : ""}+ />+ <button+ type="button"+ className="absolute right-3 cursor-pointer"+ onClick={() => setShowPassword(!showPassword)}+ >+ {showPassword ? (+ <Eye className="w-4 h-4" />+ ) : (+ <EyeOff className="w-4 h-4" />+ )}+ </button>+ </div>+ {passwordMismatch && (+ <FormError className="pl-1">+ {t("settings.profile.password-mismatch")}+ </FormError>+ )}+ </FormField>+ </div>+ </div>+ </SheetBody>++ <SheetFooter>+ <Button appearance="outline" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button+ disabled={!allowConfirm || !hasPermission || isRequesting}+ onClick={handleSubmit}+ >+ {t("common.create")}+ </Button>+ </SheetFooter>+ </>+ );+}diff --git a/frontend/src/routes/workspace/UsersPageLayout.test.ts b/frontend/src/routes/workspace/users/UserFormSheetLayout.test.tssimilarity index 90%rename from frontend/src/routes/workspace/UsersPageLayout.test.tsrename to frontend/src/routes/workspace/users/UserFormSheetLayout.test.tsindex f4aa4f96a4..df8966ebe7 100644--- a/frontend/src/routes/workspace/UsersPageLayout.test.ts+++ b/frontend/src/routes/workspace/users/UserFormSheetLayout.test.ts@@ -5,9 +5,9 @@ import { describe, expect, test } from "vitest";const sectionDir = dirname(fileURLToPath(import.meta.url));-describe("UsersPage drawer layout", () => {+describe("UserFormSheet drawer layout", () => {test("keeps the password hint aligned in the compact drawer field", () => {- const source = readFileSync(join(sectionDir, "UsersPage.tsx"), "utf8");+ const source = readFileSync(join(sectionDir, "UserFormSheet.tsx"), "utf8");const passwordTitleIndex = source.indexOf('id="user-form-password-title"');const passwordHintIndex = source.indexOf(@@ -42,7 +42,7 @@ describe("UsersPage drawer layout", () => {});test("does not require password when creating a user", () => {- const source = readFileSync(join(sectionDir, "UsersPage.tsx"), "utf8");+ const source = readFileSync(join(sectionDir, "UserFormSheet.tsx"), "utf8");expect(source).not.toContain("(isEditMode || password.length > 0)");expect(source).toContain("password,");diff --git a/frontend/src/routes/workspace/users/UserRowMenu.test.tsx b/frontend/src/routes/workspace/users/UserRowMenu.test.tsxnew file mode 100644index 0000000000..cb8adbacd4--- /dev/null+++ b/frontend/src/routes/workspace/users/UserRowMenu.test.tsx@@ -0,0 +1,200 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { State } from "@/types/proto-es/v1/common_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const activeUser = {+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Alice",+ phone: "",+ password: "",+ state: State.ACTIVE,+ mfaEnabled: true,+ groups: [],+};++const mocks = vi.hoisted(() => ({+ hasWorkspacePermissionV2: vi.fn(() => true),+ isSaaSMode: vi.fn(() => false),+ pushNotification: vi.fn(),+ updateUser: vi.fn(),+ updateEmail: vi.fn(),+}));++vi.mock("@/utils", () => ({+ hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,+}));++vi.mock("@/stores", () => ({+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/stores/app", () => {+ const buildState = () => ({+ updateUser: mocks.updateUser,+ updateEmail: mocks.updateEmail,+ isSaaSMode: () => mocks.isSaaSMode(),+ getWorkspaceProfile: () => ({+ requireMfa: false,+ passwordRestriction: undefined,+ }),+ });+ const useAppStore = (selector: (state: unknown) => unknown) =>+ selector(buildState());+ useAppStore.getState = () => buildState();+ return { useAppStore };+});++// Render dropdown content inline so the menu items are inspectable without+// driving Base UI's portal + open state.+vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ DropdownMenuTrigger: () => null,+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="menu">{children}</div>+ ),+ DropdownMenuItem: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="menu-item">{children}</div>+ ),+ DropdownMenuSeparator: () => <hr />,+}));++vi.mock("@/components/ui/dialog", () => ({+ Dialog: ({ open, children }: { open?: boolean; children: React.ReactNode }) =>+ open ? <>{children}</> : null,+ DialogContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ DialogDescription: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));++vi.mock("../profile/EmailInput", () => ({+ EmailInput: () => <input />,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ initReactI18next: { type: "3rdParty", init: () => {} },+}));++let UserRowMenu: typeof import("./UserRowMenu").UserRowMenu;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: async () => {+ await act(async () => {+ root.render(element);+ });+ },+ unmount: () => act(() => root.unmount()),+ };+};++const menuItems = (container: HTMLElement) =>+ Array.from(container.querySelectorAll('[data-testid="menu-item"]')).map(+ (el) => el.textContent+ );++const renderMenu = async (user: typeof activeUser) => {+ const handle = renderIntoContainer(+ <UserRowMenu+ user={user as never}+ isSelf={false}+ onUserUpdated={() => {}}+ onEdit={() => {}}+ onDeactivate={async () => {}}+ onReactivate={async () => {}}+ />+ );+ await handle.render();+ return handle;+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.hasWorkspacePermissionV2.mockReturnValue(true);+ mocks.isSaaSMode.mockReturnValue(false);+ ({ UserRowMenu } = await import("./UserRowMenu"));+});++describe("UserRowMenu", () => {+ test("leads with the two recovery actions", async () => {+ const { container, unmount } = await renderMenu(activeUser);++ const items = menuItems(container);+ expect(items[0]).toBe("settings.members.admin.reset-password");+ expect(items[1]).toBe("settings.members.admin.reset-mfa");++ unmount();+ });++ test("offers no MFA reset for someone who never enrolled", async () => {+ const { container, unmount } = await renderMenu({+ ...activeUser,+ mfaEnabled: false,+ });++ expect(menuItems(container)).not.toContain(+ "settings.members.admin.reset-mfa"+ );++ unmount();+ });++ test("offers reactivate and nothing else for a deactivated account", async () => {+ // UpdateUser and UpdateEmail both reject a deleted user, so any other+ // action here would only produce a "user has been deleted" error. The one+ // thing to do with such an account is bring it back.+ const { container, unmount } = await renderMenu({+ ...activeUser,+ state: State.DELETED,+ });++ expect(menuItems(container)).toEqual([+ "settings.members.admin.reactivate",+ ]);++ unmount();+ });++ test("in cloud, explains instead of offering actions that the API rejects", async () => {+ // UpdateUser, UpdateEmail, DeleteUser and UndeleteUser all refuse to touch+ // another user in SaaS mode, so every one of these would only error.+ mocks.isSaaSMode.mockReturnValue(true);++ const { container, unmount } = await renderMenu(activeUser);++ expect(menuItems(container)).toEqual([]);+ expect(container.textContent).toContain(+ "settings.members.admin.saas-read-only"+ );++ unmount();+ });++ test("shows nothing at all without permission", async () => {+ mocks.hasWorkspacePermissionV2.mockReturnValue(false);++ const { container, unmount } = await renderMenu(activeUser);++ expect(container.querySelector('[data-testid="menu"]')).toBeNull();++ unmount();+ });+});diff --git a/frontend/src/routes/workspace/users/UserRowMenu.tsx b/frontend/src/routes/workspace/users/UserRowMenu.tsxnew file mode 100644index 0000000000..980164236a--- /dev/null+++ b/frontend/src/routes/workspace/users/UserRowMenu.tsx@@ -0,0 +1,499 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import type { ConnectError } from "@connectrpc/connect";+import { Ellipsis } from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Alert } from "@/components/ui/alert";+import { Button } from "@/components/ui/button";+import { CopyButton } from "@/components/ui/copy-button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import { AccountType, getAccountTypeByEmail } from "@/types";+import { State } from "@/types/proto-es/v1/common_pb";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";+import { hasWorkspacePermissionV2 } from "@/utils";+import { EmailInput } from "../profile/EmailInput";+import { getPasswordErrors } from "../profile/UserPasswordSection";+import { generatePassword } from "./generatePassword";++type OpenDialog =+ | "none"+ | "reset-password"+ | "reset-mfa"+ | "change-email"+ | "lifecycle";++interface UserRowMenuProps {+ user: User;+ isSelf: boolean;+ /** `replaces` names an identity the update supersedes, if any. */+ onUserUpdated: (user: User, replaces?: User) => void;+ onEdit: (user: User) => void;+ onDeactivate: (user: User) => Promise<void>;+ onReactivate: (user: User) => Promise<void>;+}++/**+ * Administrative actions for one account, from the directory row.+ *+ * Recovery leads because it is why an admin opens this menu: somebody cannot+ * sign in. Everything below the separator is ordinary bookkeeping.+ */+export function UserRowMenu({+ user,+ isSelf,+ onUserUpdated,+ onEdit,+ onDeactivate,+ onReactivate,+}: UserRowMenuProps) {+ const { t } = useTranslation();+ const updateUser = useAppStore((state) => state.updateUser);+ const updateEmail = useAppStore((state) => state.updateEmail);+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());+ const requireMfa = useAppStore((s) => s.getWorkspaceProfile().requireMfa);+ const passwordRestriction = useAppStore(+ (s) => s.getWorkspaceProfile().passwordRestriction+ );++ const [dialog, setDialog] = useState<OpenDialog>("none");+ const [processing, setProcessing] = useState(false);++ // Reset-password state. `issuedPassword` doubles as the dialog's phase: once+ // set, the dialog shows the result instead of the form.+ const [password, setPassword] = useState("");+ const [issuedPassword, setIssuedPassword] = useState("");++ const [newEmail, setNewEmail] = useState("");++ const accountType = getAccountTypeByEmail(user.email);+ const isEndUser = accountType === AccountType.USER;+ const isDeactivated = user.state === State.DELETED;++ // Cloud owns the account record, so only role management remains — and that+ // lives on the members page, not here.+ //+ // A deactivated account is also off limits: UpdateUser and UpdateEmail both+ // reject a deleted user outright, so every one of these would fail. The only+ // thing to do with such an account is bring it back.+ const canAdminister = !isSaaSMode && isEndUser && !isDeactivated && !isSelf;+ const canUpdate =+ canAdminister && hasWorkspacePermissionV2("bb.users.update");+ const canUpdateEmail =+ canAdminister && hasWorkspacePermissionV2("bb.users.updateEmail");+ // DeleteUser and UndeleteUser are unimplemented in cloud, so offering them+ // for an end user there would only produce an error. Service accounts and+ // workload identities go through their own RPCs and are unaffected.+ const canChangeLifecycle = !isEndUser || !isSaaSMode;+ const canDeactivate =+ canChangeLifecycle &&+ !isSelf &&+ hasWorkspacePermissionV2(+ accountType === AccountType.SERVICE_ACCOUNT+ ? "bb.serviceAccounts.delete"+ : accountType === AccountType.WORKLOAD_IDENTITY+ ? "bb.workloadIdentities.delete"+ : "bb.users.delete"+ );+ const canReactivate =+ canChangeLifecycle &&+ hasWorkspacePermissionV2(+ accountType === AccountType.SERVICE_ACCOUNT+ ? "bb.serviceAccounts.undelete"+ : accountType === AccountType.WORKLOAD_IDENTITY+ ? "bb.workloadIdentities.undelete"+ : "bb.users.undelete"+ );++ // Recovery restores sign-in, which only means something for a live account.+ const showRecovery = canUpdate;+ const hasAnyAction =+ showRecovery ||+ canUpdate ||+ canUpdateEmail ||+ (isDeactivated ? canReactivate : canDeactivate);++ // In cloud the account itself is out of the workspace's hands, so say so+ // rather than rendering nothing and leaving the admin to wonder.+ const saasNotice = isSaaSMode && isEndUser;++ const closeDialog = () => {+ setDialog("none");+ setPassword("");+ setIssuedPassword("");+ setNewEmail("");+ };++ const passwordErrors = getPasswordErrors(+ password,+ password,+ passwordRestriction+ );++ const notifyFailure = (error: unknown) => {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: (error as ConnectError).message || t("common.error"),+ });+ };++ const handleResetPassword = async () => {+ setProcessing(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { ...user, password },+ updateMask: create(FieldMaskSchema, { paths: ["password"] }),+ })+ );+ onUserUpdated(updated);+ setIssuedPassword(password);+ } catch (error) {+ notifyFailure(error);+ } finally {+ setProcessing(false);+ }+ };++ const handleResetMfa = async () => {+ setProcessing(true);+ try {+ const updated = await updateUser(+ create(UpdateUserRequestSchema, {+ user: { name: user.name, mfaEnabled: false },+ updateMask: create(FieldMaskSchema, { paths: ["mfa_enabled"] }),+ })+ );+ onUserUpdated(updated);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("two-factor.messages.2fa-disabled"),+ });+ closeDialog();+ } catch (error) {+ notifyFailure(error);+ } finally {+ setProcessing(false);+ }+ };++ const handleChangeEmail = async () => {+ setProcessing(true);+ try {+ const updated = await updateEmail(user.email, newEmail);+ // The resource name moved with the email, so the old row has to go.+ onUserUpdated(updated, user);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ closeDialog();+ } catch (error) {+ notifyFailure(error);+ } finally {+ setProcessing(false);+ }+ };++ const handleLifecycle = async () => {+ setProcessing(true);+ try {+ await (isDeactivated ? onReactivate(user) : onDeactivate(user));+ closeDialog();+ } catch {+ // Leave the dialog open on failure — closing it reads as success. The+ // caller has already surfaced the error, so no second toast here.+ } finally {+ setProcessing(false);+ }+ };++ if (!hasAnyAction && !saasNotice) return null;++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ appearance="secondary"+ size="sm"+ aria-label={t("common.more")}+ >+ <Ellipsis className="size-4" />+ </Button>+ }+ />+ <DropdownMenuContent className="min-w-52">+ {saasNotice && (+ <div className="px-3 py-2 text-sm text-control-light">+ {t("settings.members.admin.saas-read-only")}+ </div>+ )}+ {showRecovery && (+ <>+ <DropdownMenuItem onClick={() => setDialog("reset-password")}>+ {t("settings.members.admin.reset-password")}+ </DropdownMenuItem>+ {user.mfaEnabled && (+ <DropdownMenuItem onClick={() => setDialog("reset-mfa")}>+ {t("settings.members.admin.reset-mfa")}+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ </>+ )}+ {canUpdate && (+ <DropdownMenuItem onClick={() => onEdit(user)}>+ {t("settings.members.admin.edit-user")}+ </DropdownMenuItem>+ )}+ {canUpdateEmail && (+ <DropdownMenuItem+ onClick={() => {+ setNewEmail(user.email);+ setDialog("change-email");+ }}+ >+ {t("settings.members.admin.change-email")}+ </DropdownMenuItem>+ )}+ {isDeactivated+ ? canReactivate && (+ <DropdownMenuItem onClick={() => setDialog("lifecycle")}>+ {t("settings.members.admin.reactivate")}+ </DropdownMenuItem>+ )+ : canDeactivate && (+ <DropdownMenuItem+ className="text-error"+ onClick={() => setDialog("lifecycle")}+ >+ {t("settings.members.admin.deactivate")}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>++ {/* Reset password — two phases in one dialog: choose a password, then+ read it back once. There is no mail server to fall back on in a+ self-hosted deployment, so the admin has to carry it themselves. */}+ <Dialog+ open={dialog === "reset-password"}+ onOpenChange={(next) => {+ // From the moment the request goes out, closing loses a credential+ // that is about to become the account's only working one: the reset+ // lands server-side regardless, so an Escape or backdrop click mid+ // flight revokes the old password and discards the new one unseen.+ // Closing requires the explicit Done button.+ if (next || processing || issuedPassword) return;+ closeDialog();+ }}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>+ {t("settings.members.admin.reset-password")}+ </DialogTitle>+ {issuedPassword ? (+ <>+ <DialogDescription>+ {t("settings.members.admin.reset-password-issued", {+ user: user.title || user.email,+ })}+ </DialogDescription>+ <div className="mt-4 flex items-center gap-x-2">+ <Input+ readOnly+ value={issuedPassword}+ className="font-mono"+ aria-label={t("common.password")}+ />+ <CopyButton content={issuedPassword} size="md" />+ </div>+ <Alert+ className="mt-4"+ title={t("settings.members.admin.reset-password-deliver")}+ />+ <div className="mt-4 flex justify-end gap-x-2">+ <Button onClick={closeDialog}>{t("common.done")}</Button>+ </div>+ </>+ ) : (+ <>+ <DialogDescription>+ {t("settings.members.admin.reset-password-description", {+ user: user.title || user.email,+ })}+ </DialogDescription>+ <div className="mt-4 flex items-center gap-x-2">+ <Input+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ autoComplete="new-password"+ className="font-mono"+ aria-label={t("common.password")}+ />+ <Button+ appearance="outline"+ onClick={() =>+ setPassword(generatePassword(passwordRestriction))+ }+ >+ {t("settings.members.admin.generate")}+ </Button>+ </div>+ {password && passwordErrors.hasHint && (+ <p className="mt-2 text-sm text-error">+ {t("settings.profile.password-hint")}+ </p>+ )}+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ disabled={processing}+ onClick={closeDialog}+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={processing || !password || passwordErrors.hasHint}+ onClick={handleResetPassword}+ >+ {t("settings.members.admin.reset-password")}+ </Button>+ </div>+ </>+ )}+ </DialogContent>+ </Dialog>++ {/* Reset 2FA — the consequence differs by workspace policy, so the copy+ does too. */}+ <Dialog+ open={dialog === "reset-mfa"}+ onOpenChange={(next) => !next && closeDialog()}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>{t("settings.members.admin.reset-mfa")}</DialogTitle>+ <DialogDescription>+ {t("settings.members.admin.reset-mfa-recovery-first")}+ </DialogDescription>+ <p className="mt-3 text-sm text-control">+ {requireMfa+ ? t("settings.members.admin.reset-mfa-required", {+ user: user.title || user.email,+ })+ : t("settings.members.admin.reset-mfa-optional", {+ user: user.title || user.email,+ })}+ </p>+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ disabled={processing}+ onClick={closeDialog}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant="destructive"+ disabled={processing}+ onClick={handleResetMfa}+ >+ {t("settings.members.admin.reset-mfa")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>++ {/* Change email — an identity change, so it confirms on its own. */}+ <Dialog+ open={dialog === "change-email"}+ onOpenChange={(next) => !next && closeDialog()}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>{t("settings.members.admin.change-email")}</DialogTitle>+ <DialogDescription>+ {t("settings.members.admin.change-email-description", {+ email: user.email,+ })}+ </DialogDescription>+ <div className="mt-4">+ <EmailInput value={newEmail} onChange={setNewEmail} />+ </div>+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ disabled={processing}+ onClick={closeDialog}+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={processing || !newEmail || newEmail === user.email}+ onClick={handleChangeEmail}+ >+ {t("common.update")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>++ {/* Deactivate / reactivate */}+ <Dialog+ open={dialog === "lifecycle"}+ onOpenChange={(next) => !next && closeDialog()}+ >+ <DialogContent className="max-w-md">+ <DialogTitle>+ {isDeactivated+ ? t("settings.members.action.reactivate-confirm-title")+ : t("settings.members.action.deactivate-confirm-title")}+ </DialogTitle>+ <DialogDescription>+ {isDeactivated+ ? t("settings.members.admin.reactivate-tip")+ : t("settings.members.admin.deactivate-tip")}+ </DialogDescription>+ <div className="mt-4 flex justify-end gap-x-2">+ <Button+ appearance="outline"+ disabled={processing}+ onClick={closeDialog}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant={isDeactivated ? "default" : "destructive"}+ disabled={processing}+ onClick={handleLifecycle}+ >+ {isDeactivated+ ? t("settings.members.admin.reactivate")+ : t("settings.members.admin.deactivate")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/frontend/src/routes/workspace/users/generatePassword.test.ts b/frontend/src/routes/workspace/users/generatePassword.test.tsnew file mode 100644index 0000000000..c6fe5d37d2--- /dev/null+++ b/frontend/src/routes/workspace/users/generatePassword.test.ts@@ -0,0 +1,78 @@+import { describe, expect, test } from "vitest";+import { getPasswordErrors } from "@/routes/workspace/profile/UserPasswordSection";+import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";+import { generatePassword } from "./generatePassword";++// Every combination of the four boolean rules, since they interact: the+// uppercase rule shadows the letter rule in the validator's if/else ladder.+const FLAGS = [+ "requireNumber",+ "requireLetter",+ "requireUppercaseLetter",+ "requireSpecialCharacter",+] as const;++function combinations(): WorkspaceProfileSetting_PasswordRestriction[] {+ const out: WorkspaceProfileSetting_PasswordRestriction[] = [];+ for (let mask = 0; mask < 1 << FLAGS.length; mask++) {+ const restriction = { minLength: 12 } as Record<string, unknown>;+ FLAGS.forEach((flag, i) => {+ restriction[flag] = (mask & (1 << i)) !== 0;+ });+ out.push(restriction as WorkspaceProfileSetting_PasswordRestriction);+ }+ return out;+}++describe("generatePassword", () => {+ // The generator hands its output to an admin as a working credential. If it+ // can emit a password the server rejects, that failure lands mid-recovery,+ // on the one path that exists because the user is already locked out.+ test("always satisfies the restriction it was given", () => {+ for (const restriction of combinations()) {+ for (let i = 0; i < 50; i++) {+ const password = generatePassword(restriction);+ const errors = getPasswordErrors(password, password, restriction);+ expect(+ errors.hasHint,+ `restriction ${JSON.stringify(restriction)} produced ${password}`+ ).toBe(false);+ expect(password.length).toBeGreaterThanOrEqual(restriction.minLength);+ }+ }+ });++ test("honors a minimum length above its own floor", () => {+ const restriction = {+ minLength: 40,+ requireNumber: true,+ requireUppercaseLetter: true,+ requireSpecialCharacter: true,+ } as WorkspaceProfileSetting_PasswordRestriction;+ expect(generatePassword(restriction)).toHaveLength(40);+ });++ test("still produces a usable password with no restriction configured", () => {+ const password = generatePassword(undefined);+ expect(password.length).toBeGreaterThanOrEqual(16);+ expect(getPasswordErrors(password, password, undefined).hasHint).toBe(+ false+ );+ });++ test("does not repeat itself", () => {+ const seen = new Set(+ Array.from({ length: 100 }, () => generatePassword(undefined))+ );+ expect(seen.size).toBe(100);+ });++ test("omits characters that are misread when relayed by hand", () => {+ // The admin reads this off a screen and types or dictates it, so the+ // l/1/I and O/0 families are excluded on purpose.+ const password = Array.from({ length: 50 }, () =>+ generatePassword(undefined)+ ).join("");+ expect(password).not.toMatch(/[lIO01]/);+ });+});diff --git a/frontend/src/routes/workspace/users/generatePassword.ts b/frontend/src/routes/workspace/users/generatePassword.tsnew file mode 100644index 0000000000..fd102a13db--- /dev/null+++ b/frontend/src/routes/workspace/users/generatePassword.ts@@ -0,0 +1,60 @@+import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";++const LOWER = "abcdefghijkmnopqrstuvwxyz";+const UPPER = "ABCDEFGHJKLMNPQRSTUVWXYZ";+const DIGIT = "23456789";+const SPECIAL = "!@#$%^&*-_=+";++function pick(pool: string, count: number): string[] {+ const out: string[] = [];+ const bytes = new Uint32Array(count);+ crypto.getRandomValues(bytes);+ for (let i = 0; i < count; i++) {+ out.push(pool[bytes[i] % pool.length]);+ }+ return out;+}++/**+ * Build a password that satisfies the workspace restriction.+ *+ * Used when an admin resets a password for someone who cannot sign in. The+ * character pools omit look-alikes (l/1/I, O/0) because the result is read off+ * a screen and typed by hand, or relayed over a phone call.+ */+export function generatePassword(+ restriction: WorkspaceProfileSetting_PasswordRestriction | undefined+): string {+ const required: string[] = [];+ let pool = LOWER;++ if (restriction?.requireUppercaseLetter) {+ required.push(...pick(UPPER, 1));+ pool += UPPER;+ } else if (restriction?.requireLetter) {+ required.push(...pick(LOWER, 1));+ }+ if (restriction?.requireNumber) {+ required.push(...pick(DIGIT, 1));+ pool += DIGIT;+ }+ if (restriction?.requireSpecialCharacter) {+ required.push(...pick(SPECIAL, 1));+ pool += SPECIAL;+ }++ // Comfortably above the floor: the generated value is never memorized, and a+ // longer default costs the admin nothing since they copy it.+ const target = Math.max(restriction?.minLength ?? 8, 16);+ const chars = [...required, ...pick(pool, target - required.length)];++ // Shuffle so the required characters are not always in the leading+ // positions, which would make the pattern guessable across resets.+ const order = new Uint32Array(chars.length);+ crypto.getRandomValues(order);+ for (let i = chars.length - 1; i > 0; i--) {+ const j = order[i] % (i + 1);+ [chars[i], chars[j]] = [chars[j], chars[i]];+ }+ return chars.join("");+}