Skip to content

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

feat(review): edit the AI review policy on the SQL review pages (#21606)

h3n4lc320ae0bccf9
diff --git a/docs/agents/frontend-ux.md b/docs/agents/frontend-ux.md
index 0916a3490e..6f17fff352 100644
--- a/docs/agents/frontend-ux.md
+++ b/docs/agents/frontend-ux.md
@@ -190,6 +190,11 @@ behavior:
- A section has 24px vertical padding and 16px internal rhythm.
- On large screens, a section header uses 25% of the section width and content
uses the remainder. On smaller screens, they stack with 16px separation.
+- A page that reads as one column uses `FormSection layout="single-column"`: the
+ same section title, the header above the content at every width, and the
+ content's children 16px apart. `layout="stacked"` is the dense variant for
+ sections inside a dense form. `FormSection description` renders a short
+ introduction under the title in the header.
- `FormLabel` MUST reference its control with `htmlFor`.
- Validation MUST be adjacent to the affected field. Do not rely only on a
toast or a disabled button to explain invalid input.
diff --git a/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx b/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx
new file mode 100644
index 0000000000..2141cfea9c
--- /dev/null
+++ b/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx
@@ -0,0 +1,474 @@
+import { create } from "@bufbuild/protobuf";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type Policy,
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ ReviewAIPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+
+const PARENT = "projects/p";
+const POLICY_NAME = `${PARENT}/policies/review_ai`;
+const EDITOR = { name: "sql-review.ai-review.policy.self" };
+
+const mocks = vi.hoisted(() => ({
+ permissions: {} as Record<string, boolean>,
+ // Policy names whose read fails: the store then caches nothing for them.
+ unreadable: new Set<string>(),
+ fetchPolicy: vi.fn(),
+ upsertPolicy: vi.fn(),
+ deletePolicy: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) =>
+ params ? `${key} ${JSON.stringify(params)}` : key,
+ }),
+}));
+
+// Mirrors the real store: a fetch of a missing policy caches one with no
+// payload and resolves to null, a failed read resolves to undefined and
+// leaves the cache as it was, an update keeps the stored enforce flag, a
+// create is enforced, and a delete drops the cached entry.
+vi.mock("@/stores/app", async () => {
+ const { create: createStore } = await import("zustand");
+ const { create: createMessage } = await import("@bufbuild/protobuf");
+ const { PolicySchema: Schema, PolicyType: Type } = await import(
+ "@/types/proto-es/v1/org_policy_service_pb"
+ );
+ type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
+ type Find = { parentPath: string; policyType: number; refresh?: boolean };
+ const nameOf = (parentPath: string, policyType: number) =>
+ `${parentPath}/policies/${Type[policyType].toLowerCase()}`;
+ const useAppStore = createStore<{
+ policies: Record<string, StorePolicy>;
+ getPolicyByParentAndType: (find: Find) => StorePolicy | undefined;
+ fetchPolicyByParentAndType: (
+ find: Find
+ ) => Promise<StorePolicy | null | undefined>;
+ upsertPolicy: (params: {
+ parentPath: string;
+ policy: Partial<StorePolicy>;
+ }) => Promise<StorePolicy>;
+ deletePolicy: (name: string) => Promise<void>;
+ }>()((set, get) => ({
+ policies: {},
+ getPolicyByParentAndType: (find) =>
+ get().policies[nameOf(find.parentPath, find.policyType)],
+ fetchPolicyByParentAndType: async (find) => {
+ await mocks.fetchPolicy(find);
+ const name = nameOf(find.parentPath, find.policyType);
+ if (mocks.unreadable.has(name)) return undefined;
+ if (!get().policies[name]) {
+ set((state) => ({
+ policies: {
+ ...state.policies,
+ [name]: createMessage(Schema, { name }),
+ },
+ }));
+ return null;
+ }
+ return get().policies[name];
+ },
+ upsertPolicy: async (params) => {
+ await mocks.upsertPolicy(params);
+ const name = nameOf(params.parentPath, params.policy.type!);
+ const existing = get().policies[name];
+ const saved = {
+ ...params.policy,
+ name,
+ enforce: existing?.policy.case ? existing.enforce : true,
+ } as StorePolicy;
+ set((state) => ({ policies: { ...state.policies, [name]: saved } }));
+ return saved;
+ },
+ deletePolicy: async (name) => {
+ await mocks.deletePolicy(name);
+ set((state) => {
+ const { [name]: _removed, ...policies } = state.policies;
+ return { policies };
+ });
+ },
+ }));
+ return { useAppStore };
+});
+
+const { useAppStore } = await import("@/stores/app");
+const seedPolicies = (policies: Record<string, Policy>) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { policies: Record<string, Policy> }) => void;
+ }
+ ).setState({ policies });
+
+const { MAX_REVIEW_AI_POLICY_BYTES, ReviewAIPolicyField, useReviewAIPolicyDraft } =
+ await import("./ReviewAIPolicyField");
+
+const reviewAIPolicy = (parent: string, content: string, enforce = true) =>
+ create(PolicySchema, {
+ name: `${parent}/policies/review_ai`,
+ type: PolicyType.REVIEW_AI,
+ enforce,
+ policy: {
+ case: "reviewAiPolicy",
+ value: create(ReviewAIPolicySchema, { content }),
+ },
+ });
+
+function Harness({ parentPath = PARENT }: { parentPath?: string }) {
+ const policy = useReviewAIPolicyDraft({
+ parentPath,
+ resourceType: PolicyResourceType.PROJECT,
+ can: (permission) => mocks.permissions[permission] ?? true,
+ });
+ const [saved, setSaved] = useState<boolean>();
+ return (
+ <>
+ <ReviewAIPolicyField policy={policy} placeholder="the example rules" />
+ <output>{policy.isDirty ? "dirty" : "clean"}</output>
+ <output>{`saved: ${saved}`}</output>
+ <button type="button" onClick={() => void policy.save().then(setSaved)}>
+ save
+ </button>
+ <button type="button" onClick={policy.revert}>
+ revert
+ </button>
+ </>
+ );
+}
+
+const editor = () => screen.findByRole("textbox", EDITOR);
+
+const type = async (content: string) =>
+ fireEvent.change(await editor(), { target: { value: content } });
+
+const save = () =>
+ act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "save" }));
+ });
+
+describe("ReviewAIPolicyField", () => {
+ beforeEach(() => {
+ mocks.permissions = {};
+ mocks.unreadable.clear();
+ mocks.fetchPolicy.mockReset();
+ mocks.upsertPolicy.mockReset();
+ mocks.deletePolicy.mockReset();
+ seedPolicies({});
+ });
+
+ test("loads the stored policy into the editor", async () => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "No DROP on prod.") });
+ render(<Harness />);
+
+ const textbox = await editor();
+ expect(textbox).toHaveValue("No DROP on prod.");
+ expect(mocks.fetchPolicy).toHaveBeenCalledWith({
+ parentPath: PARENT,
+ policyType: PolicyType.REVIEW_AI,
+ refresh: false,
+ });
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+
+ test("a missing policy starts empty with example text, and a save creates it enforced", async () => {
+ render(<Harness />);
+
+ const textbox = await editor();
+ expect(textbox).toHaveValue("");
+ expect(textbox).toHaveAttribute("placeholder", "the example rules");
+ await type("Flag changes to the payments table.");
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ await save();
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledOnce();
+ const { parentPath, policy } = mocks.upsertPolicy.mock.calls[0][0];
+ expect(parentPath).toBe(PARENT);
+ expect(policy.type).toBe(PolicyType.REVIEW_AI);
+ expect(policy.resourceType).toBe(PolicyResourceType.PROJECT);
+ expect(policy.enforce).toBe(true);
+ expect(policy.policy.case).toBe("reviewAiPolicy");
+ expect(policy.policy.value.content).toBe(
+ "Flag changes to the payments table."
+ );
+ expect(screen.getByText("saved: true")).toBeInTheDocument();
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ expect(await editor()).toHaveValue("Flag changes to the payments table.");
+ });
+
+ test("reverting drops the edit", async () => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("Edited.");
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "revert" }));
+
+ expect(await editor()).toHaveValue("Stored.");
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+
+ test("typing the stored text back is not a change", async () => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("Edited.");
+ await type("Stored.");
+
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+
+ test("a failed save keeps the edit", async () => {
+ mocks.upsertPolicy.mockRejectedValueOnce(new Error("denied"));
+ render(<Harness />);
+
+ await type("Flag changes to the payments table.");
+ await save();
+
+ expect(await editor()).toHaveValue("Flag changes to the payments table.");
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ expect(screen.getByText("saved: false")).toBeInTheDocument();
+ });
+
+ test("text over the size limit, counted in UTF-8 bytes, shows an error and does not save", async () => {
+ render(<Harness />);
+
+ // Under the limit in characters, over it in bytes.
+ const tooLarge = "表".repeat(Math.floor(MAX_REVIEW_AI_POLICY_BYTES / 3) + 1);
+ expect(tooLarge.length).toBeLessThan(MAX_REVIEW_AI_POLICY_BYTES);
+ await type(tooLarge);
+
+ const textbox = await editor();
+ expect(textbox).toHaveAttribute("aria-invalid", "true");
+ // Exact byte counts, so a text one byte over never reads as the limit.
+ const error = screen.getByRole("alert");
+ expect(error).toHaveTextContent("sql-review.ai-review.policy.too-large");
+ expect(error).toHaveTextContent(
+ JSON.stringify({
+ // Three UTF-8 bytes a character.
+ size: (3 * tooLarge.length).toLocaleString(),
+ limit: MAX_REVIEW_AI_POLICY_BYTES.toLocaleString(),
+ })
+ );
+ expect(textbox).toHaveAccessibleDescription(
+ /sql-review\.ai-review\.policy\.too-large/
+ );
+ await save();
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(screen.getByText("saved: false")).toBeInTheDocument();
+
+ await type("a".repeat(MAX_REVIEW_AI_POLICY_BYTES));
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(await editor()).toHaveAttribute("aria-invalid", "false");
+ });
+
+ test("clearing the text deletes the policy", async () => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type(" \n ");
+ expect(screen.getByText("dirty")).toBeInTheDocument();
+ await save();
+
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(mocks.deletePolicy).toHaveBeenCalledWith(POLICY_NAME);
+ expect(screen.getByText("saved: true")).toBeInTheDocument();
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ expect(await editor()).toHaveValue("");
+ });
+
+ test("clearing the text needs bb.policies.delete", async () => {
+ mocks.permissions = { "bb.policies.delete": false };
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("");
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "sql-review.ai-review.policy.cannot-clear"
+ );
+ await save();
+ expect(mocks.deletePolicy).not.toHaveBeenCalled();
+ expect(screen.getByText("saved: false")).toBeInTheDocument();
+ });
+
+ test("blank text without a policy is not a change", async () => {
+ render(<Harness />);
+
+ await type(" ");
+
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+
+ // The server trims with Go's strings.TrimSpace, which differs from
+ // JavaScript's trim on these two code points.
+ test.each([
+ ["U+0085, which the server trims, deletes", 0x85, "delete"],
+ ["U+FEFF, which the server keeps, saves", 0xfeff, "upsert"],
+ ])("text of only %s", async (_name, codePoint, expected) => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type(String.fromCodePoint(codePoint));
+ await save();
+
+ expect(mocks.deletePolicy).toHaveBeenCalledTimes(
+ expected === "delete" ? 1 : 0
+ );
+ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(
+ expected === "upsert" ? 1 : 0
+ );
+ });
+
+ test("shows that the policy is loading until it has been read", async () => {
+ let finishRead = () => {};
+ mocks.fetchPolicy.mockReturnValueOnce(
+ new Promise<void>((resolve) => {
+ finishRead = resolve;
+ })
+ );
+ render(<Harness />);
+
+ expect(screen.getByText("common.loading")).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ await act(async () => finishRead());
+
+ expect(await editor()).toBeInTheDocument();
+ expect(screen.queryByText("common.loading")).not.toBeInTheDocument();
+ });
+
+ test("shows the policy as text without bb.policies.update or bb.policies.delete", async () => {
+ mocks.permissions = {
+ "bb.policies.update": false,
+ "bb.policies.delete": false,
+ };
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "No DROP on prod.") });
+ render(<Harness />);
+
+ expect(await screen.findByText("No DROP on prod.")).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ test("a role with bb.policies.delete but not bb.policies.update can clear the policy", async () => {
+ mocks.permissions = { "bb.policies.update": false };
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("");
+
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ await save();
+ expect(mocks.deletePolicy).toHaveBeenCalledWith(POLICY_NAME);
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(screen.getByText("saved: true")).toBeInTheDocument();
+ });
+
+ test("a role with bb.policies.delete but not bb.policies.update cannot change the text", async () => {
+ mocks.permissions = { "bb.policies.update": false };
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("Edited.");
+
+ expect(await editor()).toHaveAttribute("aria-invalid", "true");
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "sql-review.ai-review.policy.remove-only"
+ );
+ await save();
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(mocks.deletePolicy).not.toHaveBeenCalled();
+ expect(screen.getByText("saved: false")).toBeInTheDocument();
+ });
+
+ test.each([
+ ["bb.policies.update alone", { "bb.policies.delete": false }],
+ ["bb.policies.update and bb.policies.delete", {}],
+ ])("a role with %s changes the text", async (_name, permissions) => {
+ mocks.permissions = permissions;
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ await type("Edited.");
+
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ await save();
+ expect(mocks.upsertPolicy).toHaveBeenCalledOnce();
+ expect(mocks.upsertPolicy.mock.calls[0][0].policy.policy.value.content).toBe(
+ "Edited."
+ );
+ });
+
+ test("shows that there is no policy without bb.policies.create", async () => {
+ mocks.permissions = { "bb.policies.create": false };
+ render(<Harness />);
+
+ expect(
+ await screen.findByText("sql-review.ai-review.policy.none")
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ test("editing an existing policy does not need bb.policies.create", async () => {
+ mocks.permissions = { "bb.policies.create": false };
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.") });
+ render(<Harness />);
+
+ expect(await editor()).toBeEnabled();
+ });
+
+ test("says when the policy is paused, and an edit keeps it paused", async () => {
+ seedPolicies({ [POLICY_NAME]: reviewAIPolicy(PARENT, "Stored.", false) });
+ render(<Harness />);
+
+ await type("Edited.");
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "sql-review.ai-review.policy.paused"
+ );
+ await save();
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "sql-review.ai-review.policy.paused"
+ );
+ });
+
+ test("a failed read shows an error instead of the editor, and retry reads again", async () => {
+ mocks.unreadable.add(POLICY_NAME);
+ render(<Harness />);
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "sql-review.ai-review.policy.load-failed"
+ );
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+
+ mocks.unreadable.clear();
+ fireEvent.click(
+ screen.getByRole("button", { name: "sql-review.standard-rules.retry" })
+ );
+
+ expect(await editor()).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(mocks.fetchPolicy).toHaveBeenLastCalledWith({
+ parentPath: PARENT,
+ policyType: PolicyType.REVIEW_AI,
+ refresh: true,
+ });
+ });
+
+ test("moving to another project drops the edit", async () => {
+ seedPolicies({
+ [POLICY_NAME]: reviewAIPolicy(PARENT, "First."),
+ "projects/q/policies/review_ai": reviewAIPolicy("projects/q", "Second."),
+ });
+ const { rerender } = render(<Harness />);
+ await type("Edited.");
+
+ rerender(<Harness parentPath="projects/q" />);
+
+ expect(await editor()).toHaveValue("Second.");
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/sql-review/ReviewAIPolicyField.tsx b/frontend/src/components/sql-review/ReviewAIPolicyField.tsx
new file mode 100644
index 0000000000..2558afcfee
--- /dev/null
+++ b/frontend/src/components/sql-review/ReviewAIPolicyField.tsx
@@ -0,0 +1,256 @@
+import { create } from "@bufbuild/protobuf";
+import { useEffect, useId, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Alert } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { FormControlGroup, FormError, FormField } from "@/components/ui/form";
+import { Textarea } from "@/components/ui/textarea";
+import { useAppStore } from "@/stores/app";
+import type { Permission } from "@/types";
+import {
+ PolicyResourceType,
+ PolicyType,
+ ReviewAIPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+
+// The server's limit: the whole policy goes into every review prompt.
+export const MAX_REVIEW_AI_POLICY_BYTES = 64 * 1024;
+
+// The server rejects text that Go's strings.TrimSpace empties, which trims the
+// Unicode White_Space set. JavaScript's trim differs: it keeps U+0085 and
+// removes U+FEFF.
+const isBlank = (content: string) => /^\p{White_Space}*$/u.test(content);
+
+// The server measures the text in UTF-8 bytes, not characters.
+const utf8Bytes = (content: string) => new TextEncoder().encode(content).length;
+
+export interface ReviewAIPolicyDraft {
+ // False until the policy has been read.
+ loaded: boolean;
+ readFailed: boolean;
+ reload: () => void;
+ // The policy text, or the unsaved edit; empty when there is no policy.
+ content: string;
+ setContent: (content: string) => void;
+ // A policy paused through the API is kept but not read by the AI review.
+ paused: boolean;
+ canEdit: boolean;
+ error: "too-large" | "cannot-clear" | "remove-only" | undefined;
+ size: number;
+ isDirty: boolean;
+ saving: boolean;
+ revert: () => void;
+ // Resolves whether the policy saved. The page reports the update; a failure
+ // is reported by the response middleware and keeps the draft.
+ save: () => Promise<boolean>;
+}
+
+// The page owns the draft so the policy saves from the page's one sticky
+// footer. Blank text saves as no policy, since the server rejects a blank one.
+export function useReviewAIPolicyDraft({
+ parentPath,
+ resourceType,
+ can,
+ enabled = true,
+}: {
+ // The workspace or project the policy belongs to.
+ parentPath: string;
+ resourceType: PolicyResourceType;
+ can: (permission: Permission) => boolean;
+ enabled?: boolean;
+}): ReviewAIPolicyDraft {
+ const policy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath,
+ policyType: PolicyType.REVIEW_AI,
+ })
+ );
+ const [draft, setDraft] = useState<string>();
+ const [attempt, setAttempt] = useState(0);
+ const [loaded, setLoaded] = useState(false);
+ const [readFailed, setReadFailed] = useState(false);
+ const [saving, setSaving] = useState(false);
+ useEffect(() => {
+ if (!enabled || !parentPath) return;
+ let active = true;
+ // The route component is reused when moving to another project.
+ setDraft(undefined);
+ setLoaded(false);
+ setReadFailed(false);
+ void useAppStore
+ .getState()
+ .fetchPolicyByParentAndType({
+ parentPath,
+ policyType: PolicyType.REVIEW_AI,
+ refresh: attempt > 0,
+ })
+ .then((result) => {
+ if (!active) return;
+ // A read that failed may leave an earlier policy in the cache, so the
+ // result decides, not the cache.
+ if (result === undefined) {
+ setReadFailed(true);
+ return;
+ }
+ setLoaded(true);
+ });
+ return () => {
+ active = false;
+ };
+ }, [enabled, parentPath, attempt]);
+
+ // A missing policy is cached as a stand-in without a payload.
+ const stored = policy?.policy.case === "reviewAiPolicy" ? policy : undefined;
+ const storedContent =
+ policy?.policy.case === "reviewAiPolicy" ? policy.policy.value.content : "";
+ const content = draft ?? storedContent;
+ const isDirty =
+ draft !== undefined &&
+ (isBlank(draft) ? stored !== undefined : draft !== storedContent);
+ const clearing = isDirty && isBlank(content);
+ const size = utf8Bytes(content);
+ // Clearing an existing policy deletes it and any other edit updates it, so
+ // a role with only one of the two may make only that change.
+ const error =
+ isDirty && stored && !clearing && !can("bb.policies.update")
+ ? "remove-only"
+ : isDirty && size > MAX_REVIEW_AI_POLICY_BYTES
+ ? "too-large"
+ : clearing && !can("bb.policies.delete")
+ ? "cannot-clear"
+ : undefined;
+
+ const save = async () => {
+ if (!isDirty) return true;
+ if (error) return false;
+ setSaving(true);
+ try {
+ const store = useAppStore.getState();
+ if (clearing && stored) {
+ await store.deletePolicy(stored.name);
+ } else {
+ // The update mask names only the text, so a paused policy stays
+ // paused; a new policy is created enforced.
+ await store.upsertPolicy({
+ parentPath,
+ policy: {
+ type: PolicyType.REVIEW_AI,
+ resourceType,
+ enforce: true,
+ policy: {
+ case: "reviewAiPolicy",
+ value: create(ReviewAIPolicySchema, { content }),
+ },
+ },
+ });
+ }
+ setDraft(undefined);
+ return true;
+ } catch {
+ return false;
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return {
+ loaded,
+ readFailed,
+ reload: () => setAttempt((n) => n + 1),
+ content,
+ setContent: setDraft,
+ paused: stored !== undefined && !stored.enforce,
+ canEdit: stored
+ ? can("bb.policies.update") || can("bb.policies.delete")
+ : can("bb.policies.create"),
+ error,
+ size,
+ isDirty,
+ saving,
+ revert: () => setDraft(undefined),
+ save,
+ };
+}
+
+export function ReviewAIPolicyField({
+ policy,
+ placeholder,
+}: {
+ policy: ReviewAIPolicyDraft;
+ // Example rules for this level, shown while the field is empty.
+ placeholder: string;
+}) {
+ const { t } = useTranslation();
+ const id = useId();
+ const titleId = `${id}-title`;
+ const errorId = `${id}-error`;
+
+ if (policy.readFailed) {
+ return (
+ <Alert variant="error">
+ <div className="flex flex-col items-start gap-y-3">
+ {t("sql-review.ai-review.policy.load-failed")}
+ <Button appearance="outline" size="sm" onClick={policy.reload}>
+ {t("sql-review.standard-rules.retry")}
+ </Button>
+ </div>
+ </Alert>
+ );
+ }
+
+ return (
+ <FormField
+ title={<span id={titleId}>{t("sql-review.ai-review.policy.self")}</span>}
+ >
+ <FormControlGroup>
+ {policy.loaded && policy.paused && (
+ <Alert
+ variant="warning"
+ appearance="caption"
+ description={t("sql-review.ai-review.policy.paused")}
+ />
+ )}
+ {!policy.loaded ? (
+ <p className="text-sm text-control-light">{t("common.loading")}</p>
+ ) : policy.canEdit ? (
+ <Textarea
+ aria-labelledby={titleId}
+ aria-describedby={policy.error ? errorId : undefined}
+ aria-invalid={policy.error !== undefined}
+ rows={8}
+ placeholder={placeholder}
+ value={policy.content}
+ onChange={(event) => policy.setContent(event.target.value)}
+ disabled={policy.saving}
+ />
+ ) : policy.content ? (
+ <p className="whitespace-pre-wrap break-words rounded-sm border border-block-border px-3 py-2 text-sm text-main">
+ {policy.content}
+ </p>
+ ) : (
+ <p className="text-sm text-control-light">
+ {t("sql-review.ai-review.policy.none")}
+ </p>
+ )}
+ </FormControlGroup>
+ {policy.error === "too-large" && (
+ <FormError id={errorId}>
+ {t("sql-review.ai-review.policy.too-large", {
+ size: policy.size.toLocaleString(),
+ limit: MAX_REVIEW_AI_POLICY_BYTES.toLocaleString(),
+ })}
+ </FormError>
+ )}
+ {policy.error === "cannot-clear" && (
+ <FormError id={errorId}>
+ {t("sql-review.ai-review.policy.cannot-clear")}
+ </FormError>
+ )}
+ {policy.error === "remove-only" && (
+ <FormError id={errorId}>
+ {t("sql-review.ai-review.policy.remove-only")}
+ </FormError>
+ )}
+ </FormField>
+ );
+}
diff --git a/frontend/src/components/ui/form.test.tsx b/frontend/src/components/ui/form.test.tsx
index 0251fa9942..2742c281de 100644
--- a/frontend/src/components/ui/form.test.tsx
+++ b/frontend/src/components/ui/form.test.tsx
@@ -14,13 +14,22 @@ import {
FormTitle,
} from "./form";
import {
+ denseFormContentStyle,
+ denseFormHeaderStyle,
+ denseFormSectionStyle,
+ denseFormTitleStyle,
formControlGroupStyle,
formControlRowStyle,
formErrorStyle,
formFieldGroupStyle,
formFieldTitleStyle,
formLabelStyle,
+ formSectionDescriptionStyle,
formSectionStyle,
+ formSectionTitleStyle,
+ singleColumnFormContentStyle,
+ singleColumnFormHeaderStyle,
+ singleColumnFormSectionStyle,
} from "./styles.stylex";
(
@@ -223,6 +232,113 @@ describe("Form section layouts", () => {
unmount();
});
+
+ test("renders the description in the header, under the title", () => {
+ const { container, unmount } = renderIntoContainer(
+ createElement(
+ FormSection,
+ { title: "AI review", description: "Reviews the SQL of an issue." },
+ createElement("div", null, "Content")
+ )
+ );
+
+ const header = container.querySelector('[data-slot="form-section-header"]');
+ const description = container.querySelector(
+ '[data-slot="form-section-description"]'
+ );
+
+ expect(description?.parentElement).toBe(header);
+ expect(description?.previousElementSibling?.getAttribute("data-slot")).toBe(
+ "form-section-title"
+ );
+ expect(description?.textContent).toBe("Reviews the SQL of an issue.");
+ expect(description?.className).toContain(
+ stylex.props(formSectionDescriptionStyle()).className ?? ""
+ );
+
+ unmount();
+ });
+
+ test("renders no description slot without a description", () => {
+ const { container, unmount } = renderIntoContainer(
+ createElement(FormSection, { title: "General" }, "Content")
+ );
+
+ expect(
+ container.querySelector('[data-slot="form-section-description"]')
+ ).toBeNull();
+
+ unmount();
+ });
+
+ test("keeps the page section title and puts the header above the content in the single-column layout", () => {
+ const { container, unmount } = renderIntoContainer(
+ createElement(
+ FormSection,
+ { title: "Standard rules", layout: "single-column" },
+ createElement("div", null, "Content")
+ )
+ );
+
+ const section = container.querySelector('[data-slot="form-section"]');
+ const header = container.querySelector('[data-slot="form-section-header"]');
+ const title = container.querySelector('[data-slot="form-section-title"]');
+ const content = container.querySelector(
+ '[data-slot="form-section-content"]'
+ );
+
+ expect(section?.className).toContain(
+ stylex.props(singleColumnFormSectionStyle()).className ?? ""
+ );
+ expect(section?.className).not.toContain(
+ stylex.props(formSectionStyle()).className ?? ""
+ );
+ expect(header?.className).toContain(
+ stylex.props(singleColumnFormHeaderStyle()).className ?? ""
+ );
+ expect(title?.className).toContain(
+ stylex.props(formSectionTitleStyle()).className ?? ""
+ );
+ expect(content?.className).toContain(
+ stylex.props(singleColumnFormContentStyle()).className ?? ""
+ );
+ expect(header?.nextElementSibling).toBe(content);
+
+ unmount();
+ });
+
+ test("keeps the dense styles in the stacked layout, with a description", () => {
+ const { container, unmount } = renderIntoContainer(
+ createElement(
+ FormSection,
+ {
+ title: "Connection",
+ description: "Where Bytebase reaches the instance.",
+ layout: "stacked",
+ },
+ createElement("div", null, "Content")
+ )
+ );
+
+ const slot = (name: string) =>
+ container.querySelector(`[data-slot="form-section${name}"]`);
+
+ expect(slot("")?.className).toContain(
+ stylex.props(denseFormSectionStyle()).className ?? ""
+ );
+ expect(slot("-header")?.className).toContain(
+ stylex.props(denseFormHeaderStyle()).className ?? ""
+ );
+ expect(slot("-title")?.className).toContain(
+ stylex.props(denseFormTitleStyle()).className ?? ""
+ );
+ expect(slot("-content")?.className).toContain(
+ stylex.props(denseFormContentStyle()).className ?? ""
+ );
+ expect(slot("-description")?.parentElement).toBe(slot("-header"));
+
+ unmount();
+ });
});
describe("responsive form fields", () => {
diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsx
index bea5d93a8f..986b93012a 100644
--- a/frontend/src/components/ui/form.tsx
+++ b/frontend/src/components/ui/form.tsx
@@ -28,9 +28,13 @@ import {
formFieldTitleStyle,
formLabelStyle,
formSectionContentStyle,
+ formSectionDescriptionStyle,
formSectionHeaderStyle,
formSectionStyle,
formSectionTitleStyle,
+ singleColumnFormContentStyle,
+ singleColumnFormHeaderStyle,
+ singleColumnFormSectionStyle,
} from "./styles.stylex";
type FormLayout = "vertical" | "horizontal";
@@ -300,16 +304,46 @@ function FormFieldGroup({
interface FormSectionProps extends Omit<ComponentProps<"section">, "title"> {
title: ReactNode;
- layout?: "default" | "stacked";
+ description?: ReactNode;
+ /**
+ * - `default`: on large screens the header takes a 25% column beside the
+ * content; on smaller screens it stacks above.
+ * - `single-column`: the header stays above the content at every width,
+ * with the same page section title, for a page that reads as one column.
+ * - `stacked`: the dense variant with a 16px title and 16px padding, for
+ * sections inside a dense form such as the instance form.
+ */
+ layout?: "default" | "single-column" | "stacked";
}
+const formSectionLayoutStyles = {
+ default: {
+ section: formSectionStyle,
+ header: formSectionHeaderStyle,
+ title: formSectionTitleStyle,
+ content: formSectionContentStyle,
+ },
+ "single-column": {
+ section: singleColumnFormSectionStyle,
+ header: singleColumnFormHeaderStyle,
+ title: formSectionTitleStyle,
+ content: singleColumnFormContentStyle,
+ },
+ stacked: {
+ section: denseFormSectionStyle,
+ header: denseFormHeaderStyle,
+ title: denseFormTitleStyle,
+ content: denseFormContentStyle,
+ },
+};
+
/**
* Wraps a settings page section with a consistent section heading and content
* column.
*
* @example
* ```tsx
- * <FormSection id="general" title={sectionTitle}>
+ * <FormSection id="general" title={sectionTitle} description={summary}>
* <FormFieldGroup>
* <FormField title={fieldTitle}>
* <Input value={name} onChange={handleNameChange} />
@@ -324,21 +358,16 @@ function FormSection({
ref,
style,
title,
+ description,
layout = "default",
...props
}: FormSectionProps) {
- const sectionStylexProps = stylex.props(
- layout === "stacked" ? denseFormSectionStyle() : formSectionStyle()
- );
- const headerStylexProps = stylex.props(
- layout === "stacked" ? denseFormHeaderStyle() : formSectionHeaderStyle()
- );
- const titleStylexProps = stylex.props(
- layout === "stacked" ? denseFormTitleStyle() : formSectionTitleStyle()
- );
- const contentStylexProps = stylex.props(
- layout === "stacked" ? denseFormContentStyle() : formSectionContentStyle()
- );
+ const styles = formSectionLayoutStyles[layout];
+ const sectionStylexProps = stylex.props(styles.section());
+ const headerStylexProps = stylex.props(styles.header());
+ const titleStylexProps = stylex.props(styles.title());
+ const descriptionStylexProps = stylex.props(formSectionDescriptionStyle());
+ const contentStylexProps = stylex.props(styles.content());
return (
<section
@@ -362,6 +391,15 @@ function FormSection({
>
{title}
</div>
+ {description !== undefined && (
+ <div
+ data-slot="form-section-description"
+ className={descriptionStylexProps.className}
+ style={descriptionStylexProps.style}
+ >
+ {description}
+ </div>
+ )}
</div>
<div
data-slot="form-section-content"
diff --git a/frontend/src/components/ui/styles.stylex.ts b/frontend/src/components/ui/styles.stylex.ts
index 7bc80dd78a..6fd5723426 100644
--- a/frontend/src/components/ui/styles.stylex.ts
+++ b/frontend/src/components/ui/styles.stylex.ts
@@ -286,6 +286,9 @@ const formStyles = stylex.create({
},
},
sectionHeader: {
+ display: "flex",
+ flexDirection: "column",
+ rowGap: 8,
textAlign: "left",
"@media (min-width: 1024px)": {
width: "25%",
@@ -297,6 +300,29 @@ const formStyles = stylex.create({
fontWeight: 700,
lineHeight: "32px",
},
+ sectionDescription: {
+ color: "rgb(var(--color-control-light))",
+ fontSize: 14,
+ lineHeight: "20px",
+ },
+ singleColumnSection: {
+ display: "flex",
+ flexDirection: "column",
+ paddingBlock: 24,
+ rowGap: 16,
+ },
+ singleColumnHeader: {
+ display: "flex",
+ flexDirection: "column",
+ rowGap: 8,
+ width: "100%",
+ },
+ singleColumnContent: {
+ display: "flex",
+ flexDirection: "column",
+ minWidth: 0,
+ rowGap: 16,
+ },
});
export function formFieldStyle() {
@@ -364,6 +390,22 @@ export function formSectionContentStyle() {
return formStyles.sectionContent;
}
+export function formSectionDescriptionStyle() {
+ return formStyles.sectionDescription;
+}
+
+export function singleColumnFormSectionStyle() {
+ return formStyles.singleColumnSection;
+}
+
+export function singleColumnFormHeaderStyle() {
+ return formStyles.singleColumnHeader;
+}
+
+export function singleColumnFormContentStyle() {
+ return formStyles.singleColumnContent;
+}
+
const stickyActionFooterStyles = stylex.create({
root: {
width: "100%",
@@ -538,7 +580,12 @@ const denseFormStyles = stylex.create({
rowGap: 16,
paddingBlock: 16,
},
- header: { width: "100%" },
+ header: {
+ display: "flex",
+ flexDirection: "column",
+ rowGap: 8,
+ width: "100%",
+ },
content: { minWidth: 0 },
title: {
color: "rgb(var(--color-main))",
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index a3264ee15f..08a5959f65 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -3,12 +3,23 @@
"add-rules": "Add rules",
"ai-review": {
"ai-off": "AI is off for the workspace, so no AI review runs.",
- "description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see. It applies to every project in the workspace.",
+ "description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see. It applies to every project in the workspace, and each project can add its own policy.",
"enable": {
"description": "Each review sends the statements as written to the AI provider, and can send the schema of the target databases and their table statistics. It reads no rows from the databases.",
"self": "Review changes with AI"
},
- "project-description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see.",
+ "policy": {
+ "cannot-clear": "Your role cannot delete policies, so this policy cannot be emptied.",
+ "load-failed": "The review policy could not be loaded.",
+ "none": "No review policy.",
+ "paused": "This policy is paused, so the AI review does not read it.",
+ "placeholder": "For example:\nFlag a schema change that blocks writes on a table with more than 1 million rows.\nEvery foreign key needs an index on its columns.\nNew tables need created_at and updated_at columns.",
+ "project-placeholder": "For example:\nNever delete rows from the payments or ledger tables.\nStore amounts of money in DECIMAL columns, never FLOAT or DOUBLE.\nNew columns on the users table must allow NULL or have a default.",
+ "remove-only": "You can remove this policy but not change it. Clear the text to remove it.",
+ "self": "Review policy",
+ "too-large": "The policy is {{size}} bytes, over the {{limit}}-byte limit. Shorten it to save."
+ },
+ "project-description": "An AI model that reviews the SQL of an issue for risks the standard rules cannot see. This project's policy adds to the workspace policy and wins where the two conflict.",
"self": "AI review",
"set-for-workspace": "Set for the whole workspace.",
"turn-on-ai": "Turn on AI",
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 03910a1595..83e2510cb1 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -3,12 +3,23 @@
"add-rules": "Agregar reglas",
"ai-review": {
"ai-off": "La IA está desactivada en el espacio de trabajo, por lo que no se ejecuta ninguna revisión con IA.",
- "description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver. Se aplica a todos los proyectos del espacio de trabajo.",
+ "description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver. Se aplica a todos los proyectos del espacio de trabajo, y cada proyecto puede añadir su propia política.",
"enable": {
"description": "Cada revisión envía al proveedor de IA las sentencias tal como están escritas, y puede enviar el esquema de las bases de datos de destino y las estadísticas de sus tablas. No lee ninguna fila de las bases de datos.",
"self": "Revisar los cambios con IA"
},
- "project-description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver.",
+ "policy": {
+ "cannot-clear": "Tu rol no puede eliminar políticas, por lo que esta política no se puede vaciar.",
+ "load-failed": "No se pudo cargar la política de revisión.",
+ "none": "No hay política de revisión.",
+ "paused": "Esta política está en pausa, por lo que la revisión con IA no la lee.",
+ "placeholder": "Por ejemplo:\nSeñala un cambio de esquema que bloquee las escrituras en una tabla de más de 1 millón de filas.\nToda clave foránea necesita un índice sobre sus columnas.\nLas tablas nuevas necesitan las columnas created_at y updated_at.",
+ "project-placeholder": "Por ejemplo:\nNunca elimines filas de las tablas payments o ledger.\nGuarda los importes de dinero en columnas DECIMAL, nunca FLOAT ni DOUBLE.\nLas columnas nuevas de la tabla users deben admitir NULL o tener un valor por defecto.",
+ "remove-only": "Puedes eliminar esta política, pero no cambiarla. Vacía el texto para eliminarla.",
+ "self": "Política de revisión",
+ "too-large": "La política ocupa {{size}} bytes, más que el límite de {{limit}} bytes. Acórtala para guardarla."
+ },
+ "project-description": "Un modelo de IA que revisa el SQL de un issue en busca de riesgos que las reglas estándar no pueden ver. La política de este proyecto se suma a la del espacio de trabajo y prevalece cuando ambas se contradicen.",
"self": "Revisión con IA",
"set-for-workspace": "Se establece para todo el espacio de trabajo.",
"turn-on-ai": "Activar la IA",
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 8d18cad47f..2be11426fe 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -3,12 +3,23 @@
"add-rules": "ルールを追加する",
"ai-review": {
"ai-off": "ワークスペースで AI が無効になっているため、AI レビューは実行されません。",
- "description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。ワークスペース内のすべてのプロジェクトに適用されます。",
+ "description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。ワークスペース内のすべてのプロジェクトに適用され、各プロジェクトは独自のポリシーを追加できます。",
"enable": {
"description": "レビューのたびにステートメントの原文が AI プロバイダーに送信され、対象データベースのスキーマとテーブルの統計情報も送信される場合があります。データベースの行は読み取りません。",
"self": "AI で変更をレビューする"
},
- "project-description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。",
+ "policy": {
+ "cannot-clear": "ロールにポリシーの削除権限がないため、このポリシーを空にできません。",
+ "load-failed": "レビューポリシーを読み込めませんでした。",
+ "none": "レビューポリシーはありません。",
+ "paused": "このポリシーは一時停止中のため、AI レビューでは読み込まれません。",
+ "placeholder": "例:\n100 万行を超えるテーブルで書き込みをブロックするスキーマ変更を指摘する。\nすべての外部キーの列にインデックスを必須とする。\n新しいテーブルには created_at 列と updated_at 列を必須とする。",
+ "project-placeholder": "例:\npayments テーブルと ledger テーブルの行は削除しない。\n金額は DECIMAL 列に保存し、FLOAT や DOUBLE は使わない。\nusers テーブルに追加する列は NULL を許可するか、デフォルト値を持つこと。",
+ "remove-only": "このポリシーは削除できますが、変更はできません。削除するにはテキストを空にしてください。",
+ "self": "レビューポリシー",
+ "too-large": "ポリシーのサイズは {{size}} バイトで、上限の {{limit}} バイトを超えています。短くしてから保存してください。"
+ },
+ "project-description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。このプロジェクトのポリシーはワークスペースのポリシーに追加され、両者が矛盾する場合はこちらが優先されます。",
"self": "AI レビュー",
"set-for-workspace": "ワークスペース全体で設定されます。",
"turn-on-ai": "AI を有効にする",
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index 0bd881c1f0..a4c36130cb 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -3,12 +3,23 @@
"add-rules": "Thêm quy tắc",
"ai-review": {
"ai-off": "AI đang tắt trong không gian làm việc nên không có lần đánh giá bằng AI nào được chạy.",
- "description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được. Áp dụng cho mọi dự án trong không gian làm việc.",
+ "description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được. Áp dụng cho mọi dự án trong không gian làm việc, và mỗi dự án có thể thêm chính sách riêng.",
"enable": {
"description": "Mỗi lần đánh giá sẽ gửi nguyên văn các câu lệnh tới nhà cung cấp AI, và có thể gửi lược đồ của các cơ sở dữ liệu đích cùng số liệu thống kê bảng của chúng. Tính năng này không đọc bất kỳ hàng dữ liệu nào trong cơ sở dữ liệu.",
"self": "Đánh giá thay đổi bằng AI"
},
- "project-description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được.",
+ "policy": {
+ "cannot-clear": "Vai trò của bạn không thể xóa chính sách, nên không thể để trống chính sách này.",
+ "load-failed": "Không thể tải chính sách đánh giá.",
+ "none": "Chưa có chính sách đánh giá.",
+ "paused": "Chính sách này đang tạm dừng nên tính năng đánh giá bằng AI không đọc nó.",
+ "placeholder": "Ví dụ:\nĐánh dấu thay đổi lược đồ chặn ghi trên bảng có hơn 1 triệu hàng.\nMọi khóa ngoại đều cần chỉ mục trên các cột của nó.\nBảng mới cần có cột created_at và updated_at.",
+ "project-placeholder": "Ví dụ:\nKhông bao giờ xóa hàng khỏi bảng payments hoặc ledger.\nLưu số tiền trong cột DECIMAL, không dùng FLOAT hoặc DOUBLE.\nCột mới trên bảng users phải cho phép NULL hoặc có giá trị mặc định.",
+ "remove-only": "Bạn có thể xóa chính sách này nhưng không thể thay đổi nó. Hãy xóa hết nội dung để xóa chính sách.",
+ "self": "Chính sách đánh giá",
+ "too-large": "Chính sách có dung lượng {{size}} byte, vượt quá giới hạn {{limit}} byte. Hãy rút gọn để lưu."
+ },
+ "project-description": "Một mô hình AI đánh giá SQL của issue để tìm các rủi ro mà quy tắc tiêu chuẩn không phát hiện được. Chính sách của dự án này được bổ sung vào chính sách của không gian làm việc và được ưu tiên khi hai bên mâu thuẫn.",
"self": "Đánh giá bằng AI",
"set-for-workspace": "Được thiết lập cho toàn bộ không gian làm việc.",
"turn-on-ai": "Bật AI",
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index 5b664df5b1..4aeff1e12f 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -3,12 +3,23 @@
"add-rules": "添加规则",
"ai-review": {
"ai-off": "工作空间尚未启用 AI,因此不会运行 AI 审核。",
- "description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。对工作空间内的所有项目生效。",
+ "description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。对工作空间内的所有项目生效,每个项目还可以添加自己的策略。",
"enable": {
"description": "每次审核会将语句原文发送给 AI 提供方,并可能发送目标数据库的 Schema 及其表的统计信息,但不会读取数据库中的任何数据行。",
"self": "使用 AI 审核变更"
},
- "project-description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。",
+ "policy": {
+ "cannot-clear": "你的角色无法删除策略,因此不能清空此策略。",
+ "load-failed": "审核策略加载失败。",
+ "none": "未设置审核策略。",
+ "paused": "此策略已暂停,AI 审核不会读取它。",
+ "placeholder": "例如:\n标记在超过 100 万行的表上会阻塞写入的结构变更。\n每个外键的列都必须有索引。\n新建的表必须包含 created_at 列和 updated_at 列。",
+ "project-placeholder": "例如:\n禁止删除 payments 表或 ledger 表中的行。\n金额必须存放在 DECIMAL 列中,不能使用 FLOAT 或 DOUBLE。\nusers 表新增的列必须允许 NULL 或带有默认值。",
+ "remove-only": "你可以删除此策略,但不能修改它。清空文本即可删除。",
+ "self": "审核策略",
+ "too-large": "策略大小为 {{size}} 字节,超过了 {{limit}} 字节的上限。请缩短后再保存。"
+ },
+ "project-description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。本项目的策略会追加到工作空间策略之上,两者冲突时以本项目的策略为准。",
"self": "AI 审核",
"set-for-workspace": "由工作空间统一设置。",
"turn-on-ai": "启用 AI",
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
index 8046a78f88..df221631a5 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
@@ -13,6 +13,7 @@ import {
PolicyResourceType,
PolicySchema,
PolicyType,
+ ReviewAIPolicySchema,
ReviewRulePolicySchema,
} from "@/types/proto-es/v1/org_policy_service_pb";
import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
@@ -20,10 +21,13 @@ import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
const WORKSPACE = "workspaces/ws";
const PROJECT = "projects/p";
+const ruleName = (parent: string) => `${parent}/policies/review_rule`;
+const aiName = (parent: string) => `${parent}/policies/review_ai`;
+
const mocks = vi.hoisted(() => ({
permissions: {} as Record<string, boolean>,
workspacePermissions: {} as Record<string, boolean>,
- // Parents whose read fails: the store then caches nothing for them.
+ // Policy names whose read fails: the store then caches nothing for them.
unreadable: new Set<string>(),
upsertPolicy: vi.fn(),
deletePolicy: vi.fn(),
@@ -65,30 +69,30 @@ vi.mock("@/components/RouterLink", () => ({
),
}));
-// Mirrors the real store: a fetch of a missing policy caches one with no
-// payload and resolves to null, a failed read resolves to undefined and
-// leaves the cache as it was, and a delete drops the cached entry.
+// Mirrors the real store: policies are cached by name, a fetch of a missing
+// policy caches one with no payload and resolves to null, a failed read
+// resolves to undefined and leaves the cache as it was, and a delete drops the
+// cached entry.
vi.mock("@/stores/app", async () => {
const { create: createStore } = await import("zustand");
const { create: createMessage } = await import("@bufbuild/protobuf");
- const { PolicySchema: Schema } = await import(
+ const { PolicySchema: Schema, PolicyType: Type } = await import(
"@/types/proto-es/v1/org_policy_service_pb"
);
type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
+ type Find = { parentPath: string; policyType: number; refresh?: boolean };
+ const nameOf = (parentPath: string, policyType: number) =>
+ `${parentPath}/policies/${Type[policyType].toLowerCase()}`;
const useAppStore = createStore<{
policies: Record<string, StorePolicy>;
serverInfo?: { aiEnabled: boolean; aiSqlReviewEnabled: boolean };
- getPolicyByParentAndType: (params: {
- parentPath: string;
- }) => StorePolicy | undefined;
- fetchPolicyByParentAndType: (params: {
- parentPath: string;
- refresh?: boolean;
- }) => Promise<StorePolicy | null | undefined>;
- getOrFetchPolicyByParentAndType: (params: {
- parentPath: string;
- refresh?: boolean;
- }) => Promise<StorePolicy | undefined>;
+ getPolicyByParentAndType: (find: Find) => StorePolicy | undefined;
+ fetchPolicyByParentAndType: (
+ find: Find
+ ) => Promise<StorePolicy | null | undefined>;
+ getOrFetchPolicyByParentAndType: (
+ find: Find
+ ) => Promise<StorePolicy | undefined>;
upsertPolicy: (params: {
parentPath: string;
policy: Partial<StorePolicy>;
@@ -96,58 +100,55 @@ vi.mock("@/stores/app", async () => {
deletePolicy: (name: string) => Promise<void>;
}>()((set, get) => ({
policies: {},
- getPolicyByParentAndType: ({ parentPath }) => get().policies[parentPath],
- fetchPolicyByParentAndType: async (params) => {
- mocks.fetchPolicy(params);
- if (mocks.unreadable.has(params.parentPath)) return undefined;
- if (!get().policies[params.parentPath]) {
+ getPolicyByParentAndType: (find) =>
+ get().policies[nameOf(find.parentPath, find.policyType)],
+ fetchPolicyByParentAndType: async (find) => {
+ mocks.fetchPolicy(find);
+ const name = nameOf(find.parentPath, find.policyType);
+ if (mocks.unreadable.has(name)) return undefined;
+ if (!get().policies[name]) {
set((state) => ({
policies: {
...state.policies,
- [params.parentPath]: createMessage(Schema, {
- name: `${params.parentPath}/policies/review_rule`,
- }),
+ [name]: createMessage(Schema, { name }),
},
}));
return null;
}
- return get().policies[params.parentPath];
+ return get().policies[name];
},
- getOrFetchPolicyByParentAndType: async (params) =>
- (await get().fetchPolicyByParentAndType(params)) ?? undefined,
+ getOrFetchPolicyByParentAndType: async (find) =>
+ (await get().fetchPolicyByParentAndType(find)) ?? undefined,
upsertPolicy: async (params) => {
await mocks.upsertPolicy(params);
- const saved = {
- ...params.policy,
- name: `${params.parentPath}/policies/review_rule`,
- } as StorePolicy;
- set((state) => ({
- policies: { ...state.policies, [params.parentPath]: saved },
- }));
+ const name = nameOf(params.parentPath, params.policy.type!);
+ const saved = { ...params.policy, name } as StorePolicy;
+ set((state) => ({ policies: { ...state.policies, [name]: saved } }));
return saved;
},
deletePolicy: async (name) => {
await mocks.deletePolicy(name);
- set((state) => ({
- policies: Object.fromEntries(
- Object.entries(state.policies).filter(
- ([, policy]) => policy.name !== name
- )
- ),
- }));
+ set((state) => {
+ const { [name]: _removed, ...policies } = state.policies;
+ return { policies };
+ });
},
}));
return { useAppStore };
});
const { useAppStore } = await import("@/stores/app");
-// The mocked store holds only the policy cache.
+// Caches each policy under its name; the keys only label the seed.
const seedPolicies = (policies: Record<string, Policy>) =>
(
useAppStore as unknown as {
setState: (state: { policies: Record<string, Policy> }) => void;
}
- ).setState({ policies });
+ ).setState({
+ policies: Object.fromEntries(
+ Object.values(policies).map((policy) => [policy.name, policy])
+ ),
+ });
const seedServerInfo = (serverInfo?: {
aiEnabled: boolean;
aiSqlReviewEnabled: boolean;
@@ -165,7 +166,7 @@ const reviewRulePolicy = (
enforce = true
): Policy =>
create(PolicySchema, {
- name: `${parent}/policies/review_rule`,
+ name: ruleName(parent),
type: PolicyType.REVIEW_RULE,
enforce,
policy: {
@@ -174,6 +175,17 @@ const reviewRulePolicy = (
},
});
+const reviewAIPolicy = (parent: string, content: string): Policy =>
+ create(PolicySchema, {
+ name: aiName(parent),
+ type: PolicyType.REVIEW_AI,
+ enforce: true,
+ policy: {
+ case: "reviewAiPolicy",
+ value: create(ReviewAIPolicySchema, { content }),
+ },
+ });
+
const workspacePolicy = () =>
reviewRulePolicy(WORKSPACE, [
ReviewRuleType.SYNTAX,
@@ -201,6 +213,9 @@ const ruleSwitch = (rule: string) =>
const updateButton = () =>
screen.queryByRole("button", { name: "common.update" });
+const policyEditor = () =>
+ screen.findByRole("textbox", { name: "sql-review.ai-review.policy.self" });
+
const update = () =>
act(async () => {
fireEvent.click(screen.getByRole("button", { name: "common.update" }));
@@ -325,9 +340,7 @@ describe("ProjectSQLReviewPage", () => {
await update();
expect(mocks.upsertPolicy).not.toHaveBeenCalled();
- expect(mocks.deletePolicy).toHaveBeenCalledWith(
- `${PROJECT}/policies/review_rule`
- );
+ expect(mocks.deletePolicy).toHaveBeenCalledWith(ruleName(PROJECT));
expect(mocks.fetchPolicy).toHaveBeenLastCalledWith({
parentPath: PROJECT,
policyType: PolicyType.REVIEW_RULE,
@@ -430,7 +443,7 @@ describe("ProjectSQLReviewPage", () => {
});
test("a failed read shows an error instead of the switches, and retry reads again", async () => {
- mocks.unreadable.add(PROJECT);
+ mocks.unreadable.add(ruleName(PROJECT));
render(<ProjectSQLReviewPage projectId="p" />);
expect(await screen.findByRole("alert")).toHaveTextContent(
@@ -506,13 +519,13 @@ describe("ProjectSQLReviewPage", () => {
});
test("a retry that fails again keeps the error, whatever the cache holds", async () => {
- mocks.unreadable.add(PROJECT);
+ mocks.unreadable.add(ruleName(PROJECT));
render(<ProjectSQLReviewPage projectId="p" />);
await screen.findByRole("alert");
// The workspace policy read fine and is cached; now only its read fails.
mocks.unreadable.clear();
- mocks.unreadable.add(WORKSPACE);
+ mocks.unreadable.add(ruleName(WORKSPACE));
fireEvent.click(
screen.getByRole("button", { name: "sql-review.standard-rules.retry" })
);
@@ -592,4 +605,151 @@ describe("ProjectSQLReviewPage", () => {
expect(customize).toHaveAttribute("aria-checked", "false");
expect(updateButton()).not.toBeInTheDocument();
});
+
+ test("the project AI review policy saves at the project from the footer", async () => {
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ const editor = await policyEditor();
+ expect(editor).toHaveValue("");
+ expect(editor).toHaveAttribute(
+ "placeholder",
+ "sql-review.ai-review.policy.project-placeholder"
+ );
+ fireEvent.change(editor, { target: { value: "No DROP in this project." } });
+ await update();
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledOnce();
+ const { parentPath, policy } = mocks.upsertPolicy.mock.calls[0][0];
+ expect(parentPath).toBe(PROJECT);
+ expect(policy.type).toBe(PolicyType.REVIEW_AI);
+ expect(policy.resourceType).toBe(PolicyResourceType.PROJECT);
+ expect(policy.enforce).toBe(true);
+ expect(policy.policy.value.content).toBe("No DROP in this project.");
+ expect(updateButton()).not.toBeInTheDocument();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test("the footer saves the rules and the AI review policy, and reports one update", async () => {
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ fireEvent.change(await policyEditor(), { target: { value: "No DROP." } });
+ await update();
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.upsertPolicy.mock.calls.map(([params]) => params.policy.type)
+ ).toEqual(
+ expect.arrayContaining([PolicyType.REVIEW_RULE, PolicyType.REVIEW_AI])
+ );
+ expect(updateButton()).not.toBeInTheDocument();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test("a failed AI review policy save keeps its draft and reports no update", async () => {
+ mocks.upsertPolicy.mockImplementation(async ({ policy }) => {
+ if (policy.type === PolicyType.REVIEW_AI) throw new Error("denied");
+ });
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ const editor = await policyEditor();
+ fireEvent.change(editor, { target: { value: "No DROP." } });
+ await update();
+
+ expect(customize).toHaveAttribute("aria-checked", "true");
+ expect(editor).toHaveValue("No DROP.");
+ expect(updateButton()).toBeInTheDocument();
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("cancel reverts the AI review policy too", async () => {
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ ai: reviewAIPolicy(PROJECT, "Stored."),
+ });
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ const editor = await policyEditor();
+ fireEvent.change(editor, { target: { value: "Edited." } });
+ fireEvent.click(screen.getByRole("button", { name: "common.cancel" }));
+
+ expect(editor).toHaveValue("Stored.");
+ expect(updateButton()).not.toBeInTheDocument();
+ });
+
+ test("the footer cannot update while the AI review policy is over the size limit", async () => {
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ fireEvent.change(await policyEditor(), {
+ target: { value: "a".repeat(64 * 1024 + 1) },
+ });
+
+ expect(
+ screen.getByText("sql-review.ai-review.policy.too-large")
+ ).toBeInTheDocument();
+ expect(updateButton()).toBeDisabled();
+ });
+
+ test("the project AI review policy shows as text without bb.policies.update or bb.policies.delete", async () => {
+ mocks.permissions = {
+ "bb.policies.update": false,
+ "bb.policies.delete": false,
+ };
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ ai: reviewAIPolicy(PROJECT, "No DROP in this project."),
+ });
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ expect(
+ await screen.findByText("No DROP in this project.")
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ test("a project role with bb.policies.delete but not bb.policies.update removes the AI review policy from the footer", async () => {
+ mocks.permissions = { "bb.policies.update": false };
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ ai: reviewAIPolicy(PROJECT, "No DROP in this project."),
+ });
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ fireEvent.change(await policyEditor(), { target: { value: "" } });
+ await update();
+
+ expect(mocks.deletePolicy).toHaveBeenCalledWith(aiName(PROJECT));
+ expect(mocks.upsertPolicy).not.toHaveBeenCalled();
+ expect(updateButton()).not.toBeInTheDocument();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test("a project role with bb.policies.delete but not bb.policies.update cannot update changed text", async () => {
+ mocks.permissions = { "bb.policies.update": false };
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ ai: reviewAIPolicy(PROJECT, "No DROP in this project."),
+ });
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ fireEvent.change(await policyEditor(), {
+ target: { value: "No DROP or TRUNCATE in this project." },
+ });
+
+ expect(
+ screen.getByText("sql-review.ai-review.policy.remove-only")
+ ).toBeInTheDocument();
+ expect(updateButton()).toBeDisabled();
+ });
+
+ test("a project without an AI review policy needs bb.policies.create to add one", async () => {
+ mocks.permissions = { "bb.policies.create": false };
+ render(<ProjectSQLReviewPage projectId="p" />);
+
+ expect(
+ await screen.findByText("sql-review.ai-review.policy.none")
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
index 6014282081..345cde2813 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
@@ -4,6 +4,10 @@ import { useTranslation } from "react-i18next";
import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/app/router/handles";
import { ProjectPageLayout } from "@/components/ProjectPageLayout";
import { RouterLink } from "@/components/RouterLink";
+import {
+ ReviewAIPolicyField,
+ useReviewAIPolicyDraft,
+} from "@/components/sql-review/ReviewAIPolicyField";
import { StandardRuleSwitches } from "@/components/sql-review/StandardRuleSwitches";
import { SwitchRow } from "@/components/sql-review/SwitchRow";
import {
@@ -15,11 +19,11 @@ import {
} from "@/components/sql-review/standardRules";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
+import { FormFieldGroup, FormSection } from "@/components/ui/form";
import { StickyActionFooter } from "@/components/ui/sticky-action-footer";
import { useWorkspaceResourceName } from "@/hooks/useAppState";
import { useProjectByName } from "@/hooks/useProjectByName";
import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
-import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
@@ -53,7 +57,9 @@ interface ProjectStandardRules {
isDirty: boolean;
saving: boolean;
revert: () => void;
- save: () => Promise<void>;
+ // Resolves whether the rules saved. The page reports the update; a failure
+ // is reported by the response middleware and keeps the draft.
+ save: () => Promise<boolean>;
}
interface Draft {
@@ -64,7 +70,6 @@ interface Draft {
export function useProjectStandardRules(
projectName: string
): ProjectStandardRules {
- const { t } = useTranslation();
const workspace = useWorkspaceResourceName();
const projectPolicy = useAppStore((state) =>
state.getPolicyByParentAndType({
@@ -141,7 +146,7 @@ export function useProjectStandardRules(
};
const save = async () => {
- if (!draft || !isDirty) return;
+ if (!draft || !isDirty) return true;
setSaving(true);
try {
const store = useAppStore.getState();
@@ -167,14 +172,9 @@ export function useProjectStandardRules(
});
}
setDraft(undefined);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
+ return true;
} catch {
- // The response middleware reports the failure; the draft stays for a
- // retry.
+ return false;
} finally {
setSaving(false);
}
@@ -205,11 +205,19 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
const { t } = useTranslation();
const projectName = `${projectNamePrefix}${projectId}`;
const project = useProjectByName(projectName);
- const standardRules = useProjectStandardRules(projectName);
- useUnsavedChangesGuard(standardRules.isDirty);
-
const can = (permission: Permission) =>
hasProjectPermissionV2(project, permission);
+ const standardRules = useProjectStandardRules(projectName);
+ const aiReviewPolicy = useReviewAIPolicyDraft({
+ parentPath: projectName,
+ resourceType: PolicyResourceType.PROJECT,
+ can,
+ });
+ const parts = [standardRules, aiReviewPolicy];
+ const isDirty = parts.some((part) => part.isDirty);
+ const saving = parts.some((part) => part.saving);
+ useUnsavedChangesGuard(isDirty);
+
// Switching customization on and editing the project's own rules save the
// project policy: a create when the project has no row, else an update.
// Switching customization off deletes the row. Undoing an unsaved switch
@@ -232,38 +240,86 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
return (
<ProjectPageLayout>
- <div className={cn(STANDARD_RULES_COLUMN, "flex flex-col gap-y-6 pt-4")}>
- <div className="flex flex-col gap-y-2">
- <h1 className="text-2xl font-bold text-main">
- {t("sql-review.standard-rules.self")}
- </h1>
- <p className="text-sm text-control-light">
- {t("sql-review.standard-rules.project-description")}
- </p>
- </div>
- {standardRules.readFailed && (
- <Alert
- variant="error"
- description={t("sql-review.standard-rules.load-failed")}
- >
- <Button
- className="mt-3"
- appearance="outline"
- size="sm"
- onClick={standardRules.reload}
+ <div className={STANDARD_RULES_COLUMN}>
+ <FormSection
+ layout="single-column"
+ title={t("sql-review.standard-rules.self")}
+ description={t("sql-review.standard-rules.project-description")}
+ >
+ {standardRules.readFailed && (
+ <Alert
+ variant="error"
+ description={t("sql-review.standard-rules.load-failed")}
>
- {t("sql-review.standard-rules.retry")}
- </Button>
- </Alert>
- )}
- {standardRules.loaded && (
- <>
+ <Button
+ className="mt-3"
+ appearance="outline"
+ size="sm"
+ onClick={standardRules.reload}
+ >
+ {t("sql-review.standard-rules.retry")}
+ </Button>
+ </Alert>
+ )}
+ {standardRules.loaded && (
+ <>
+ <SwitchRow
+ className="rounded-sm border border-block-border px-4 py-3"
+ title={t("sql-review.standard-rules.customize.self")}
+ description={
+ <>
+ {t("sql-review.standard-rules.customize.description")}
+ {canViewWorkspaceRules && (
+ <>
+ {" "}
+ <RouterLink
+ to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}
+ className="text-accent hover:underline"
+ >
+ {t(
+ "sql-review.standard-rules.customize.view-workspace-rules"
+ )}
+ </RouterLink>
+ </>
+ )}
+ </>
+ }
+ checked={standardRules.customized}
+ onCheckedChange={standardRules.setCustomized}
+ disabled={customizeLocked || standardRules.saving}
+ />
+ {standardRules.rules ? (
+ <StandardRuleSwitches
+ // The rules remembered while SYNTAX is off belong to one
+ // project.
+ key={projectName}
+ rules={standardRules.rules}
+ onChange={standardRules.setRules}
+ disabled={!canSave || standardRules.saving}
+ readOnly={!standardRules.customized}
+ />
+ ) : (
+ <Alert
+ description={t(
+ "sql-review.standard-rules.workspace-rules-hidden"
+ )}
+ />
+ )}
+ </>
+ )}
+ </FormSection>
+ <FormSection
+ layout="single-column"
+ title={t("sql-review.ai-review.self")}
+ description={t("sql-review.ai-review.project-description")}
+ >
+ <FormFieldGroup>
<SwitchRow
className="rounded-sm border border-block-border px-4 py-3"
- title={t("sql-review.standard-rules.customize.self")}
+ title={t("sql-review.ai-review.enable.self")}
description={
<>
- {t("sql-review.standard-rules.customize.description")}
+ {t("sql-review.ai-review.set-for-workspace")}
{canViewWorkspaceRules && (
<>
{" "}
@@ -271,87 +327,56 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}
className="text-accent hover:underline"
>
- {t(
- "sql-review.standard-rules.customize.view-workspace-rules"
- )}
+ {t("sql-review.ai-review.view-workspace-setting")}
</RouterLink>
</>
)}
</>
}
- checked={standardRules.customized}
- onCheckedChange={standardRules.setCustomized}
- disabled={customizeLocked || standardRules.saving}
+ checked={aiReviewOn}
+ onCheckedChange={() => {}}
+ readOnly
/>
- {standardRules.rules ? (
- <StandardRuleSwitches
- // The rules remembered while SYNTAX is off belong to one
- // project.
- key={projectName}
- rules={standardRules.rules}
- onChange={standardRules.setRules}
- disabled={!canSave || standardRules.saving}
- readOnly={!standardRules.customized}
- />
- ) : (
- <Alert
- description={t(
- "sql-review.standard-rules.workspace-rules-hidden"
- )}
- />
- )}
- </>
- )}
- <div className="flex flex-col gap-y-2 pt-8">
- <h1 className="text-2xl font-bold text-main">
- {t("sql-review.ai-review.self")}
- </h1>
- <p className="text-sm text-control-light">
- {t("sql-review.ai-review.project-description")}
- </p>
- </div>
- <SwitchRow
- className="rounded-sm border border-block-border px-4 py-3"
- title={t("sql-review.ai-review.enable.self")}
- description={
- <>
- {t("sql-review.ai-review.set-for-workspace")}
- {canViewWorkspaceRules && (
- <>
- {" "}
- <RouterLink
- to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}
- className="text-accent hover:underline"
- >
- {t("sql-review.ai-review.view-workspace-setting")}
- </RouterLink>
- </>
- )}
- </>
- }
- checked={aiReviewOn}
- onCheckedChange={() => {}}
- readOnly
- />
+ <ReviewAIPolicyField
+ policy={aiReviewPolicy}
+ placeholder={t("sql-review.ai-review.policy.project-placeholder")}
+ />
+ </FormFieldGroup>
+ </FormSection>
</div>
- {standardRules.isDirty && (
+ {isDirty && (
<StickyActionFooter
contentPadding={false}
contentClassName={STANDARD_RULES_COLUMN}
left={
<Button
appearance="outline"
- disabled={standardRules.saving}
- onClick={standardRules.revert}
+ disabled={saving}
+ onClick={() => {
+ for (const part of parts) part.revert();
+ }}
>
{t("common.cancel")}
</Button>
}
right={
<Button
- disabled={standardRules.saving}
- onClick={() => void standardRules.save()}
+ disabled={saving || aiReviewPolicy.error !== undefined}
+ onClick={async () => {
+ const saves = parts
+ .filter((part) => part.isDirty)
+ .map((part) => part.save());
+ // One click reports one update, and only when every changed
+ // part saved.
+ if ((await Promise.all(saves)).every(Boolean)) {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ }
+ }}
>
{t("common.update")}
</Button>
diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx
index 63edca90eb..50cf5e68eb 100644
--- a/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx
@@ -1,14 +1,25 @@
+import { create } from "@bufbuild/protobuf";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { type ReactNode, useState } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ type Policy,
+ PolicyResourceType,
+ PolicySchema,
+ PolicyType,
+ ReviewAIPolicySchema,
+} from "@/types/proto-es/v1/org_policy_service_pb";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
const SWITCH = { name: "sql-review.ai-review.enable.self" };
+const POLICY_EDITOR = { name: "sql-review.ai-review.policy.self" };
+const WORKSPACE = "workspaces/ws";
const mocks = vi.hoisted(() => ({
permissions: {} as Record<string, boolean>,
saas: { value: false },
upsertSetting: vi.fn(),
+ upsertPolicy: vi.fn(),
pushNotification: vi.fn(),
}));
@@ -18,6 +29,7 @@ vi.mock("react-i18next", () => ({
vi.mock("@/hooks/useAppState", () => ({
useServerState: () => ({ isSaaSMode: mocks.saas.value }),
+ useWorkspaceResourceName: () => "workspaces/ws",
}));
vi.mock("@/utils", () => ({
@@ -33,18 +45,36 @@ vi.mock("@/components/RouterLink", () => ({
),
}));
-// Mirrors the real store: a saved AI setting updates the server info.
+// Mirrors the real store: a saved AI setting updates the server info, a fetch
+// of a missing policy caches one with no payload and resolves to null, and a
+// saved policy is cached under its name.
vi.mock("@/stores/app", async () => {
const { create: createStore } = await import("zustand");
+ const { create: createMessage } = await import("@bufbuild/protobuf");
+ const { PolicySchema: Schema, PolicyType: Type } = await import(
+ "@/types/proto-es/v1/org_policy_service_pb"
+ );
+ type StorePolicy = import("@/types/proto-es/v1/org_policy_service_pb").Policy;
+ type Find = { parentPath: string; policyType: number };
+ const nameOf = (parentPath: string, policyType: number) =>
+ `${parentPath}/policies/${Type[policyType].toLowerCase()}`;
type ServerInfo = { aiEnabled: boolean; aiSqlReviewEnabled: boolean };
type Saved = {
value: { value: { value: { sqlReviewEnabled: boolean } } };
};
const useAppStore = createStore<{
serverInfo: ServerInfo;
+ policies: Record<string, StorePolicy>;
upsertSetting: (params: Saved) => Promise<void>;
- }>()((set) => ({
+ getPolicyByParentAndType: (find: Find) => StorePolicy | undefined;
+ fetchPolicyByParentAndType: (find: Find) => Promise<StorePolicy | null>;
+ upsertPolicy: (params: {
+ parentPath: string;
+ policy: Partial<StorePolicy>;
+ }) => Promise<StorePolicy>;
+ }>()((set, get) => ({
serverInfo: { aiEnabled: true, aiSqlReviewEnabled: false },
+ policies: {},
upsertSetting: async (params) => {
await mocks.upsertSetting(params);
set((state) => ({
@@ -54,6 +84,28 @@ vi.mock("@/stores/app", async () => {
},
}));
},
+ getPolicyByParentAndType: (find) =>
+ get().policies[nameOf(find.parentPath, find.policyType)],
+ fetchPolicyByParentAndType: async (find) => {
+ const name = nameOf(find.parentPath, find.policyType);
+ if (!get().policies[name]) {
+ set((state) => ({
+ policies: {
+ ...state.policies,
+ [name]: createMessage(Schema, { name }),
+ },
+ }));
+ return null;
+ }
+ return get().policies[name];
+ },
+ upsertPolicy: async (params) => {
+ await mocks.upsertPolicy(params);
+ const name = nameOf(params.parentPath, params.policy.type!);
+ const saved = { ...params.policy, name } as StorePolicy;
+ set((state) => ({ policies: { ...state.policies, [name]: saved } }));
+ return saved;
+ },
}));
return { useAppStore };
});
@@ -68,19 +120,42 @@ const seedServerInfo = (serverInfo: {
setState: (state: { serverInfo: typeof serverInfo }) => void;
}
).setState({ serverInfo });
+const seedPolicies = (policies: Record<string, Policy>) =>
+ (
+ useAppStore as unknown as {
+ setState: (state: { policies: Record<string, Policy> }) => void;
+ }
+ ).setState({ policies });
+
+const workspacePolicy = (content: string) =>
+ create(PolicySchema, {
+ name: `${WORKSPACE}/policies/review_ai`,
+ type: PolicyType.REVIEW_AI,
+ enforce: true,
+ policy: {
+ case: "reviewAiPolicy",
+ value: create(ReviewAIPolicySchema, { content }),
+ },
+ });
-const { SQLReviewAIReviewSection, useWorkspaceAIReview } = await import(
- "./SQLReviewAIReviewSection"
-);
+const {
+ SQLReviewAIReviewSection,
+ useWorkspaceAIReview,
+ useWorkspaceReviewAIPolicy,
+} = await import("./SQLReviewAIReviewSection");
function Harness() {
const aiReview = useWorkspaceAIReview();
+ const policy = useWorkspaceReviewAIPolicy(true);
const [saved, setSaved] = useState<boolean>();
+ const [policySaved, setPolicySaved] = useState<boolean>();
return (
<>
- <SQLReviewAIReviewSection aiReview={aiReview} />
+ <SQLReviewAIReviewSection aiReview={aiReview} policy={policy} />
<output>{aiReview.isDirty ? "dirty" : "clean"}</output>
<output>{`saved: ${saved}`}</output>
+ <output>{`policy ${policy.isDirty ? "dirty" : "clean"}`}</output>
+ <output>{`policy saved: ${policySaved}`}</output>
<button
type="button"
onClick={() => void aiReview.save().then(setSaved)}
@@ -90,6 +165,12 @@ function Harness() {
<button type="button" onClick={aiReview.revert}>
revert
</button>
+ <button
+ type="button"
+ onClick={() => void policy.save().then(setPolicySaved)}
+ >
+ save policy
+ </button>
</>
);
}
@@ -104,8 +185,69 @@ describe("SQLReviewAIReviewSection", () => {
mocks.permissions = {};
mocks.saas.value = false;
mocks.upsertSetting.mockReset();
+ mocks.upsertPolicy.mockReset();
mocks.pushNotification.mockReset();
seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: false });
+ seedPolicies({});
+ });
+
+ test("loads the workspace policy, and saves an edit under the workspace", async () => {
+ seedPolicies({
+ [`${WORKSPACE}/policies/review_ai`]: workspacePolicy("No DROP."),
+ });
+ render(<Harness />);
+
+ const editor = await screen.findByRole("textbox", POLICY_EDITOR);
+ expect(editor).toHaveValue("No DROP.");
+ expect(editor).toHaveAttribute(
+ "placeholder",
+ "sql-review.ai-review.policy.placeholder"
+ );
+ fireEvent.change(editor, { target: { value: "No DROP or TRUNCATE." } });
+ expect(screen.getByText("policy dirty")).toBeInTheDocument();
+ expect(screen.getByText("clean")).toBeInTheDocument();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "save policy" }));
+ });
+
+ expect(mocks.upsertPolicy).toHaveBeenCalledOnce();
+ const { parentPath, policy } = mocks.upsertPolicy.mock.calls[0][0];
+ expect(parentPath).toBe(WORKSPACE);
+ expect(policy.type).toBe(PolicyType.REVIEW_AI);
+ expect(policy.resourceType).toBe(PolicyResourceType.WORKSPACE);
+ expect(policy.policy.case).toBe("reviewAiPolicy");
+ expect(policy.policy.value.content).toBe("No DROP or TRUNCATE.");
+ expect(screen.getByText("policy clean")).toBeInTheDocument();
+ expect(screen.getByText("policy saved: true")).toBeInTheDocument();
+ expect(mocks.upsertSetting).not.toHaveBeenCalled();
+ expect(mocks.pushNotification).not.toHaveBeenCalled();
+ });
+
+ test("a failed policy save keeps the edit", async () => {
+ mocks.upsertPolicy.mockRejectedValueOnce(new Error("denied"));
+ render(<Harness />);
+
+ const editor = await screen.findByRole("textbox", POLICY_EDITOR);
+ fireEvent.change(editor, { target: { value: "No DROP." } });
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "save policy" }));
+ });
+
+ expect(editor).toHaveValue("No DROP.");
+ expect(screen.getByText("policy dirty")).toBeInTheDocument();
+ expect(screen.getByText("policy saved: false")).toBeInTheDocument();
+ });
+
+ test("shows the workspace policy as text without bb.policies.update or bb.policies.delete", async () => {
+ mocks.permissions["bb.policies.update"] = false;
+ mocks.permissions["bb.policies.delete"] = false;
+ seedPolicies({
+ [`${WORKSPACE}/policies/review_ai`]: workspacePolicy("No DROP."),
+ });
+ render(<Harness />);
+
+ expect(await screen.findByText("No DROP.")).toBeInTheDocument();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
});
test("saves the switch under its own mask path", async () => {
diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx
index 156cc52e4c..882dac4103 100644
--- a/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx
@@ -4,10 +4,17 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";
import { RouterLink } from "@/components/RouterLink";
+import {
+ type ReviewAIPolicyDraft,
+ ReviewAIPolicyField,
+ useReviewAIPolicyDraft,
+} from "@/components/sql-review/ReviewAIPolicyField";
import { SwitchRow } from "@/components/sql-review/SwitchRow";
import { Alert } from "@/components/ui/alert";
-import { useServerState } from "@/hooks/useAppState";
+import { FormFieldGroup, FormSection } from "@/components/ui/form";
+import { useServerState, useWorkspaceResourceName } from "@/hooks/useAppState";
import { useAppStore } from "@/stores/app";
+import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";
import {
AISettingSchema,
Setting_SettingName,
@@ -86,10 +93,26 @@ export function useWorkspaceAIReview(): WorkspaceAIReview {
};
}
+// The workspace policy reaches the review of every project, together with the
+// project's own.
+export function useWorkspaceReviewAIPolicy(
+ enabled: boolean
+): ReviewAIPolicyDraft {
+ const workspace = useWorkspaceResourceName();
+ return useReviewAIPolicyDraft({
+ parentPath: workspace,
+ resourceType: PolicyResourceType.WORKSPACE,
+ can: hasWorkspacePermissionV2,
+ enabled,
+ });
+}
+
export function SQLReviewAIReviewSection({
aiReview,
+ policy,
}: {
aiReview: WorkspaceAIReview;
+ policy: ReviewAIPolicyDraft;
}) {
const { t } = useTranslation();
// AI is turned on in the general settings, whose AI section shows its
@@ -100,15 +123,11 @@ export function SQLReviewAIReviewSection({
hasWorkspacePermissionV2("bb.settings.getWorkspaceProfile");
return (
- <section className="flex flex-col gap-y-6 pt-8">
- <div className="flex flex-col gap-y-2">
- <h1 className="text-2xl font-bold text-main">
- {t("sql-review.ai-review.self")}
- </h1>
- <p className="text-sm text-control-light">
- {t("sql-review.ai-review.description")}
- </p>
- </div>
+ <FormSection
+ layout="single-column"
+ title={t("sql-review.ai-review.self")}
+ description={t("sql-review.ai-review.description")}
+ >
{!aiReview.aiEnabled && (
<Alert
variant="warning"
@@ -133,15 +152,21 @@ export function SQLReviewAIReviewSection({
}
/>
)}
- <SwitchRow
- className="rounded-sm border border-block-border px-4 py-3"
- title={t("sql-review.ai-review.enable.self")}
- description={t("sql-review.ai-review.enable.description")}
- checked={aiReview.enabled}
- onCheckedChange={aiReview.setEnabled}
- disabled={aiReview.saving}
- readOnly={!aiReview.canEdit}
- />
- </section>
+ <FormFieldGroup>
+ <SwitchRow
+ className="rounded-sm border border-block-border px-4 py-3"
+ title={t("sql-review.ai-review.enable.self")}
+ description={t("sql-review.ai-review.enable.description")}
+ checked={aiReview.enabled}
+ onCheckedChange={aiReview.setEnabled}
+ disabled={aiReview.saving}
+ readOnly={!aiReview.canEdit}
+ />
+ <ReviewAIPolicyField
+ policy={policy}
+ placeholder={t("sql-review.ai-review.policy.placeholder")}
+ />
+ </FormFieldGroup>
+ </FormSection>
);
}
diff --git a/frontend/src/routes/workspace/SQLReviewPage.test.tsx b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
index 450dc993f1..919a8e7edd 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.test.tsx
@@ -14,6 +14,14 @@ const mocks = vi.hoisted(() => ({
save: vi.fn(),
},
aiReview: { isDirty: false, saving: false, revert: vi.fn(), save: vi.fn() },
+ aiReviewPolicy: {
+ isDirty: false,
+ saving: false,
+ error: undefined as string | undefined,
+ revert: vi.fn(),
+ save: vi.fn(),
+ },
+ aiReviewPolicyEnabled: vi.fn(),
pushNotification: vi.fn(),
}));
@@ -33,6 +41,10 @@ vi.mock("./SQLReviewStandardRulesSection", () => ({
vi.mock("./SQLReviewAIReviewSection", () => ({
SQLReviewAIReviewSection: () => <div>ai-review-section</div>,
useWorkspaceAIReview: () => mocks.aiReview,
+ useWorkspaceReviewAIPolicy: (enabled: boolean) => {
+ mocks.aiReviewPolicyEnabled(enabled);
+ return mocks.aiReviewPolicy;
+ },
}));
vi.mock("@/stores/sqlReview", () => {
@@ -71,12 +83,18 @@ const update = () =>
describe("SQLReviewPage", () => {
beforeEach(() => {
mocks.fetchReviewPolicyList.mockReset();
- for (const part of [mocks.standardRules, mocks.aiReview]) {
+ for (const part of [
+ mocks.standardRules,
+ mocks.aiReview,
+ mocks.aiReviewPolicy,
+ ]) {
part.isDirty = false;
part.saving = false;
part.revert.mockReset();
part.save.mockReset().mockResolvedValue(true);
}
+ mocks.aiReviewPolicy.error = undefined;
+ mocks.aiReviewPolicyEnabled.mockReset();
mocks.pushNotification.mockReset();
});
@@ -92,6 +110,7 @@ describe("SQLReviewPage", () => {
expect(screen.queryByText("sql-review.description")).not.toBeInTheDocument();
expect(screen.queryByText("common.create")).not.toBeInTheDocument();
expect(mocks.fetchReviewPolicyList).not.toHaveBeenCalled();
+ expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(true);
});
test("keeps the v1 review policies without SQL Review V2", () => {
@@ -105,6 +124,30 @@ describe("SQLReviewPage", () => {
expect(screen.getByText("sql-review.description")).toBeInTheDocument();
expect(screen.getAllByText("common.create").length).toBeGreaterThan(0);
expect(mocks.fetchReviewPolicyList).toHaveBeenCalledTimes(1);
+ expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(false);
+ });
+
+ test("the footer saves the AI review policy when only it changed", async () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.aiReviewPolicy.isDirty = true;
+ render(<SQLReviewPage />);
+
+ await update();
+
+ expect(mocks.aiReviewPolicy.save).toHaveBeenCalledOnce();
+ expect(mocks.aiReview.save).not.toHaveBeenCalled();
+ expect(mocks.standardRules.save).not.toHaveBeenCalled();
+ expect(mocks.pushNotification).toHaveBeenCalledOnce();
+ });
+
+ test("the footer cannot update while the AI review policy is invalid", () => {
+ mocks.sqlReviewV2.value = true;
+ mocks.aiReviewPolicy.isDirty = true;
+ mocks.aiReviewPolicy.error = "too-large";
+ render(<SQLReviewPage />);
+
+ expect(screen.getByRole("button", { name: "common.update" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "common.cancel" })).toBeEnabled();
});
test("the footer saves only the part that changed", async () => {
@@ -119,26 +162,30 @@ describe("SQLReviewPage", () => {
expect(mocks.pushNotification).toHaveBeenCalledOnce();
});
- test("the footer saves both parts when both changed, and reports one update", async () => {
+ test("the footer saves every part that changed, and reports one update", async () => {
mocks.sqlReviewV2.value = true;
mocks.aiReview.isDirty = true;
mocks.standardRules.isDirty = true;
+ mocks.aiReviewPolicy.isDirty = true;
render(<SQLReviewPage />);
await update();
expect(mocks.aiReview.save).toHaveBeenCalledOnce();
expect(mocks.standardRules.save).toHaveBeenCalledOnce();
+ expect(mocks.aiReviewPolicy.save).toHaveBeenCalledOnce();
expect(mocks.pushNotification).toHaveBeenCalledOnce();
});
test.each([
["the AI review", mocks.aiReview],
["the standard rules", mocks.standardRules],
+ ["the AI review policy", mocks.aiReviewPolicy],
])("reports no update when %s fails to save", async (_, failing) => {
mocks.sqlReviewV2.value = true;
mocks.aiReview.isDirty = true;
mocks.standardRules.isDirty = true;
+ mocks.aiReviewPolicy.isDirty = true;
render(<SQLReviewPage />);
failing.save.mockResolvedValue(false);
@@ -146,10 +193,11 @@ describe("SQLReviewPage", () => {
expect(mocks.aiReview.save).toHaveBeenCalledOnce();
expect(mocks.standardRules.save).toHaveBeenCalledOnce();
+ expect(mocks.aiReviewPolicy.save).toHaveBeenCalledOnce();
expect(mocks.pushNotification).not.toHaveBeenCalled();
});
- test("cancel reverts both parts", () => {
+ test("cancel reverts every part", () => {
mocks.sqlReviewV2.value = true;
mocks.standardRules.isDirty = true;
render(<SQLReviewPage />);
@@ -158,12 +206,16 @@ describe("SQLReviewPage", () => {
expect(mocks.standardRules.revert).toHaveBeenCalledOnce();
expect(mocks.aiReview.revert).toHaveBeenCalledOnce();
+ expect(mocks.aiReviewPolicy.revert).toHaveBeenCalledOnce();
});
- test("the footer waits while either part is saving", () => {
+ test.each([
+ ["the AI review", mocks.aiReview],
+ ["the AI review policy", mocks.aiReviewPolicy],
+ ])("the footer waits while %s is saving", (_, saving) => {
mocks.sqlReviewV2.value = true;
mocks.standardRules.isDirty = true;
- mocks.aiReview.saving = true;
+ saving.saving = true;
render(<SQLReviewPage />);
expect(screen.getByRole("button", { name: "common.update" })).toBeDisabled();
diff --git a/frontend/src/routes/workspace/SQLReviewPage.tsx b/frontend/src/routes/workspace/SQLReviewPage.tsx
index b7f1e363e8..fd625d2af5 100644
--- a/frontend/src/routes/workspace/SQLReviewPage.tsx
+++ b/frontend/src/routes/workspace/SQLReviewPage.tsx
@@ -37,6 +37,7 @@ import { sqlReviewV2Enabled } from "@/utils/featureGates";
import {
SQLReviewAIReviewSection,
useWorkspaceAIReview,
+ useWorkspaceReviewAIPolicy,
} from "./SQLReviewAIReviewSection";
import {
SQLReviewStandardRulesSection,
@@ -268,8 +269,10 @@ export function SQLReviewPage() {
const sqlReviewV2 = sqlReviewV2Enabled();
const standardRules = useWorkspaceStandardRules(sqlReviewV2);
const aiReview = useWorkspaceAIReview();
- const isDirty = standardRules.isDirty || aiReview.isDirty;
- const saving = standardRules.saving || aiReview.saving;
+ const aiReviewPolicy = useWorkspaceReviewAIPolicy(sqlReviewV2);
+ const parts = [standardRules, aiReview, aiReviewPolicy];
+ const isDirty = parts.some((part) => part.isDirty);
+ const saving = parts.some((part) => part.saving);
useUnsavedChangesGuard(isDirty);
useEffect(() => {
@@ -310,7 +313,10 @@ export function SQLReviewPage() {
{sqlReviewV2 ? (
<div className={STANDARD_RULES_COLUMN}>
<SQLReviewStandardRulesSection standardRules={standardRules} />
- <SQLReviewAIReviewSection aiReview={aiReview} />
+ <SQLReviewAIReviewSection
+ aiReview={aiReview}
+ policy={aiReviewPolicy}
+ />
</div>
) : (
<>
@@ -362,8 +368,7 @@ export function SQLReviewPage() {
appearance="outline"
disabled={saving}
onClick={() => {
- standardRules.revert();
- aiReview.revert();
+ for (const part of parts) part.revert();
}}
>
{t("common.cancel")}
@@ -371,11 +376,11 @@ export function SQLReviewPage() {
}
right={
<Button
- disabled={saving}
+ disabled={saving || aiReviewPolicy.error !== undefined}
onClick={async () => {
- const saves: Promise<boolean>[] = [];
- if (standardRules.isDirty) saves.push(standardRules.save());
- if (aiReview.isDirty) saves.push(aiReview.save());
+ const saves = parts
+ .filter((part) => part.isDirty)
+ .map((part) => part.save());
// One click reports one update, and only when every changed
// part saved.
if ((await Promise.all(saves)).every(Boolean)) {
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
index 10a6e55990..c8d964f7fc 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -8,6 +8,7 @@ import {
} from "@/components/sql-review/standardRules";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
+import { FormSection } from "@/components/ui/form";
import { useWorkspaceResourceName } from "@/hooks/useAppState";
import { useAppStore } from "@/stores/app";
import {
@@ -124,15 +125,11 @@ export function SQLReviewStandardRulesSection({
const workspace = useWorkspaceResourceName();
return (
- <section className="flex flex-col gap-y-6 pt-8">
- <div className="flex flex-col gap-y-2">
- <h1 className="text-2xl font-bold text-main">
- {t("sql-review.standard-rules.self")}
- </h1>
- <p className="text-sm text-control-light">
- {t("sql-review.standard-rules.description")}
- </p>
- </div>
+ <FormSection
+ layout="single-column"
+ title={t("sql-review.standard-rules.self")}
+ description={t("sql-review.standard-rules.description")}
+ >
{standardRules.readFailed && (
<Alert
variant="error"
@@ -157,6 +154,6 @@ export function SQLReviewStandardRulesSection({
disabled={!standardRules.canEdit || standardRules.saving}
/>
)}
- </section>
+ </FormSection>
);
}
diff --git a/frontend/src/stores/app/policy.test.ts b/frontend/src/stores/app/policy.test.ts
index 95b635f27e..9fd79ffa78 100644
--- a/frontend/src/stores/app/policy.test.ts
+++ b/frontend/src/stores/app/policy.test.ts
@@ -6,6 +6,7 @@ import {
PolicyResourceType,
PolicySchema,
PolicyType,
+ ReviewAIPolicySchema,
ReviewRulePolicySchema,
type UpdatePolicyRequest,
} from "@/types/proto-es/v1/org_policy_service_pb";
@@ -84,6 +85,39 @@ describe("policy store", () => {
).toEqual(expect.objectContaining({ rules: [ReviewRuleType.SYNTAX] }));
});
+ test("upserts an AI review policy under policies/review_ai, leaving enforce as stored", async () => {
+ const store = createStore();
+
+ await store.upsertPolicy({
+ parentPath: "workspaces/ws",
+ policy: {
+ type: PolicyType.REVIEW_AI,
+ resourceType: PolicyResourceType.WORKSPACE,
+ enforce: true,
+ policy: {
+ case: "reviewAiPolicy",
+ value: create(ReviewAIPolicySchema, { content: "No DROP." }),
+ },
+ },
+ });
+
+ const request = mocks.updatePolicy.mock.calls[0][0] as UpdatePolicyRequest;
+ expect(request.policy?.name).toBe("workspaces/ws/policies/review_ai");
+ expect(request.policy?.type).toBe(PolicyType.REVIEW_AI);
+ expect(request.policy?.policy.case).toBe("reviewAiPolicy");
+ expect(request.policy?.policy.value).toEqual(
+ expect.objectContaining({ content: "No DROP." })
+ );
+ expect(request.updateMask?.paths).toEqual(["review_ai_policy"]);
+ expect(request.allowMissing).toBe(true);
+ expect(
+ store.getPolicyByParentAndType({
+ parentPath: "workspaces/ws",
+ policyType: PolicyType.REVIEW_AI,
+ })?.policy.value
+ ).toEqual(expect.objectContaining({ content: "No DROP." }));
+ });
+
test("fetches a policy, and tells an absent one from a failed read", async () => {
const store = createStore();
const find = {
diff --git a/frontend/src/stores/app/policy.ts b/frontend/src/stores/app/policy.ts
index 80c21aedc3..25aa9c14d2 100644
--- a/frontend/src/stores/app/policy.ts
+++ b/frontend/src/stores/app/policy.ts
@@ -35,6 +35,9 @@ const getUpdateMaskFromPolicyType = (policyType: PolicyType): string[] => {
PolicySchema.field.reviewRulePolicy.name,
PolicySchema.field.enforce.name,
];
+ case PolicyType.REVIEW_AI:
+ // Saving the text leaves a policy paused through the API paused.
+ return [PolicySchema.field.reviewAiPolicy.name];
default:
throw new Error(`unexpected policy type ${policyType}`);
}