Skip to content

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

feat: redesign the saved query share popover (#21244)

Danny Xu9207b6b53092
diff --git a/frontend/src/components/AccountMultiSelect.test.tsx b/frontend/src/components/AccountMultiSelect.test.tsx
index 8aac5763d5..61a3392c2d 100644
--- a/frontend/src/components/AccountMultiSelect.test.tsx
+++ b/frontend/src/components/AccountMultiSelect.test.tsx
@@ -137,4 +137,153 @@ describe("AccountMultiSelect", () => {
act(() => root.unmount());
});
+
+ test("hides excluded accounts from the dropdown", async () => {
+ mocks.listUsers.mockResolvedValue({
+ users: [
+ {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ title: "Alice",
+ },
+ {
+ name: "users/[email protected]",
+ email: "[email protected]",
+ title: "Bob",
+ },
+ ],
+ nextPageToken: "",
+ });
+ mocks.listGroups.mockResolvedValue({
+ groups: [
+ {
+ name: "groups/[email protected]",
+ email: "[email protected]",
+ title: "G1",
+ members: [],
+ },
+ {
+ name: "groups/[email protected]",
+ email: "[email protected]",
+ title: "G2",
+ members: [],
+ },
+ ],
+ nextPageToken: "",
+ });
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ excludeAccounts={["user:[email protected]", "group:[email protected]"]}
+ />
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ container.firstElementChild?.firstElementChild?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+
+ const rendered = Array.from(container.querySelectorAll("b")).map(
+ (element) => element.textContent
+ );
+ expect(rendered).toContain("Bob");
+ expect(rendered).toContain("G2");
+ expect(rendered).not.toContain("Alice");
+ expect(rendered).not.toContain("G1");
+
+ // The fetch over-fetches by the exclusion count so filtering cannot
+ // shrink the pickable page below the default.
+ expect(mocks.listUsers).toHaveBeenCalledWith(
+ expect.objectContaining({ pageSize: 52 })
+ );
+
+ act(() => root.unmount());
+ });
+
+ test("shows the no-data state when every fetched account is excluded", async () => {
+ mocks.listGroups.mockResolvedValue({ groups: [], nextPageToken: "" });
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ excludeAccounts={["user:[email protected]"]}
+ />
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ container.firstElementChild?.firstElementChild?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+
+ expect(container.textContent).toContain("common.no-data");
+ act(() => root.unmount());
+ });
+
+ test("Escape closes only the dropdown and does not bubble further", async () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ // Listen above the React root (React 18 delegates at the container, so a
+ // same-node listener would fire regardless of stopPropagation) — the real
+ // popover's Escape dismissal also listens at the document level.
+ const outerKeydown = vi.fn();
+ document.addEventListener("keydown", outerKeydown);
+ await act(async () => {
+ root.render(<AccountMultiSelect value={[]} onChange={() => {}} />);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ container.firstElementChild?.firstElementChild?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ const search = container.querySelector('[data-testid="search"]');
+ expect(search).not.toBeNull();
+
+ await act(async () => {
+ search?.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
+ );
+ });
+
+ expect(container.querySelector('[data-testid="search"]')).toBeNull();
+ expect(outerKeydown).not.toHaveBeenCalled();
+ document.removeEventListener("keydown", outerKeydown);
+ act(() => root.unmount());
+ });
+
+ test("renders a caller-provided placeholder when empty", () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <AccountMultiSelect
+ value={[]}
+ onChange={() => {}}
+ placeholder="Add users or groups"
+ />
+ );
+ });
+ expect(container.textContent).toContain("Add users or groups");
+ act(() => root.unmount());
+ });
});
diff --git a/frontend/src/components/AccountMultiSelect.tsx b/frontend/src/components/AccountMultiSelect.tsx
index bf66ff43c6..3cdcde836e 100644
--- a/frontend/src/components/AccountMultiSelect.tsx
+++ b/frontend/src/components/AccountMultiSelect.tsx
@@ -191,11 +191,22 @@ export function AccountMultiSelect({
onChange,
disabled,
includeAllUsers,
+ excludeAccounts,
+ placeholder,
}: {
value: string[];
onChange: (value: string[]) => void;
disabled?: boolean;
includeAllUsers?: boolean;
+ /** Empty-state text in the trigger; defaults to the generic account label. */
+ placeholder?: string;
+ /**
+ * Binding strings ("user:{email}" / "group:{email}") to hide from the
+ * dropdown — accounts that cannot or need not be picked here, such as the
+ * caller themselves or accounts already holding a grant. Display-only:
+ * chips already in `value` keep rendering and stay removable.
+ */
+ excludeAccounts?: string[];
}) {
const { t } = useTranslation();
const listUsers = useAppStore((state) => state.listUsers);
@@ -214,13 +225,17 @@ export function AccountMultiSelect({
useEffect(() => {
const query = search.trim();
- listUsers({ pageSize: getDefaultPagination(), filter: { query } }).then(
- ({ users: fetched }) => setUsers(fetched)
+ // Over-fetch by the exclusion count: filtering happens after server
+ // pagination, so without this a widely-shared exclusion list could
+ // consume the entire page and leave nothing pickable.
+ const pageSize = getDefaultPagination() + (excludeAccounts?.length ?? 0);
+ listUsers({ pageSize, filter: { query } }).then(({ users: fetched }) =>
+ setUsers(fetched)
);
- listGroups({ pageSize: getDefaultPagination(), filter: { query } }).then(
- ({ groups: fetched }) => setGroups(fetched)
+ listGroups({ pageSize, filter: { query } }).then(({ groups: fetched }) =>
+ setGroups(fetched)
);
- }, [search, listUsers, listGroups]);
+ }, [search, listUsers, listGroups, excludeAccounts]);
const handleClickOutside = useCallback(() => {
setOpen(false);
@@ -234,6 +249,21 @@ export function AccountMultiSelect({
[value]
);
+ const excludedFullnames = useMemo(
+ () => new Set((excludeAccounts ?? []).map(bindingToFullname)),
+ [excludeAccounts]
+ );
+ // Filter the rendered lists only — `users`/`groups` stay complete so
+ // resolveLabel keeps labeling chips for any binding in `value`.
+ const visibleUsers = useMemo(
+ () => users.filter((user) => !excludedFullnames.has(`users/${user.email}`)),
+ [users, excludedFullnames]
+ );
+ const visibleGroups = useMemo(
+ () => groups.filter((group) => !excludedFullnames.has(group.name)),
+ [groups, excludedFullnames]
+ );
+
const toggle = (fullname: string) => {
if (disabled) return;
const binding = fullnameToBinding(fullname);
@@ -296,6 +326,16 @@ export function AccountMultiSelect({
return trimmed;
}, [search, specialAccountMatch, users]);
+ const visibleSpecialAccountMatch =
+ specialAccountMatch && !excludedFullnames.has(specialAccountMatch.fullname)
+ ? specialAccountMatch
+ : null;
+ const visibleArbitraryEmailMatch =
+ arbitraryEmailMatch &&
+ !excludedFullnames.has(`users/${arbitraryEmailMatch}`)
+ ? arbitraryEmailMatch
+ : null;
+
// Label for a selected binding chip — uses cache to survive search changes
const chipLabel = (binding: string): string => {
if (binding === ALL_USERS_USER_EMAIL) {
@@ -312,7 +352,19 @@ export function AccountMultiSelect({
};
return (
- <div ref={containerRef} className="relative">
+ <div
+ ref={containerRef}
+ className="relative"
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || !open) return;
+ // Swallow Escape while the dropdown is open: it closes only the
+ // dropdown, not the popover (and staged state) around the picker.
+ event.stopPropagation();
+ event.preventDefault();
+ setOpen(false);
+ setSearch("");
+ }}
+ >
{/* Trigger */}
<div
className={cn(
@@ -349,7 +401,7 @@ export function AccountMultiSelect({
))}
{value.length === 0 && (
<span className="text-control-placeholder">
- {t("settings.members.select-account", { count: 2 })}
+ {placeholder ?? t("settings.members.select-account", { count: 2 })}
</span>
)}
<ChevronDown className="ml-auto h-4 w-4 shrink-0 text-control-light" />
@@ -372,7 +424,7 @@ export function AccountMultiSelect({
placeholder={t("common.search-for-more")}
/>
- <div className="overflow-auto">
+ <div className="overflow-auto" role="listbox" aria-multiselectable>
{/* allUsers option */}
{includeAllUsers && (
<div
@@ -401,12 +453,12 @@ export function AccountMultiSelect({
)}
{/* Users */}
- {users.length > 0 && (
+ {visibleUsers.length > 0 && (
<div>
<div className="px-3 py-1.5 text-xs font-medium text-control-light uppercase tracking-wide bg-control-bg border-b">
{t("common.users")}
</div>
- {users.map((user) => {
+ {visibleUsers.map((user) => {
const fullname = `users/${user.email}`;
const selected = selectedFullnames.has(fullname);
const isCurrentUser = user.email === currentUser?.email;
@@ -458,21 +510,30 @@ export function AccountMultiSelect({
)}
{/* Groups */}
- {groups.length > 0 && (
+ {visibleGroups.length > 0 && (
<div>
<div className="px-3 py-1.5 text-xs font-medium text-control-light uppercase tracking-wide bg-control-bg border-b">
{t("common.groups")}
</div>
- {groups.map((group) => {
+ {visibleGroups.map((group) => {
const selected = selectedFullnames.has(group.name);
return (
<div
key={group.name}
+ role="option"
+ aria-selected={selected}
+ tabIndex={0}
className={cn(
"flex items-center gap-x-3 px-3 py-2 cursor-pointer hover:bg-control-bg",
selected && "bg-accent/5"
)}
onClick={() => toggle(group.name)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ toggle(group.name);
+ }
+ }}
>
<SelectionCheckbox selected={selected} />
<div className="size-7 rounded-full bg-control-bg-hover flex items-center justify-center shrink-0">
@@ -506,41 +567,44 @@ export function AccountMultiSelect({
)}
{/* Service account / workload identity match */}
- {specialAccountMatch && (
+ {visibleSpecialAccountMatch && (
<SpecialAccountOption
keyword={search}
- match={specialAccountMatch}
- selected={selectedFullnames.has(specialAccountMatch.fullname)}
- onToggle={() => toggle(specialAccountMatch.fullname)}
+ match={visibleSpecialAccountMatch}
+ selected={selectedFullnames.has(
+ visibleSpecialAccountMatch.fullname
+ )}
+ onToggle={() => toggle(visibleSpecialAccountMatch.fullname)}
/>
)}
{/* Arbitrary email fallback */}
- {arbitraryEmailMatch && (
+ {visibleArbitraryEmailMatch && (
<div
className={cn(
"flex items-center gap-x-3 px-3 py-2 cursor-pointer hover:bg-control-bg",
- selectedFullnames.has(`users/${arbitraryEmailMatch}`) &&
- "bg-accent/5"
+ selectedFullnames.has(
+ `users/${visibleArbitraryEmailMatch}`
+ ) && "bg-accent/5"
)}
- onClick={() => toggle(`users/${arbitraryEmailMatch}`)}
+ onClick={() => toggle(`users/${visibleArbitraryEmailMatch}`)}
>
<SelectionCheckbox
selected={selectedFullnames.has(
- `users/${arbitraryEmailMatch}`
+ `users/${visibleArbitraryEmailMatch}`
)}
/>
<div
className="size-7 rounded-full flex items-center justify-center text-accent-text text-xs font-medium shrink-0"
style={{
- backgroundColor: getAvatarColor(arbitraryEmailMatch),
+ backgroundColor: getAvatarColor(visibleArbitraryEmailMatch),
}}
>
- {getInitials(arbitraryEmailMatch.split("@")[0])}
+ {getInitials(visibleArbitraryEmailMatch.split("@")[0])}
</div>
<div className="flex flex-col min-w-0">
<HighlightLabelText
- text={arbitraryEmailMatch}
+ text={visibleArbitraryEmailMatch}
keyword={search}
className="text-sm font-medium truncate"
/>
@@ -550,10 +614,10 @@ export function AccountMultiSelect({
{/* Empty state */}
{!includeAllUsers &&
- users.length === 0 &&
- groups.length === 0 &&
- !specialAccountMatch &&
- !arbitraryEmailMatch && (
+ visibleUsers.length === 0 &&
+ visibleGroups.length === 0 &&
+ !visibleSpecialAccountMatch &&
+ !visibleArbitraryEmailMatch && (
<div className="px-3 py-4 text-sm text-center text-control-light">
{t("common.no-data")}
</div>
diff --git a/frontend/src/components/UserCell.tsx b/frontend/src/components/UserCell.tsx
index 5577b363c1..610dda1918 100644
--- a/frontend/src/components/UserCell.tsx
+++ b/frontend/src/components/UserCell.tsx
@@ -85,7 +85,7 @@ export function UserCell({
) : (
<span
className={cn(
- "font-medium text-main",
+ "font-medium text-main truncate",
size === "sm" && "text-sm",
nameClassName
)}
@@ -106,13 +106,15 @@ export function UserCell({
<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">
+ <div className="flex flex-col min-w-0">
+ <div className="flex items-center gap-x-1.5 min-w-0">
{hoverableNameEl}
{badges}
</div>
{subtitle && (
- <span className="text-control-light text-xs">{subtitle}</span>
+ <span className="text-control-light text-xs truncate">
+ {subtitle}
+ </span>
)}
</div>
</div>
diff --git a/frontend/src/lib/memberBindings.ts b/frontend/src/lib/memberBindings.ts
index 5cad9a20ca..d6a1d3c45a 100644
--- a/frontend/src/lib/memberBindings.ts
+++ b/frontend/src/lib/memberBindings.ts
@@ -26,7 +26,7 @@ import { convertMemberToFullname, hasWorkspacePermissionV2 } from "@/utils";
// recreate the static ESM cycle the SQL editor connection move fixed.
// Members surfaces are React-only, so a React-side location is natural.
-const getMemberBinding = (
+export const getMemberBinding = (
member: string,
searchText: string
): MemberBinding | undefined => {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 8934cbaa17..397e02a4b1 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3090,13 +3090,16 @@
"rows-upper-limit": "reached the limit of query results",
"save-sheet": "Save query",
"saved-query-share": {
+ "add-people": "Add users or groups",
"editor": "Editor",
- "granted-at-other-level": "{{count}} more granted at another level.",
+ "load-failed": "Couldn't load sharing.",
"not-shared": "Not shared with anyone.",
"only-users-and-groups": "Only users and groups can be granted access.",
+ "owner": "Owner",
+ "people-with-access": "People with access",
"policy-changed": "Sharing changed elsewhere. Reloaded the latest.",
"private-hint": "Only you and workspace admins can open this saved query.",
- "shared-with": "Shared with",
+ "share-title": "“{{title}}”",
"viewer": "Viewer"
},
"scroll-to-bottom": "Scroll to the bottom",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 2ed85e524c..be89336222 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3090,13 +3090,16 @@
"rows-upper-limit": "se ha alcanzado el límite de resultados de la consulta",
"save-sheet": "Guardar consulta",
"saved-query-share": {
+ "add-people": "Agregar usuarios o grupos",
"editor": "Editor",
- "granted-at-other-level": "{{count}} más con acceso en otro nivel.",
+ "load-failed": "No se pudo cargar el uso compartido.",
"not-shared": "No compartido con nadie.",
"only-users-and-groups": "Solo se puede conceder acceso a usuarios y grupos.",
+ "owner": "Propietario",
+ "people-with-access": "Usuarios con acceso",
"policy-changed": "El uso compartido cambió en otro lugar. Se recargó la versión más reciente.",
"private-hint": "Solo tú y los administradores del espacio de trabajo pueden abrir esta consulta guardada.",
- "shared-with": "Compartido con",
+ "share-title": "“{{title}}”",
"viewer": "Lector"
},
"scroll-to-bottom": "Desplazarse hacia abajo",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a4aa237531..a403ae2c99 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3090,13 +3090,16 @@
"rows-upper-limit": "クエリ結果の数が上限に達しました",
"save-sheet": "クエリを保存",
"saved-query-share": {
+ "add-people": "ユーザーまたはグループを追加",
"editor": "編集者",
- "granted-at-other-level": "他のレベルで {{count}} 件付与されています。",
+ "load-failed": "共有設定を読み込めませんでした。",
"not-shared": "誰にも共有されていません。",
"only-users-and-groups": "アクセス権を付与できるのはユーザーとグループのみです。",
+ "owner": "オーナー",
+ "people-with-access": "アクセスできるユーザー",
"policy-changed": "共有設定が別の場所で変更されました。最新の状態を再読み込みしました。",
"private-hint": "この保存済みクエリを開けるのは、あなたとワークスペース管理者のみです。",
- "shared-with": "共有先",
+ "share-title": "「{{title}}」",
"viewer": "閲覧者"
},
"scroll-to-bottom": "末尾へスクロール",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index d6a9a8f28e..fa38e44454 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -3090,13 +3090,16 @@
"rows-upper-limit": "đã đạt đến giới hạn kết quả truy vấn",
"save-sheet": "Lưu truy vấn",
"saved-query-share": {
+ "add-people": "Thêm người dùng hoặc nhóm",
"editor": "Người chỉnh sửa",
- "granted-at-other-level": "Còn {{count}} mục được cấp ở mức khác.",
+ "load-failed": "Không thể tải chia sẻ.",
"not-shared": "Chưa chia sẻ với ai.",
"only-users-and-groups": "Chỉ có thể cấp quyền cho người dùng và nhóm.",
+ "owner": "Chủ sở hữu",
+ "people-with-access": "Người có quyền truy cập",
"policy-changed": "Cài đặt chia sẻ đã thay đổi ở nơi khác. Đã tải lại bản mới nhất.",
"private-hint": "Chỉ bạn và quản trị viên workspace có thể mở truy vấn đã lưu này.",
- "shared-with": "Được chia sẻ với",
+ "share-title": "“{{title}}”",
"viewer": "Người xem"
},
"scroll-to-bottom": "Cuộn xuống cuối",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 7befeeba5f..c3f48a00d6 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3090,13 +3090,16 @@
"rows-upper-limit": "到达查询结果条数上限",
"save-sheet": "保存查询",
"saved-query-share": {
+ "add-people": "添加用户或分组",
"editor": "编辑者",
- "granted-at-other-level": "另有 {{count}} 个成员在其他权限级别。",
+ "load-failed": "无法加载共享设置。",
"not-shared": "尚未共享给任何人。",
"only-users-and-groups": "只能将访问权限授予用户和用户组。",
+ "owner": "所有者",
+ "people-with-access": "拥有访问权限",
"policy-changed": "共享设置已在别处更改,已重新加载最新配置。",
"private-hint": "仅你和工作区管理员可以打开该已保存的查询。",
- "shared-with": "共享给",
+ "share-title": "“{{title}}”",
"viewer": "查看者"
},
"scroll-to-bottom": "滚动到底部",
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx
new file mode 100644
index 0000000000..e5a5e3770c
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.test.tsx
@@ -0,0 +1,883 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
+import type { ReactElement, ReactNode } from "react";
+import { act, createContext, createElement, useContext } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { SavedQueryPolicy } from "@/types/proto-es/v1/saved_query_service_pb";
+import {
+ SavedQueryBinding_Level,
+ SavedQueryPolicySchema,
+} from "@/types/proto-es/v1/saved_query_service_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ getSavedQueryPolicy: vi.fn<() => Promise<unknown>>(),
+ setSavedQueryPolicy: vi.fn<(name: string, policy: unknown) => Promise<unknown>>(),
+ batchGetOrFetchUsers: vi.fn(async () => []),
+ batchGetOrFetchGroups: vi.fn(async () => []),
+ notify: vi.fn(),
+ usersByBinding: {} as Record<string, { title: string; email: string }>,
+ groupsByBinding: {} as Record<string, { name: string; title: string }>,
+ // What the picker stub hands to onChange when clicked.
+ pickerSelection: [] as string[],
+ pickerProps: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/stores/app", () => {
+ const state = () => ({
+ currentUser: { email: "[email protected]" },
+ getSavedQueryPolicy: mocks.getSavedQueryPolicy,
+ setSavedQueryPolicy: mocks.setSavedQueryPolicy,
+ batchGetOrFetchUsers: mocks.batchGetOrFetchUsers,
+ batchGetOrFetchGroups: mocks.batchGetOrFetchGroups,
+ notify: mocks.notify,
+ getUserByIdentifier: (identifier: string) =>
+ mocks.usersByBinding[identifier],
+ getGroupByIdentifier: (identifier: string) =>
+ mocks.groupsByBinding[identifier],
+ });
+ return {
+ useAppStore: Object.assign(
+ (selector: (s: ReturnType<typeof state>) => unknown) => selector(state()),
+ { getState: state }
+ ),
+ };
+});
+
+// The picker's own behavior (search, toggle, labels) has its own tests; here a
+// stub exposes the `onChange` contract: clicking it reports
+// `mocks.pickerSelection` the way a user picking those accounts would.
+vi.mock("@/components/AccountMultiSelect", () => ({
+ AccountMultiSelect: (props: {
+ value: string[];
+ onChange: (value: string[]) => void;
+ disabled?: boolean;
+ excludeAccounts?: string[];
+ placeholder?: string;
+ }) => {
+ mocks.pickerProps(props);
+ return createElement(
+ "button",
+ {
+ type: "button",
+ "data-testid": "account-picker",
+ disabled: props.disabled,
+ onClick: () => props.onChange(mocks.pickerSelection),
+ },
+ "picker"
+ );
+ },
+}));
+
+// Functional stand-in for the Base UI select. Faithful on the axis that
+// matters here: a bare `<SelectValue />` renders the raw stringified value
+// (Base UI has no Radix-style echo of the selected item's label), while a
+// render-function child maps value → label. Items are buttons that fire
+// `onValueChange` so tests can drive level changes.
+vi.mock("@/components/ui/select", () => {
+ const SelectCtx = createContext<{
+ value?: unknown;
+ onValueChange?: (value: never) => void;
+ disabled?: boolean;
+ }>({});
+ return {
+ Select: ({
+ children,
+ value,
+ onValueChange,
+ disabled,
+ }: {
+ children: ReactNode;
+ value?: unknown;
+ onValueChange?: (value: never) => void;
+ disabled?: boolean;
+ }) =>
+ createElement(
+ SelectCtx.Provider,
+ { value: { value, onValueChange, disabled } },
+ children
+ ),
+ SelectTrigger: ({ children }: { children?: ReactNode }) =>
+ createElement("div", { "data-testid": "select-trigger" }, children),
+ SelectValue: ({
+ children,
+ }: {
+ children?: ReactNode | ((value: unknown) => ReactNode);
+ }) => {
+ const ctx = useContext(SelectCtx);
+ return createElement(
+ "span",
+ { "data-testid": "select-value" },
+ typeof children === "function"
+ ? children(ctx.value)
+ : (children ?? String(ctx.value))
+ );
+ },
+ SelectContent: ({ children }: { children?: ReactNode }) =>
+ createElement("div", {}, children),
+ SelectItem: ({
+ children,
+ value,
+ }: {
+ children?: ReactNode;
+ value: unknown;
+ }) => {
+ const ctx = useContext(SelectCtx);
+ return createElement(
+ "button",
+ {
+ type: "button",
+ "data-testid": "select-item",
+ "data-value": String(value),
+ disabled: ctx.disabled,
+ onClick: () => ctx.onValueChange?.(value as never),
+ },
+ children
+ );
+ },
+ };
+});
+
+// The hover card fetches on open; rows only need its children rendered.
+vi.mock("@/components/UserHoverCard", () => ({
+ UserHoverCard: ({ children }: { children: ReactNode }) => children,
+}));
+
+let SavedQueryGrantEditor: typeof import("./SavedQueryGrantEditor").SavedQueryGrantEditor;
+
+const mockSavedQuery = {
+ name: "projects/proj1/savedQueries/1",
+ project: "projects/proj1",
+ creator: "users/[email protected]",
+ title: "test sheet",
+} as never;
+
+const makePolicy = (
+ init?: Partial<{ bindings: unknown[]; etag: string }>
+): SavedQueryPolicy =>
+ createProto(SavedQueryPolicySchema, {
+ bindings: [
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "group:[email protected]"],
+ },
+ {
+ level: SavedQueryBinding_Level.EDITOR,
+ members: ["user:[email protected]"],
+ },
+ ],
+ etag: "v1",
+ ...init,
+ } as never);
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ document.body.appendChild(container);
+ return {
+ container,
+ render: async () => {
+ await act(async () => {
+ root.render(element);
+ });
+ },
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+};
+
+const rowFor = (container: HTMLElement, member: string) =>
+ container.querySelector<HTMLElement>(
+ `[data-testid="grant-row"][data-member="${member}"]`
+ );
+
+const clickLevelItem = async (scope: HTMLElement, level: number) => {
+ const item = Array.from(
+ scope.querySelectorAll<HTMLButtonElement>('[data-testid="select-item"]')
+ ).find((candidate) => candidate.dataset.value === String(level));
+ expect(item).toBeTruthy();
+ await act(async () => {
+ item?.click();
+ });
+};
+
+const lastPickerProps = () =>
+ mocks.pickerProps.mock.lastCall?.[0] as {
+ value: string[];
+ excludeAccounts?: string[];
+ placeholder?: string;
+ };
+
+const writtenBindings = () => {
+ const policy = mocks.setSavedQueryPolicy.mock.lastCall?.[1] as
+ | SavedQueryPolicy
+ | undefined;
+ return policy?.bindings.map((binding) => ({
+ level: binding.level,
+ members: [...binding.members],
+ }));
+};
+
+beforeEach(async () => {
+ // resetAllMocks, not clearAllMocks: it also drops unconsumed mock*Once
+ // queues (a test that queues a rejection but bails early must not leak it
+ // into the next test's first write).
+ vi.resetAllMocks();
+ mocks.getSavedQueryPolicy.mockImplementation(async () => makePolicy());
+ // Echo the written policy back, the way the server returns the stored one.
+ mocks.setSavedQueryPolicy.mockImplementation(
+ async (_name, policy) => policy as SavedQueryPolicy
+ );
+ mocks.usersByBinding = {
+ "user:[email protected]": { title: "Viewer Vi", email: "[email protected]" },
+ "user:[email protected]": { title: "Editor Ed", email: "[email protected]" },
+ };
+ mocks.groupsByBinding = {
+ "group:[email protected]": { name: "groups/[email protected]", title: "Team X" },
+ };
+ mocks.pickerSelection = [];
+ ({ SavedQueryGrantEditor } = await import("./SavedQueryGrantEditor"));
+});
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("SavedQueryGrantEditor", () => {
+ test("renders one row per grantee with resolved names and level labels", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const rows = container.querySelectorAll('[data-testid="grant-row"]');
+ expect(rows).toHaveLength(3);
+
+ const viewerRow = rowFor(container, "user:[email protected]");
+ expect(viewerRow?.textContent).toContain("Viewer Vi");
+ expect(viewerRow?.textContent).toContain("[email protected]");
+ expect(
+ viewerRow?.querySelector('[data-testid="select-value"]')?.textContent
+ ).toBe("sql-editor.saved-query-share.viewer");
+
+ const groupRow = rowFor(container, "group:[email protected]");
+ expect(groupRow?.textContent).toContain("Team X");
+
+ const editorRow = rowFor(container, "user:[email protected]");
+ expect(
+ editorRow?.querySelector('[data-testid="select-value"]')?.textContent
+ ).toBe("sql-editor.saved-query-share.editor");
+
+ // The list carries an accessible name via its caption.
+ expect(
+ container.querySelector("ul")?.getAttribute("aria-labelledby")
+ ).toBe("saved-query-grantee-caption");
+
+ // Regression for the raw-enum bug: no select renders "1" or "2".
+ for (const value of container.querySelectorAll(
+ '[data-testid="select-value"]'
+ )) {
+ expect(["1", "2"]).not.toContain(value.textContent);
+ }
+ unmount();
+ });
+
+ test("prefetches user and group display names referenced by the policy", async () => {
+ const { render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ expect(mocks.batchGetOrFetchUsers).toHaveBeenCalledWith([
+ ]);
+ expect(mocks.batchGetOrFetchGroups).toHaveBeenCalledWith([
+ ]);
+ unmount();
+ });
+
+ test("changing a row's level moves the member and keeps the etag", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const viewerRow = rowFor(container, "user:[email protected]");
+ await clickLevelItem(viewerRow as HTMLElement, SavedQueryBinding_Level.EDITOR);
+
+ expect(mocks.setSavedQueryPolicy).toHaveBeenCalledTimes(1);
+ expect(writtenBindings()).toEqual([
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["group:[email protected]"],
+ },
+ {
+ level: SavedQueryBinding_Level.EDITOR,
+ members: ["user:[email protected]", "user:[email protected]"],
+ },
+ ]);
+ const written = mocks.setSavedQueryPolicy.mock.lastCall?.[1] as SavedQueryPolicy;
+ expect(written.etag).toBe("v1");
+ unmount();
+ });
+
+ test("re-selecting a row's current level writes nothing", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const viewerRow = rowFor(container, "user:[email protected]");
+ await clickLevelItem(viewerRow as HTMLElement, SavedQueryBinding_Level.VIEWER);
+
+ expect(mocks.setSavedQueryPolicy).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("removing a member drops them and strips the emptied binding", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const editorRow = rowFor(container, "user:[email protected]");
+ const removeButton = editorRow?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="common.remove"]'
+ );
+ expect(removeButton).toBeTruthy();
+ await act(async () => {
+ removeButton?.click();
+ });
+
+ expect(writtenBindings()).toEqual([
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "group:[email protected]"],
+ },
+ ]);
+ unmount();
+ });
+
+ test("staged people do not write until Add commits them at the invite level", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ // Resting state: only the field — the commit controls do not exist yet.
+ const invite = container.querySelector<HTMLElement>(
+ '[data-testid="grant-invite"]'
+ );
+ expect(
+ container.querySelector('[data-testid="grant-add"]')
+ ).toBeNull();
+ expect(invite?.querySelector('[data-testid="select-item"]')).toBeNull();
+
+ // Stage a new user: the chips and the level+Add row appear, but there is
+ // no policy write and no grant row yet.
+ mocks.pickerSelection = ["user:[email protected]"];
+ const picker = container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ );
+ await act(async () => {
+ picker?.click();
+ });
+ expect(mocks.setSavedQueryPolicy).not.toHaveBeenCalled();
+ expect(lastPickerProps().value).toEqual(["user:[email protected]"]);
+ expect(rowFor(container, "user:[email protected]")).toBeNull();
+ const addButton = container.querySelector<HTMLButtonElement>(
+ '[data-testid="grant-add"]'
+ );
+ expect(addButton?.disabled).toBe(false);
+
+ // The invite level is chosen after staging, Drive-style.
+ await clickLevelItem(invite as HTMLElement, SavedQueryBinding_Level.EDITOR);
+ await act(async () => {
+ addButton?.click();
+ });
+ expect(writtenBindings()).toEqual([
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "group:[email protected]"],
+ },
+ {
+ level: SavedQueryBinding_Level.EDITOR,
+ members: ["user:[email protected]", "user:[email protected]"],
+ },
+ ]);
+ expect(lastPickerProps().value).toEqual([]);
+ expect(rowFor(container, "user:[email protected]")).not.toBeNull();
+ // The compose session is over: the commit controls fold away, the level
+ // defaults back to Viewer for the next one, and focus re-homes to the
+ // section instead of falling to <body>.
+ expect(container.querySelector('[data-testid="grant-add"]')).toBeNull();
+ expect(document.activeElement).toBe(container.querySelector("section"));
+
+ mocks.pickerSelection = ["user:[email protected]"];
+ await act(async () => {
+ picker?.click();
+ });
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>('[data-testid="grant-add"]')
+ ?.click();
+ });
+ expect(writtenBindings()).toContainEqual({
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "group:[email protected]", "user:[email protected]"],
+ });
+ unmount();
+ });
+
+ test("the picker excludes the caller, the creator, and current grantees", async () => {
+ const { render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ expect([...(lastPickerProps().excludeAccounts ?? [])].sort()).toEqual(
+ [
+ ].sort()
+ );
+ expect(lastPickerProps().placeholder).toBe(
+ "sql-editor.saved-query-share.add-people"
+ );
+ unmount();
+ });
+
+ test("Add with only already-granted selections clears staging without writing", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ mocks.pickerSelection = ["user:[email protected]"];
+ const picker = container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ );
+ await act(async () => {
+ picker?.click();
+ });
+ const addButton = container.querySelector<HTMLButtonElement>(
+ '[data-testid="grant-add"]'
+ );
+ await act(async () => {
+ addButton?.click();
+ });
+
+ expect(mocks.setSavedQueryPolicy).not.toHaveBeenCalled();
+ expect(lastPickerProps().value).toEqual([]);
+ unmount();
+ });
+
+ test("rejects non user/group grantees at selection time", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ mocks.pickerSelection = ["serviceAccount:[email protected]"];
+ const picker = container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ );
+ await act(async () => {
+ picker?.click();
+ });
+
+ expect(mocks.notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ style: "WARN",
+ title: "sql-editor.saved-query-share.only-users-and-groups",
+ })
+ );
+ // Nothing staged: the chip never appears and the commit row never shows.
+ expect(lastPickerProps().value).toEqual([]);
+ expect(container.querySelector('[data-testid="grant-add"]')).toBeNull();
+ expect(mocks.setSavedQueryPolicy).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("pins the creator as a static Owner row, with a you badge for the caller", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const ownerRow = container.querySelector<HTMLElement>(
+ '[data-testid="grant-owner-row"]'
+ );
+ expect(ownerRow?.textContent).toContain("[email protected]");
+ expect(ownerRow?.textContent).toContain(
+ "sql-editor.saved-query-share.owner"
+ );
+ // The creator is not the caller here, so no badge; and the Owner row
+ // carries no controls.
+ expect(ownerRow?.textContent).not.toContain("common.you");
+ expect(ownerRow?.querySelector("button")).toBeNull();
+ unmount();
+
+ const own = renderIntoContainer(
+ <SavedQueryGrantEditor
+ savedQuery={
+ { ...(mockSavedQuery as object), creator: "users/[email protected]" } as never
+ }
+ canManage={true}
+ />
+ );
+ await own.render();
+ expect(
+ own.container.querySelector('[data-testid="grant-owner-row"]')
+ ?.textContent
+ ).toContain("common.you");
+ own.unmount();
+ });
+
+ test("a creator listed in the bindings is hidden from rows but kept on write", async () => {
+ mocks.getSavedQueryPolicy.mockImplementation(async () =>
+ makePolicy({
+ bindings: [
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "user:[email protected]"],
+ },
+ {
+ level: SavedQueryBinding_Level.EDITOR,
+ members: ["user:[email protected]"],
+ },
+ ],
+ })
+ );
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ expect(rowFor(container, "user:[email protected]")).toBeNull();
+ expect(
+ container.querySelector('[data-testid="grant-owner-row"]')
+ ).not.toBeNull();
+
+ // A rewrite through another row keeps the hidden creator binding.
+ const editorRow = rowFor(container, "user:[email protected]");
+ await clickLevelItem(editorRow as HTMLElement, SavedQueryBinding_Level.VIEWER);
+ expect(writtenBindings()).toEqual([
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: [
+ ],
+ },
+ ]);
+ unmount();
+ });
+
+ test("a failed Add keeps the staged people for retry", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ mocks.pickerSelection = ["user:[email protected]"];
+ const picker = container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ );
+ await act(async () => {
+ picker?.click();
+ });
+ mocks.setSavedQueryPolicy.mockRejectedValueOnce(new Error("boom"));
+ const addButton = container.querySelector<HTMLButtonElement>(
+ '[data-testid="grant-add"]'
+ );
+ await act(async () => {
+ addButton?.click();
+ });
+
+ expect(mocks.notify).toHaveBeenCalledWith(
+ expect.objectContaining({ style: "CRITICAL" })
+ );
+ expect(lastPickerProps().value).toEqual(["user:[email protected]"]);
+ unmount();
+ });
+
+ test("an aborted write warns about the conflict and reloads the policy", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+ expect(mocks.getSavedQueryPolicy).toHaveBeenCalledTimes(1);
+
+ mocks.setSavedQueryPolicy.mockRejectedValueOnce(
+ new ConnectError("conflict", Code.Aborted)
+ );
+ const editorRow = rowFor(container, "user:[email protected]");
+ await clickLevelItem(editorRow as HTMLElement, SavedQueryBinding_Level.VIEWER);
+
+ expect(mocks.notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ style: "WARN",
+ title: "sql-editor.saved-query-share.policy-changed",
+ })
+ );
+ expect(mocks.getSavedQueryPolicy).toHaveBeenCalledTimes(2);
+ // The conflict reload must hand the controls back for a retry.
+ expect(
+ container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ )?.disabled
+ ).toBe(false);
+ unmount();
+ });
+
+ test("controls stay disabled while a write is in flight", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ let finish: (policy: SavedQueryPolicy) => void = () => {};
+ mocks.setSavedQueryPolicy.mockImplementationOnce(
+ (_name, policy) =>
+ new Promise((resolve) => {
+ finish = () => resolve(policy as SavedQueryPolicy);
+ })
+ );
+ const editorRow = rowFor(container, "user:[email protected]");
+ const removeButton = editorRow?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="common.remove"]'
+ );
+ await act(async () => {
+ removeButton?.click();
+ });
+
+ expect(
+ container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ )?.disabled
+ ).toBe(true);
+ expect(
+ rowFor(container, "user:[email protected]")?.querySelector<HTMLButtonElement>(
+ 'button[aria-label="common.remove"]'
+ )?.disabled
+ ).toBe(true);
+
+ await act(async () => {
+ finish(makePolicy());
+ });
+ expect(
+ container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ )?.disabled
+ ).toBe(false);
+ unmount();
+ });
+
+ test("read-only view lists grantees with level text and no controls", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={false} />
+ );
+ await render();
+
+ expect(container.querySelectorAll('[data-testid="grant-row"]')).toHaveLength(
+ 3
+ );
+ expect(container.querySelector('[data-testid="account-picker"]')).toBeNull();
+ expect(container.querySelector('[data-testid="select-item"]')).toBeNull();
+ expect(
+ container.querySelector('button[aria-label="common.remove"]')
+ ).toBeNull();
+ expect(rowFor(container, "user:[email protected]")?.textContent).toContain(
+ "sql-editor.saved-query-share.editor"
+ );
+ unmount();
+ });
+
+ test("empty policy shows the private hint to managers and not-shared to readers", async () => {
+ mocks.getSavedQueryPolicy.mockImplementation(async () =>
+ makePolicy({ bindings: [] })
+ );
+
+ const managed = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await managed.render();
+ expect(managed.container.textContent).toContain(
+ "sql-editor.saved-query-share.private-hint"
+ );
+ managed.unmount();
+
+ // Readers see the Owner row instead of text that would contradict it.
+ const readOnly = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={false} />
+ );
+ await readOnly.render();
+ expect(
+ readOnly.container.querySelector('[data-testid="grant-owner-row"]')
+ ).not.toBeNull();
+ expect(readOnly.container.textContent).not.toContain(
+ "sql-editor.saved-query-share.not-shared"
+ );
+ readOnly.unmount();
+ });
+
+ test("a write finishing after a saved-query switch cannot touch the new editor", async () => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ // Query A: start a remove whose write resolves under our control.
+ await act(async () => {
+ root.render(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ });
+ let finish: () => void = () => {};
+ mocks.setSavedQueryPolicy.mockImplementationOnce(
+ (_name, policy) =>
+ new Promise((resolve) => {
+ finish = () => resolve(policy as SavedQueryPolicy);
+ })
+ );
+ const editorRow = rowFor(container, "user:[email protected]");
+ await act(async () => {
+ editorRow
+ ?.querySelector<HTMLButtonElement>('button[aria-label="common.remove"]')
+ ?.click();
+ });
+
+ // Switch to query B while A's write is still in flight.
+ mocks.getSavedQueryPolicy.mockImplementation(async () =>
+ makePolicy({
+ bindings: [
+ { level: SavedQueryBinding_Level.VIEWER, members: ["user:[email protected]"] },
+ ],
+ etag: "b1",
+ })
+ );
+ await act(async () => {
+ root.render(
+ <SavedQueryGrantEditor
+ savedQuery={
+ {
+ ...(mockSavedQuery as object),
+ name: "projects/proj1/savedQueries/2",
+ } as never
+ }
+ canManage={true}
+ />
+ );
+ });
+ expect(rowFor(container, "user:[email protected]")).not.toBeNull();
+ // B's controls are live, not held hostage by A's in-flight write.
+ expect(
+ container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ )?.disabled
+ ).toBe(false);
+
+ // A's write resolves late: B's rows must be untouched by its echo.
+ await act(async () => {
+ finish();
+ });
+ expect(rowFor(container, "user:[email protected]")).not.toBeNull();
+ expect(rowFor(container, "user:[email protected]")).toBeNull();
+
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ test("bindings at unknown levels pass through rewrites untouched", async () => {
+ mocks.getSavedQueryPolicy.mockImplementation(async () =>
+ makePolicy({
+ bindings: [
+ {
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]"],
+ },
+ { level: 99, members: ["user:[email protected]"] },
+ ],
+ })
+ );
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ // The unknown level renders no row, but survives the rewrite verbatim.
+ expect(rowFor(container, "user:[email protected]")).toBeNull();
+ const viewerRow = rowFor(container, "user:[email protected]");
+ await clickLevelItem(
+ viewerRow as HTMLElement,
+ SavedQueryBinding_Level.EDITOR
+ );
+ expect(writtenBindings()).toEqual([
+ {
+ level: SavedQueryBinding_Level.EDITOR,
+ members: ["user:[email protected]"],
+ },
+ { level: 99, members: ["user:[email protected]"] },
+ ]);
+ unmount();
+ });
+
+ test("deselecting every chip resets the invite level to Viewer", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <SavedQueryGrantEditor savedQuery={mockSavedQuery} canManage={true} />
+ );
+ await render();
+
+ const picker = container.querySelector<HTMLButtonElement>(
+ '[data-testid="account-picker"]'
+ );
+ mocks.pickerSelection = ["user:[email protected]"];
+ await act(async () => {
+ picker?.click();
+ });
+ const invite = container.querySelector<HTMLElement>(
+ '[data-testid="grant-invite"]'
+ );
+ await clickLevelItem(invite as HTMLElement, SavedQueryBinding_Level.EDITOR);
+
+ // Abandon the compose session by clearing the selection, then stage again:
+ // the level must be back at the safe default.
+ mocks.pickerSelection = [];
+ await act(async () => {
+ picker?.click();
+ });
+ mocks.pickerSelection = ["user:[email protected]"];
+ await act(async () => {
+ picker?.click();
+ });
+ await act(async () => {
+ container
+ .querySelector<HTMLButtonElement>('[data-testid="grant-add"]')
+ ?.click();
+ });
+ expect(writtenBindings()).toContainEqual({
+ level: SavedQueryBinding_Level.VIEWER,
+ members: ["user:[email protected]", "group:[email protected]", "user:[email protected]"],
+ });
+ unmount();
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
index c09f9d0a8c..21095c7e7d 100644
--- a/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
+++ b/frontend/src/modules/sql-editor/components/SavedQueryGrantEditor.tsx
@@ -1,8 +1,14 @@
import { create as createProto } from "@bufbuild/protobuf";
import { Code, ConnectError } from "@connectrpc/connect";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import type { TFunction } from "i18next";
+import { Trash2, Users } from "lucide-react";
+import type { ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { AccountMultiSelect } from "@/components/AccountMultiSelect";
+import { UserCell } from "@/components/UserCell";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
@@ -10,7 +16,15 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { getMemberBinding } from "@/lib/memberBindings";
+import { extractGroupEmail } from "@/stores";
import { useAppStore } from "@/stores/app";
+import { extractUserEmail } from "@/stores/modules/v1/common";
+import {
+ getUserEmailInBinding,
+ groupBindingPrefix,
+ userBindingPrefix,
+} from "@/types";
import type {
SavedQuery,
SavedQueryPolicy,
@@ -31,6 +45,12 @@ type Props = {
readonly canManage: boolean;
};
+/** One grantee and the single level they hold. */
+type Grant = {
+ readonly member: string;
+ readonly level: SavedQueryBinding_Level;
+};
+
const GRANTABLE_LEVELS = [
SavedQueryBinding_Level.VIEWER,
SavedQueryBinding_Level.EDITOR,
@@ -46,103 +66,151 @@ const isGrantableMember = (member: string) =>
/**
* Reads a saved query's sharing policy and, for its creator or an admin,
- * edits it. Writes replace the policy in full under the etag the read
- * returned; a concurrent change aborts the write so a revocation someone else
- * just made is never silently reinstated.
+ * edits it. Adds are staged: picked accounts sit as chips until the Add
+ * button commits them at the invite level in one write (the BigQuery /
+ * Snowsight / Databricks confirm-the-add pattern), while each grantee row's
+ * level select and remove button apply per action. Every write rewrites the
+ * policy in full under the etag the read returned; a concurrent change
+ * aborts the write so a revocation someone else just made is never silently
+ * reinstated.
*/
export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
const { t } = useTranslation();
- const levelLabel = (level: SavedQueryBinding_Level) =>
- level === SavedQueryBinding_Level.EDITOR
- ? t("sql-editor.saved-query-share.editor")
- : t("sql-editor.saved-query-share.viewer");
const getSavedQueryPolicy = useAppStore((s) => s.getSavedQueryPolicy);
const setSavedQueryPolicy = useAppStore((s) => s.setSavedQueryPolicy);
+ const batchGetOrFetchUsers = useAppStore((s) => s.batchGetOrFetchUsers);
+ const batchGetOrFetchGroups = useAppStore((s) => s.batchGetOrFetchGroups);
const notify = useAppStore((s) => s.notify);
+ const currentUserEmail = useAppStore((s) => s.currentUser?.email);
const [policy, setPolicy] = useState<SavedQueryPolicy | undefined>();
- const [level, setLevel] = useState<SavedQueryBinding_Level>(
+ const [inviteLevel, setInviteLevel] = useState<SavedQueryBinding_Level>(
SavedQueryBinding_Level.VIEWER
);
+ // Accounts picked but not yet granted: chips in the picker until Add.
+ const [pending, setPending] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ // Focus recovery target after a commit/remove unmounts the focused control.
+ const sectionRef = useRef<HTMLElement>(null);
+ // Rejects policy responses that land after a newer load started (the
+ // popover instance can outlive a switch to a different saved query).
+ const loadGeneration = useRef(0);
const load = useCallback(async () => {
+ const generation = ++loadGeneration.current;
setLoading(true);
try {
- setPolicy(await getSavedQueryPolicy(savedQuery.name));
+ const fetched = await getSavedQueryPolicy(savedQuery.name);
+ if (generation !== loadGeneration.current) return;
+ setPolicy(fetched);
+ // Prefetch grantee display names; rows fall back to emails if this fails.
+ const members = fetched.bindings.flatMap((binding) => binding.members);
+ void Promise.allSettled([
+ batchGetOrFetchUsers(
+ members.filter((member) => !member.startsWith(groupBindingPrefix))
+ ),
+ batchGetOrFetchGroups(
+ members.filter((member) => member.startsWith(groupBindingPrefix))
+ ),
+ ]);
} catch {
+ if (generation !== loadGeneration.current) return;
setPolicy(undefined);
} finally {
- setLoading(false);
+ if (generation === loadGeneration.current) setLoading(false);
}
- }, [getSavedQueryPolicy, savedQuery.name]);
+ }, [
+ batchGetOrFetchGroups,
+ batchGetOrFetchUsers,
+ getSavedQueryPolicy,
+ savedQuery.name,
+ ]);
useEffect(() => {
+ // `load` changes identity exactly when `savedQuery.name` does; a
+ // different saved query is a fresh editor, so nothing staged — and no
+ // previously loaded policy or its etag — may carry over.
+ setPolicy(undefined);
+ setPending([]);
+ setInviteLevel(SavedQueryBinding_Level.VIEWER);
+ setSaving(false);
void load();
}, [load]);
- // The picker edits one level at a time, so members are flattened into the
- // selected level's list and rewritten as a single binding on save.
- const membersAtLevel = useMemo(
- () =>
- policy?.bindings.find((binding) => binding.level === level)?.members ??
- [],
- [policy, level]
- );
+ // One row per grantee, grouped viewers first; within a level, rows keep the
+ // policy's member order. A level change moves its row to the end of the new
+ // level's group (writes append the touched member). A member duplicated
+ // across levels (which the server rejects) collapses to their first listing.
+ const grants = useMemo<Grant[]>(() => {
+ if (!policy) return [];
+ const rows: Grant[] = [];
+ const seen = new Set<string>();
+ for (const level of GRANTABLE_LEVELS) {
+ for (const binding of policy.bindings) {
+ if (binding.level !== level) continue;
+ for (const member of binding.members) {
+ if (seen.has(member)) continue;
+ seen.add(member);
+ rows.push({ member, level });
+ }
+ }
+ }
+ return rows;
+ }, [policy]);
+
+ // The creator renders as a pinned Owner row, not a grant row: ownership is
+ // not a binding. A degenerate policy that does list the creator keeps its
+ // binding through rewrites — it is only hidden from the rows.
+ const creatorMember = useMemo(() => {
+ const email = extractUserEmail(savedQuery.creator);
+ return email && email !== savedQuery.creator
+ ? getUserEmailInBinding(email)
+ : "";
+ }, [savedQuery.creator]);
- const membersAtOtherLevel = useMemo(
- () =>
- policy?.bindings
- .filter((binding) => binding.level !== level)
- .flatMap((binding) => binding.members) ?? [],
- [policy, level]
+ const grantRows = useMemo(
+ () => grants.filter((grant) => grant.member !== creatorMember),
+ [grants, creatorMember]
);
- const handleChange = async (members: string[]) => {
- if (!policy) return;
- const rejected = members.filter((member) => !isGrantableMember(member));
- if (rejected.length > 0) {
- notify({
- module: "bytebase",
- style: "WARN",
- title: t("sql-editor.saved-query-share.only-users-and-groups"),
- });
- }
- const granted = members.filter(isGrantableMember);
- // A member holds one level at a time: promoting or demoting somebody drops
- // them from the level they used to hold rather than leaving both.
- const promoted = new Set(granted);
-
- const bindings = [];
- for (const candidate of GRANTABLE_LEVELS) {
- const at =
- candidate === level
- ? granted
- : (policy.bindings
- .find((binding) => binding.level === candidate)
- ?.members.filter((member) => !promoted.has(member)) ?? []);
- if (at.length > 0) {
- bindings.push(
- createProto(SavedQueryBindingSchema, {
- level: candidate,
- members: at,
- })
- );
- }
- }
+ // Whether the write succeeded — Add keeps its staged chips on failure.
+ const writeGrants = async (next: Grant[]): Promise<boolean> => {
+ if (!policy) return false;
+ // The write belongs to the editor state it started from; once a switch to
+ // another saved query bumps the generation, its completion must neither
+ // replace the new policy nor reload/toast for the old query.
+ const generation = loadGeneration.current;
+ const bindings = [
+ ...GRANTABLE_LEVELS.map((level) =>
+ createProto(SavedQueryBindingSchema, {
+ level,
+ members: next
+ .filter((grant) => grant.level === level)
+ .map((grant) => grant.member),
+ })
+ ).filter((binding) => binding.members.length > 0),
+ // Levels this bundle does not know (a newer server's) pass through
+ // untouched — the same carry-through the creator binding gets.
+ ...policy.bindings.filter(
+ (binding) =>
+ !(GRANTABLE_LEVELS as readonly SavedQueryBinding_Level[]).includes(
+ binding.level
+ )
+ ),
+ ];
setSaving(true);
try {
- const next = await setSavedQueryPolicy(
+ const updated = await setSavedQueryPolicy(
savedQuery.name,
- createProto(SavedQueryPolicySchema, {
- bindings,
- etag: policy.etag,
- })
+ createProto(SavedQueryPolicySchema, { bindings, etag: policy.etag })
);
- setPolicy(next);
+ if (generation !== loadGeneration.current) return false;
+ setPolicy(updated);
+ return true;
} catch (error) {
+ if (generation !== loadGeneration.current) return false;
if (error instanceof ConnectError && error.code === Code.Aborted) {
// Somebody else changed the grants between the read and this write.
// Reload rather than retrying, so their change is not overwritten.
@@ -151,8 +219,11 @@ export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
style: "WARN",
title: t("sql-editor.saved-query-share.policy-changed"),
});
+ // The write is over; clear saving before the reload, whose own
+ // generation bump makes the guarded finally skip it.
+ setSaving(false);
await load();
- return;
+ return false;
}
notify({
module: "bytebase",
@@ -160,8 +231,78 @@ export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
title:
error instanceof ConnectError ? error.message : t("common.error"),
});
+ return false;
} finally {
- setSaving(false);
+ if (generation === loadGeneration.current) setSaving(false);
+ }
+ };
+
+ // Hidden from the picker: accounts a grant would be pointless or redundant
+ // for. The creator and the caller hold access already; grantees change
+ // level through their row, not by re-adding.
+ const excludeAccounts = useMemo(() => {
+ const excluded = new Set(grants.map((grant) => grant.member));
+ if (currentUserEmail) excluded.add(getUserEmailInBinding(currentUserEmail));
+ if (creatorMember) excluded.add(creatorMember);
+ return [...excluded];
+ }, [grants, currentUserEmail, creatorMember]);
+
+ const stagePending = (members: string[]) => {
+ const rejected = members.filter((member) => !isGrantableMember(member));
+ if (rejected.length > 0) {
+ notify({
+ module: "bytebase",
+ style: "WARN",
+ title: t("sql-editor.saved-query-share.only-users-and-groups"),
+ });
+ }
+ const granted = members.filter(isGrantableMember);
+ if (granted.length === 0) {
+ // Empty staging ends the compose session: the next one starts back at
+ // the safe default, matching a committed Add.
+ setInviteLevel(SavedQueryBinding_Level.VIEWER);
+ }
+ setPending(granted);
+ };
+
+ const handleAdd = async () => {
+ if (pending.length === 0) return;
+ // A member holds one level at a time: adding an existing grantee (still
+ // possible through a concurrent grant elsewhere) moves them to the invite
+ // level instead of granting both.
+ const touched = new Set(pending);
+ const next = [
+ ...grants.filter((grant) => !touched.has(grant.member)),
+ ...pending.map((member) => ({ member, level: inviteLevel })),
+ ];
+ if (sameGrants(grants, next)) {
+ setPending([]);
+ setInviteLevel(SavedQueryBinding_Level.VIEWER);
+ return;
+ }
+ if (await writeGrants(next)) {
+ setPending([]);
+ // Each add is its own compose session; the next one starts back at the
+ // safe default.
+ setInviteLevel(SavedQueryBinding_Level.VIEWER);
+ // The commit row just unmounted under the focused Add button.
+ sectionRef.current?.focus();
+ }
+ };
+
+ const changeLevel = (member: string, level: SavedQueryBinding_Level) => {
+ const current = grants.find((grant) => grant.member === member);
+ if (!current || current.level === level) return;
+ void writeGrants([
+ ...grants.filter((grant) => grant.member !== member),
+ { member, level },
+ ]);
+ };
+
+ const removeMember = async (member: string) => {
+ if (await writeGrants(grants.filter((grant) => grant.member !== member))) {
+ // The row holding the focused remove button just unmounted.
+ sectionRef.current?.focus();
}
};
@@ -171,85 +312,243 @@ export function SavedQueryGrantEditor({ savedQuery, canManage }: Props) {
);
}
if (!policy) {
- return null;
+ // A failed read must not look like "nothing to manage" — say so and
+ // offer a retry in place.
+ return (
+ <div className="flex items-center gap-x-2 text-sm text-control-light">
+ <span>{t("sql-editor.saved-query-share.load-failed")}</span>
+ <Button
+ type="button"
+ appearance="link"
+ size="sm"
+ onClick={() => void load()}
+ >
+ {t("common.refresh")}
+ </Button>
+ </div>
+ );
}
return (
- <section className="flex flex-col gap-y-2">
- <div className="flex items-center justify-between gap-x-2">
- <h3 className="text-sm font-medium">
- {t("sql-editor.saved-query-share.shared-with")}
- </h3>
- {canManage && (
- <Select
- value={String(level)}
- onValueChange={(next) =>
- setLevel(Number(next) as SavedQueryBinding_Level)
- }
- >
- <SelectTrigger size="sm" className="w-28">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {GRANTABLE_LEVELS.map((candidate) => (
- <SelectItem key={candidate} value={String(candidate)}>
- {levelLabel(candidate)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- </div>
-
- {canManage ? (
- <>
+ <section
+ ref={sectionRef}
+ tabIndex={-1}
+ className="flex flex-col gap-y-2 focus:outline-hidden"
+ >
+ {canManage && (
+ <div data-testid="grant-invite" className="flex flex-col gap-y-2">
<AccountMultiSelect
- value={membersAtLevel}
- onChange={(members) => void handleChange(members)}
+ value={pending}
+ onChange={stagePending}
disabled={saving}
+ excludeAccounts={excludeAccounts}
+ placeholder={t("sql-editor.saved-query-share.add-people")}
/>
- {membersAtOtherLevel.length > 0 && (
- <p className="text-xs text-control-light">
- {t("sql-editor.saved-query-share.granted-at-other-level", {
- count: membersAtOtherLevel.length,
- })}
- </p>
- )}
- </>
- ) : policy.bindings.length === 0 ? (
- <p className="text-sm text-control-light">
- {t("sql-editor.saved-query-share.not-shared")}
- </p>
- ) : (
- // Labelled by level, not flattened: this read-only view is the only
- // place a grantee can see whether they hold VIEWER or EDITOR, which is
- // the whole reason the policy is readable by anyone who can read the
- // saved query.
- <dl className="flex flex-col gap-y-1 text-sm">
- {GRANTABLE_LEVELS.filter((candidate) =>
- policy.bindings.some(
- (binding) =>
- binding.level === candidate && binding.members.length > 0
- )
- ).map((candidate) => (
- <div key={candidate} className="flex gap-x-2">
- <dt className="shrink-0 font-medium">{levelLabel(candidate)}</dt>
- <dd className="text-control-light">
- {policy.bindings
- .filter((binding) => binding.level === candidate)
- .flatMap((binding) => binding.members)
- .join(", ")}
- </dd>
+ {/* The commit controls exist only while an add is in progress —
+ the resting popover is just the field and the list. */}
+ {pending.length > 0 && (
+ <div className="flex justify-end gap-x-2">
+ <LevelSelect
+ value={inviteLevel}
+ onChange={setInviteLevel}
+ disabled={saving}
+ className="min-w-24"
+ />
+ <Button
+ type="button"
+ data-testid="grant-add"
+ disabled={saving}
+ onClick={() => void handleAdd()}
+ >
+ {t("common.add")}
+ </Button>
</div>
- ))}
- </dl>
+ )}
+ </div>
)}
- {canManage && policy.bindings.length === 0 && (
- <p className="text-xs text-control-light">
- {t("sql-editor.saved-query-share.private-hint")}
- </p>
+ {(creatorMember || grantRows.length > 0) && (
+ <>
+ {/* Caption, not a heading: the list states who holds access; the
+ field above is where the action lives. */}
+ <p
+ id="saved-query-grantee-caption"
+ className="text-xs text-control-light"
+ >
+ {t("sql-editor.saved-query-share.people-with-access")}
+ </p>
+ <ul
+ aria-labelledby="saved-query-grantee-caption"
+ className="flex flex-col gap-y-1 max-h-64 overflow-y-auto"
+ >
+ {creatorMember && (
+ <li
+ data-testid="grant-owner-row"
+ className="flex items-center justify-between gap-x-2"
+ >
+ <GranteeCell
+ member={creatorMember}
+ badge={
+ currentUserEmail &&
+ creatorMember ===
+ getUserEmailInBinding(currentUserEmail) ? (
+ <Badge className="text-xs">{t("common.you")}</Badge>
+ ) : undefined
+ }
+ />
+ <span className="text-sm text-control-light shrink-0">
+ {t("sql-editor.saved-query-share.owner")}
+ </span>
+ </li>
+ )}
+ {grantRows.map(({ member, level }) => (
+ <li
+ key={member}
+ data-testid="grant-row"
+ data-member={member}
+ className="flex items-center justify-between gap-x-2"
+ >
+ <GranteeCell member={member} />
+ {canManage ? (
+ <div className="flex items-center gap-x-2 shrink-0">
+ <LevelSelect
+ value={level}
+ onChange={(next) => changeLevel(member, next)}
+ disabled={saving}
+ size="sm"
+ className="min-w-24"
+ />
+ <Button
+ type="button"
+ appearance="secondary"
+ size="sm"
+ aria-label={t("common.remove")}
+ disabled={saving}
+ className="text-control-light hover:text-error"
+ onClick={() => void removeMember(member)}
+ >
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ ) : (
+ <span className="text-sm text-control-light shrink-0">
+ {levelLabel(t, level)}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </>
)}
+
+ {grantRows.length === 0 &&
+ (canManage ? (
+ <p className="text-xs text-control-light">
+ {t("sql-editor.saved-query-share.private-hint")}
+ </p>
+ ) : (
+ // With an Owner row on screen, "not shared" would contradict it;
+ // the single-row list already says everything.
+ !creatorMember && (
+ <p className="text-xs text-control-light">
+ {t("sql-editor.saved-query-share.not-shared")}
+ </p>
+ )
+ ))}
</section>
);
}
+
+/** Same member→level assignments, ignoring row order. */
+const sameGrants = (a: Grant[], b: Grant[]) => {
+ if (a.length !== b.length) return false;
+ const levels = new Map(a.map((grant) => [grant.member, grant.level]));
+ return b.every((grant) => levels.get(grant.member) === grant.level);
+};
+
+function LevelSelect({
+ value,
+ onChange,
+ disabled,
+ size = "md",
+ className,
+}: {
+ readonly value: SavedQueryBinding_Level;
+ readonly onChange: (level: SavedQueryBinding_Level) => void;
+ readonly disabled?: boolean;
+ readonly size?: "sm" | "md";
+ readonly className?: string;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Select
+ value={value}
+ onValueChange={(next: SavedQueryBinding_Level | null) => {
+ if (next !== null) onChange(next);
+ }}
+ disabled={disabled}
+ >
+ <SelectTrigger size={size} className={className}>
+ <SelectValue>
+ {(current: SavedQueryBinding_Level) => levelLabel(t, current)}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {GRANTABLE_LEVELS.map((candidate) => (
+ <SelectItem key={candidate} value={candidate}>
+ {levelLabel(t, candidate)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+/**
+ * Level → label, keeping the locale keys as literal arguments so the locale
+ * checker can trace them statically.
+ */
+const levelLabel = (t: TFunction, level: SavedQueryBinding_Level) =>
+ level === SavedQueryBinding_Level.EDITOR
+ ? t("sql-editor.saved-query-share.editor")
+ : t("sql-editor.saved-query-share.viewer");
+
+function GranteeCell({
+ member,
+ badge,
+}: {
+ readonly member: string;
+ readonly badge?: ReactNode;
+}) {
+ const isGroup = member.startsWith(groupBindingPrefix);
+ // Subscribe to the store slice behind this row so it repaints when the
+ // prefetch lands; the display projection itself is the shared members
+ // surface, which handles every principal kind.
+ useAppStore((s) =>
+ isGroup ? s.getGroupByIdentifier(member) : s.getUserByIdentifier(member)
+ );
+ const memberBinding = getMemberBinding(member, "");
+ if (!memberBinding) return null;
+
+ const email = memberBinding.group
+ ? extractGroupEmail(memberBinding.group.name)
+ : (memberBinding.user?.email ?? "");
+ const title = memberBinding.title || email;
+ return (
+ <UserCell
+ size="sm"
+ className="min-w-0"
+ title={title}
+ subtitle={email && title !== email ? email : undefined}
+ avatar={
+ isGroup ? (
+ <div className="size-7 rounded-full bg-control-bg text-control-light flex items-center justify-center shrink-0">
+ <Users className="size-4" />
+ </div>
+ ) : undefined
+ }
+ hoverEmail={member.startsWith(userBindingPrefix) ? email : undefined}
+ badges={badge}
+ />
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
index 143a67a005..0944bf63c6 100644
--- a/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
+++ b/frontend/src/modules/sql-editor/components/SharePopoverBody.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { router } from "@/app/router";
import { SQL_EDITOR_SAVED_QUERY_MODULE } from "@/app/router/handles";
import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
import { writeTextToClipboard } from "@/lib/clipboard";
import { useAppStore } from "@/stores/app";
import type { SavedQuery } from "@/types/proto-es/v1/saved_query_service_pb";
@@ -63,24 +64,38 @@ export function SharePopoverBody({ savedQuery }: Props) {
};
return (
- <div className="w-96 p-2 flex flex-col gap-y-4">
- <section className="w-full flex flex-row justify-between items-center">
- <div className="pr-4">
- <h2 className="text-lg font-semibold">{t("common.share")}</h2>
- </div>
- </section>
+ <div className="w-96 flex flex-col gap-y-3">
+ {/* One compact header row: the action plus what it acts on. A popover
+ is not a dialog, so the 18px dialog-title role does not apply —
+ 14px medium, with the saved query's title carrying the context the
+ bare word "Share" lacks. */}
+ <div className="flex items-baseline gap-x-1.5 min-w-0">
+ <h2 className="text-sm font-medium shrink-0">{t("common.share")}</h2>
+ {savedQuery?.title && (
+ <span className="text-sm text-control-light truncate">
+ {t("sql-editor.saved-query-share.share-title", {
+ title: savedQuery.title,
+ })}
+ </span>
+ )}
+ </div>
{savedQuery && (
<SavedQueryGrantEditor savedQuery={savedQuery} canManage={canManage} />
)}
+ {/* The grants above carry access; the link below carries location. The
+ separator makes that split structural instead of another heading —
+ and only exists when the grant editor above it does. */}
+ {savedQuery && <Separator />}
+
{/* Link input + copy button — single bordered container with rounded
inner corners. No group-level focus ring; only the input shows a
focus highlight. */}
<div className="flex items-center h-8 rounded-xs border border-control-border overflow-hidden">
{/* Link icon prefix (gray addon) */}
<div className="flex items-center justify-center h-full px-2 bg-control-bg text-control-light border-r border-control-border">
- <Link2 className="size-5" />
+ <Link2 className="size-4" />
</div>
{/* URL input — always read-only; the link itself is not editable. */}
<input
diff --git a/frontend/src/stores/app/user.ts b/frontend/src/stores/app/user.ts
index 5b1131c499..c2e8ade5d4 100644
--- a/frontend/src/stores/app/user.ts
+++ b/frontend/src/stores/app/user.ts
@@ -164,12 +164,16 @@ export const createUserSlice: AppSliceCreator<UserSlice> = (set, get) => {
getUserByIdentifier: (identifier) => {
if (!identifier) return undefined;
const id = extractUserEmail(identifier);
+ // Direct map hit first: `user.name` is `users/{email}`, so the common
+ // email-shaped lookup needs no scan over the cache.
+ const direct = get().usersByName[`${userNamePrefix}${id}`];
+ if (direct) return direct;
if (Number.isNaN(Number(id))) {
return Object.values(get().usersByName).find(
(user) => user.email === id
);
}
- return get().usersByName[`${userNamePrefix}${id}`];
+ return undefined;
},
createUser: async (user) => {