Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: some ux change for sql review (#21614)
ecmadao7b221e88506d
diff --git a/backend/api/v1/auth_service.go b/backend/api/v1/auth_service.goindex d10d16b2f2..6ad8e5f45d 100644--- a/backend/api/v1/auth_service.go+++ b/backend/api/v1/auth_service.go@@ -1318,11 +1318,12 @@ func (*AuthService) getAdditionalWorkspaceSettings() []store.AdditionalSetting {settings = append(settings, store.AdditionalSetting{Name: storepb.SettingName_AI,Payload: &storepb.AISetting{- Enabled: true,- Provider: storepb.AISetting_GEMINI,- ApiKey: geminiAPIKey,- Endpoint: "https://generativelanguage.googleapis.com/v1beta",- Model: "gemini-3.7-flash",+ Enabled: true,+ Provider: storepb.AISetting_GEMINI,+ ApiKey: geminiAPIKey,+ Endpoint: "https://generativelanguage.googleapis.com/v1beta",+ Model: "gemini-3.7-flash",+ SqlReviewEnabled: true,},})}diff --git a/backend/api/v1/setting_service.go b/backend/api/v1/setting_service.goindex df7a7a3751..e6e6b22bea 100644--- a/backend/api/v1/setting_service.go+++ b/backend/api/v1/setting_service.go@@ -468,14 +468,14 @@ func (s *SettingService) UpdateSetting(ctx context.Context, request *connect.Req// turning AI or the AI SQL review back on after another admin turned it off.// Workspace creation does not seed this row, so a missing row starts empty.func (s *SettingService) updateAISetting(ctx context.Context, request *connect.Request[v1pb.UpdateSettingRequest], workspaceID string) (*connect.Response[v1pb.Setting], error) {- if s.profile.SaaS {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("the AI setting cannot be changed in SaaS mode"))- }if request.Msg.UpdateMask == nil {return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("update mask is required"))}payload := convertAISetting(request.Msg.Setting.Value.GetAi())paths := request.Msg.UpdateMask.Paths+ if s.profile.SaaS && !canUpdateAISettingInSaaS(paths) {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("only the AI SQL review can be changed in SaaS mode"))+ }if request.Msg.ValidateOnly {stored, err := s.store.GetAISettingUncached(ctx, workspaceID)@@ -537,6 +537,10 @@ func (s *SettingService) updateAISetting(ctx context.Context, request *connect.Rreturn connect.NewResponse(settingMessage), nil}+func canUpdateAISettingInSaaS(paths []string) bool {+ return len(paths) == 1 && paths[0] == "value.ai.sql_review_enabled"+}+// mergeAISetting applies the update mask to a copy of stored and validates// the result.func mergeAISetting(stored, payload *storepb.AISetting, paths []string) (*storepb.AISetting, error) {diff --git a/backend/api/v1/setting_service_test.go b/backend/api/v1/setting_service_test.goindex 9c86f9e4be..3964e7e74d 100644--- a/backend/api/v1/setting_service_test.go+++ b/backend/api/v1/setting_service_test.go@@ -389,3 +389,41 @@ func TestMergeAISetting(t *testing.T) {require.Equal(t, "stored-key", merged.ApiKey)})}++func TestCanUpdateAISettingInSaaS(t *testing.T) {+ t.Parallel()++ testCases := []struct {+ name string+ paths []string+ want bool+ }{+ {+ name: "allows the AI SQL review switch",+ paths: []string{"value.ai.sql_review_enabled"},+ want: true,+ },+ {+ name: "rejects enabling the AI assistant",+ paths: []string{"value.ai.enabled"},+ },+ {+ name: "rejects provider credentials",+ paths: []string{"value.ai.api_key"},+ },+ {+ name: "rejects a mixed update",+ paths: []string{"value.ai.sql_review_enabled", "value.ai.model"},+ },+ {+ name: "rejects an empty update",+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ require.Equal(t, tc.want, canUpdateAISettingInSaaS(tc.paths))+ })+ }+}diff --git a/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx b/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsxindex 2141cfea9c..e3b46ed84e 100644--- a/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx+++ b/frontend/src/components/sql-review/ReviewAIPolicyField.test.tsx@@ -1,4 +1,5 @@import { create } from "@bufbuild/protobuf";+import * as stylex from "@stylexjs/stylex";import { act, fireEvent, render, screen } from "@testing-library/react";import { useState } from "react";import { beforeEach, describe, expect, test, vi } from "vitest";@@ -9,6 +10,7 @@ import {PolicyType,ReviewAIPolicySchema,} from "@/types/proto-es/v1/org_policy_service_pb";+import { formFieldSectionGapStyle } from "@/components/ui/styles.stylex";const PARENT = "projects/p";const POLICY_NAME = `${PARENT}/policies/review_ai`;@@ -175,6 +177,24 @@ describe("ReviewAIPolicyField", () => {expect(screen.getByText("clean")).toBeInTheDocument();});+ test("describes how the AI uses the policy", () => {+ render(<Harness />);++ expect(+ screen.getByText("sql-review.ai-review.policy.description")+ ).toBeInTheDocument();+ });++ test("keeps the policy control aligned with its section header", async () => {+ render(<Harness />);++ expect(+ (await editor()).closest('[data-slot="form-field"]')+ ).toHaveClass(+ stylex.props(formFieldSectionGapStyle()).className ?? ""+ );+ });+test("a missing policy starts empty with example text, and a save creates it enforced", async () => {render(<Harness />);diff --git a/frontend/src/components/sql-review/ReviewAIPolicyField.tsx b/frontend/src/components/sql-review/ReviewAIPolicyField.tsxindex 2558afcfee..31657b9e2a 100644--- a/frontend/src/components/sql-review/ReviewAIPolicyField.tsx+++ b/frontend/src/components/sql-review/ReviewAIPolicyField.tsx@@ -1,5 +1,5 @@import { create } from "@bufbuild/protobuf";-import { useEffect, useId, useState } from "react";+import { type ReactNode, useEffect, useId, useState } from "react";import { useTranslation } from "react-i18next";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -175,10 +175,16 @@ export function useReviewAIPolicyDraft({export function ReviewAIPolicyField({policy,placeholder,+ title,+ description,+ emptyText,}: {policy: ReviewAIPolicyDraft;// Example rules for this level, shown while the field is empty.placeholder: string;+ title?: ReactNode;+ description?: ReactNode;+ emptyText?: ReactNode;}) {const { t } = useTranslation();const id = useId();@@ -200,7 +206,13 @@ export function ReviewAIPolicyField({return (<FormField- title={<span id={titleId}>{t("sql-review.ai-review.policy.self")}</span>}+ spacing="section"+ title={+ <span id={titleId}>+ {title ?? t("sql-review.ai-review.policy.self")}+ </span>+ }+ description={description ?? t("sql-review.ai-review.policy.description")}><FormControlGroup>{policy.loaded && policy.paused && (@@ -229,7 +241,7 @@ export function ReviewAIPolicyField({</p>) : (<p className="text-sm text-control-light">- {t("sql-review.ai-review.policy.none")}+ {emptyText ?? t("sql-review.ai-review.policy.none")}</p>)}</FormControlGroup>diff --git a/frontend/src/components/ui/form.test.tsx b/frontend/src/components/ui/form.test.tsxindex 2742c281de..2e42fdfe1a 100644--- a/frontend/src/components/ui/form.test.tsx+++ b/frontend/src/components/ui/form.test.tsx@@ -22,6 +22,7 @@ import {formControlRowStyle,formErrorStyle,formFieldGroupStyle,+ formFieldSectionGapStyle,formFieldTitleStyle,formLabelStyle,formSectionDescriptionStyle,@@ -111,6 +112,23 @@ describe("FormError", () => {unmount();});++ test("supports section spacing between a field header and its control", () => {+ const { container, unmount } = renderIntoContainer(+ createElement(+ FormField,+ { title: "Review policy", spacing: "section" },+ createElement("textarea")+ )+ );++ const field = container.querySelector('[data-slot="form-field"]');+ expect(field?.className).toContain(+ stylex.props(formFieldSectionGapStyle()).className ?? ""+ );++ unmount();+ });});describe("Form control layouts", () => {diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsxindex 986b93012a..49ff63903b 100644--- a/frontend/src/components/ui/form.tsx+++ b/frontend/src/components/ui/form.tsx@@ -24,12 +24,14 @@ import {formFieldGroupStyle,formFieldHeaderStyle,formFieldHorizontalStyle,+ formFieldSectionGapStyle,formFieldStyle,formFieldTitleStyle,formLabelStyle,formSectionContentStyle,formSectionDescriptionStyle,formSectionHeaderStyle,+ formSectionNoPaddingStyle,formSectionStyle,formSectionTitleStyle,singleColumnFormContentStyle,@@ -136,6 +138,8 @@ interface FormFieldProps extends Omit<ComponentProps<"div">, "title"> {title?: ReactNode;description?: ReactNode;layout?: FormLayout;+ /** Uses section-level spacing between the field header and its control. */+ spacing?: "default" | "section";}/**@@ -158,12 +162,14 @@ function FormField({style,title,layout: layoutOverride,+ spacing = "default",...props}: FormFieldProps) {const inherited = useContext(FormLayoutContext);const layout = layoutOverride ?? inherited.layout;const fieldStylexProps = stylex.props(formFieldStyle(),+ spacing === "section" && formFieldSectionGapStyle(),(title !== undefined ||Children.toArray(children).some((child) =>@@ -305,6 +311,8 @@ function FormFieldGroup({interface FormSectionProps extends Omit<ComponentProps<"section">, "title"> {title: ReactNode;description?: ReactNode;+ /** Removes the section's outer vertical padding when its page layout owns spacing. */+ padding?: "default" | "none";/*** - `default`: on large screens the header takes a 25% column beside the* content; on smaller screens it stacks above.@@ -360,10 +368,14 @@ function FormSection({title,description,layout = "default",+ padding = "default",...props}: FormSectionProps) {const styles = formSectionLayoutStyles[layout];- const sectionStylexProps = stylex.props(styles.section());+ const sectionStylexProps = stylex.props(+ styles.section(),+ padding === "none" && formSectionNoPaddingStyle()+ );const headerStylexProps = stylex.props(styles.header());const titleStylexProps = stylex.props(styles.title());const descriptionStylexProps = stylex.props(formSectionDescriptionStyle());diff --git a/frontend/src/components/ui/styles.stylex.ts b/frontend/src/components/ui/styles.stylex.tsindex 6fd5723426..1c57896907 100644--- a/frontend/src/components/ui/styles.stylex.ts+++ b/frontend/src/components/ui/styles.stylex.ts@@ -218,6 +218,9 @@ const formStyles = stylex.create({flexDirection: "column",rowGap: 6,},+ fieldSectionGap: {+ rowGap: 16,+ },fieldHorizontal: {alignItems: "start",columnGap: 16,@@ -329,6 +332,10 @@ export function formFieldStyle() {return formStyles.field;}+export function formFieldSectionGapStyle() {+ return formStyles.fieldSectionGap;+}+export function formFieldHorizontalStyle() {return formStyles.fieldHorizontal;}@@ -378,6 +385,16 @@ export function formSectionStyle() {return formStyles.section;}+const formSectionNoPaddingStyles = stylex.create({+ root: {+ paddingBlock: 0,+ },+});++export function formSectionNoPaddingStyle() {+ return formSectionNoPaddingStyles.root;+}+export function formSectionHeaderStyle() {return formStyles.sectionHeader;}diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex 08a5959f65..cec3f576ae 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -10,16 +10,20 @@},"policy": {"cannot-clear": "Your role cannot delete policies, so this policy cannot be emptied.",+ "description": "Instructions the AI follows when reviewing database changes.","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-description": "Optional project-specific instructions. They are added to the workspace policy and take precedence when they conflict.",+ "project-none": "No project instructions.","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.",+ "project-self": "Project additions","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.",+ "project-description": "AI review is configured for the workspace. Add optional instructions for this project below.","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.jsonindex 83e2510cb1..07df15a833 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -10,16 +10,20 @@},"policy": {"cannot-clear": "Tu rol no puede eliminar políticas, por lo que esta política no se puede vaciar.",+ "description": "Instrucciones que la IA sigue al revisar cambios en la base de datos.","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-description": "Instrucciones opcionales específicas del proyecto. Se agregan a la política del espacio de trabajo y tienen prioridad cuando entran en conflicto.",+ "project-none": "No hay instrucciones del proyecto.","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.",+ "project-self": "Adiciones del proyecto","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.",+ "project-description": "La revisión con IA se configura para el espacio de trabajo. Agrega abajo instrucciones opcionales para este proyecto.","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.jsonindex 2be11426fe..e47b8532e6 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -10,16 +10,20 @@},"policy": {"cannot-clear": "ロールにポリシーの削除権限がないため、このポリシーを空にできません。",+ "description": "AI がデータベース変更をレビューするときに従う指示。","load-failed": "レビューポリシーを読み込めませんでした。","none": "レビューポリシーはありません。","paused": "このポリシーは一時停止中のため、AI レビューでは読み込まれません。","placeholder": "例:\n100 万行を超えるテーブルで書き込みをブロックするスキーマ変更を指摘する。\nすべての外部キーの列にインデックスを必須とする。\n新しいテーブルには created_at 列と updated_at 列を必須とする。",+ "project-description": "任意のプロジェクト固有の指示です。ワークスペースポリシーに追加され、競合する場合は優先されます。",+ "project-none": "プロジェクトの指示はありません。","project-placeholder": "例:\npayments テーブルと ledger テーブルの行は削除しない。\n金額は DECIMAL 列に保存し、FLOAT や DOUBLE は使わない。\nusers テーブルに追加する列は NULL を許可するか、デフォルト値を持つこと。",+ "project-self": "プロジェクトの追加指示","remove-only": "このポリシーは削除できますが、変更はできません。削除するにはテキストを空にしてください。","self": "レビューポリシー","too-large": "ポリシーのサイズは {{size}} バイトで、上限の {{limit}} バイトを超えています。短くしてから保存してください。"},- "project-description": "AI モデルが Issue の SQL をレビューし、標準ルールでは検出できないリスクを見つけます。このプロジェクトのポリシーはワークスペースのポリシーに追加され、両者が矛盾する場合はこちらが優先されます。",+ "project-description": "AI レビューはワークスペースで設定されます。以下でこのプロジェクト向けの任意の指示を追加できます。","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.jsonindex a4c36130cb..3fb11487a5 100644--- a/frontend/src/locales/sql-review/vi-VN.json+++ b/frontend/src/locales/sql-review/vi-VN.json@@ -10,16 +10,20 @@},"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.",+ "description": "Hướng dẫn mà AI tuân theo khi đánh giá các thay đổi cơ sở dữ liệu.","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-description": "Hướng dẫn tùy chọn dành riêng cho dự án. Chúng được thêm vào chính sách không gian làm việc và được ưu tiên khi có xung đột.",+ "project-none": "Chưa có hướng dẫn dự án.","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.",+ "project-self": "Phần bổ sung của dự án","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.",+ "project-description": "Tính năng đánh giá bằng AI được cấu hình cho không gian làm việc. Hãy thêm hướng dẫn tùy chọn cho dự án này bên dưới.","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.jsonindex 4aeff1e12f..404d9fd5c3 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -10,16 +10,20 @@},"policy": {"cannot-clear": "你的角色无法删除策略,因此不能清空此策略。",+ "description": "AI 审核数据库变更时遵循的说明。","load-failed": "审核策略加载失败。","none": "未设置审核策略。","paused": "此策略已暂停,AI 审核不会读取它。","placeholder": "例如:\n标记在超过 100 万行的表上会阻塞写入的结构变更。\n每个外键的列都必须有索引。\n新建的表必须包含 created_at 列和 updated_at 列。",+ "project-description": "可选的项目专属说明。这些说明会添加到工作空间策略中;如有冲突则优先。",+ "project-none": "未设置项目说明。","project-placeholder": "例如:\n禁止删除 payments 表或 ledger 表中的行。\n金额必须存放在 DECIMAL 列中,不能使用 FLOAT 或 DOUBLE。\nusers 表新增的列必须允许 NULL 或带有默认值。",+ "project-self": "项目补充说明","remove-only": "你可以删除此策略,但不能修改它。清空文本即可删除。","self": "审核策略","too-large": "策略大小为 {{size}} 字节,超过了 {{limit}} 字节的上限。请缩短后再保存。"},- "project-description": "由 AI 模型审核工单中的 SQL,发现标准规则无法识别的风险。本项目的策略会追加到工作空间策略之上,两者冲突时以本项目的策略为准。",+ "project-description": "AI 审核在工作空间中配置。请在下方添加本项目的可选说明。","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.tsxindex df221631a5..05af831986 100644--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx@@ -1,4 +1,5 @@import { create } from "@bufbuild/protobuf";+import * as stylex from "@stylexjs/stylex";import {act,fireEvent,@@ -17,6 +18,7 @@ import {ReviewRulePolicySchema,} from "@/types/proto-es/v1/org_policy_service_pb";import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";+import { formFieldSectionGapStyle } from "@/components/ui/styles.stylex";const WORKSPACE = "workspaces/ws";const PROJECT = "projects/p";@@ -214,7 +216,9 @@ const updateButton = () =>screen.queryByRole("button", { name: "common.update" });const policyEditor = () =>- screen.findByRole("textbox", { name: "sql-review.ai-review.policy.self" });+ screen.findByRole("textbox", {+ name: "sql-review.ai-review.policy.project-self",+ });const update = () =>act(async () => {@@ -231,7 +235,7 @@ describe("ProjectSQLReviewPage", () => {mocks.fetchPolicy.mockReset();mocks.pushNotification.mockReset();seedPolicies({ [WORKSPACE]: workspacePolicy() });- seedServerInfo(undefined);+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });});// The row of the AI review: its title, its description, and its state.@@ -254,13 +258,36 @@ describe("ProjectSQLReviewPage", () => {})).toBeInTheDocument();expect(- aiReviewRow().getByRole("link", {+ await screen.findByRole("link", {name: "sql-review.ai-review.view-workspace-setting",})).toBeInTheDocument();expect(aiReviewRow().queryByRole("switch")).not.toBeInTheDocument();});+ test("uses the normal project page width for SQL Review", async () => {+ const { container } = render(<ProjectSQLReviewPage projectId="p" />);+ await screen.findByRole("switch", {+ name: "sql-review.standard-rules.customize.self",+ });++ const page = container.querySelector('[data-slot="project-page-layout"]');+ expect(page?.firstElementChild).not.toHaveClass("mx-auto", "max-w-3xl");+ });++ test("does not add outer padding around the Standard rules section", async () => {+ render(<ProjectSQLReviewPage projectId="p" />);+ await screen.findByRole("switch", {+ name: "sql-review.standard-rules.customize.self",+ });++ const section = screen+ .getByRole("heading", { name: "sql-review.standard-rules.self" })+ .closest('[data-slot="form-section"]');+ expect(getComputedStyle(section!).paddingTop).toBe("0");+ expect(getComputedStyle(section!).paddingBottom).toBe("0");+ });+test.each([["the workspace has it off", { aiEnabled: true, aiSqlReviewEnabled: false }],["AI is off for the workspace", { aiEnabled: false, aiSqlReviewEnabled: true }],@@ -271,6 +298,9 @@ describe("ProjectSQLReviewPage", () => {expect(aiReviewRow().getByText("sql-review.standard-rules.off")).toBeInTheDocument();+ expect(+ screen.queryByText("sql-review.ai-review.policy.self")+ ).not.toBeInTheDocument();});test("the workspace setting link of the AI review needs the workspace policy read", async () => {@@ -280,16 +310,38 @@ describe("ProjectSQLReviewPage", () => {expect(aiReviewRow().queryByRole("link")).not.toBeInTheDocument();});+ test("uses the shared project policy editor without duplicating the workspace policy", async () => {+ seedPolicies({+ [WORKSPACE]: workspacePolicy(),+ ai: reviewAIPolicy(WORKSPACE, "Every foreign key needs an index."),+ });+ render(<ProjectSQLReviewPage projectId="p" />);++ expect(+ screen.queryByText("Every foreign key needs an index.")+ ).not.toBeInTheDocument();+ expect(+ screen.getByText("sql-review.ai-review.policy.project-description")+ ).toBeInTheDocument();+ const projectPolicyEditor = await policyEditor();+ expect(projectPolicyEditor).not.toHaveAttribute("readonly");+ expect(+ projectPolicyEditor.closest('[data-slot="form-field"]')+ ).toHaveClass(+ stylex.props(formFieldSectionGapStyle()).className ?? ""+ );+ });+test("a project without its own policy shows the workspace rules as text", async () => {const customize = await renderLoaded();expect(customize).toHaveAttribute("aria-checked", "false");// Only the customize control is a switch; the rules are read-only.expect(screen.getAllByRole("switch")).toHaveLength(1);- expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(2);+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(3);// Nine rules, and the AI review row below them.expect(screen.getAllByText("sql-review.standard-rules.off")).toHaveLength(- 10+ 9);expect(screen.getByText("sql-review.standard-rules.running")@@ -403,7 +455,7 @@ describe("ProjectSQLReviewPage", () => {expect(customize).toHaveAttribute("aria-checked", "false");expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(- 11+ 12);fireEvent.click(customize);expect(ruleSwitch("disallow-truncate")).toHaveAttribute(@@ -549,9 +601,7 @@ describe("ProjectSQLReviewPage", () => {expect(screen.queryByRole("alert")).toHaveTextContent("sql-review.standard-rules.workspace-rules-hidden");- expect(- screen.queryByText("sql-review.standard-rules.on")- ).not.toBeInTheDocument();+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(1);expect(screen.queryByText("sql-review.standard-rules.customize.view-workspace-rules"@@ -584,7 +634,7 @@ describe("ProjectSQLReviewPage", () => {fireEvent.click(ruleSwitch("syntax"));fireEvent.click(customize);- expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(2);+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(3);fireEvent.click(customize);fireEvent.click(ruleSwitch("syntax"));@@ -748,7 +798,7 @@ describe("ProjectSQLReviewPage", () => {render(<ProjectSQLReviewPage projectId="p" />);expect(- await screen.findByText("sql-review.ai-review.policy.none")+ await screen.findByText("sql-review.ai-review.policy.project-none")).toBeInTheDocument();expect(screen.queryByRole("textbox")).not.toBeInTheDocument();});diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsxindex 345cde2813..8ca8d8e326 100644--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx@@ -197,10 +197,6 @@ export function useProjectStandardRules(};}-// The rules read as one centered column, and the footer lines its actions up-// with it.-const STANDARD_RULES_COLUMN = "mx-auto w-full max-w-3xl";-export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {const { t } = useTranslation();const projectName = `${projectNamePrefix}${projectId}`;@@ -208,10 +204,19 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {const can = (permission: Permission) =>hasProjectPermissionV2(project, permission);const standardRules = useProjectStandardRules(projectName);+ // The AI review is switched for the whole workspace, and it runs only+ // while AI itself is on.+ const aiReviewOn = useAppStore(+ (state) =>+ state.serverInfo?.aiEnabled === true &&+ state.serverInfo?.aiSqlReviewEnabled === true+ );+ const canViewWorkspaceRules = hasWorkspacePermissionV2("bb.policies.get");const aiReviewPolicy = useReviewAIPolicyDraft({parentPath: projectName,resourceType: PolicyResourceType.PROJECT,can,+ enabled: aiReviewOn,});const parts = [standardRules, aiReviewPolicy];const isDirty = parts.some((part) => part.isDirty);@@ -228,98 +233,37 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {const customizeLocked = standardRules.customized? standardRules.storedCustomized && !can("bb.policies.delete"): !standardRules.storedCustomized && !canSave;- // The V2 workspace route needs only the policy read.- const canViewWorkspaceRules = hasWorkspacePermissionV2("bb.policies.get");- // The AI review is switched for the whole workspace, and it runs only- // while AI itself is on.- const aiReviewOn = useAppStore(- (state) =>- state.serverInfo?.aiEnabled === true &&- state.serverInfo?.aiSqlReviewEnabled === true- );-return (<ProjectPageLayout>- <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")}+ <FormSection+ layout="single-column"+ padding="none"+ 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")}+ >+ <Button+ className="mt-3"+ appearance="outline"+ size="sm"+ onClick={standardRules.reload}>- <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>+ {t("sql-review.standard-rules.retry")}+ </Button>+ </Alert>+ )}+ {standardRules.loaded && (+ <><SwitchRowclassName="rounded-sm border border-block-border px-4 py-3"- title={t("sql-review.ai-review.enable.self")}+ title={t("sql-review.standard-rules.customize.self")}description={<>- {t("sql-review.ai-review.set-for-workspace")}+ {t("sql-review.standard-rules.customize.description")}{canViewWorkspaceRules && (<>{" "}@@ -327,28 +271,83 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {to={{ name: WORKSPACE_ROUTE_SQL_REVIEW }}className="text-accent hover:underline">- {t("sql-review.ai-review.view-workspace-setting")}+ {t(+ "sql-review.standard-rules.customize.view-workspace-rules"+ )}</RouterLink></>)}</>}- checked={aiReviewOn}- onCheckedChange={() => {}}- readOnly+ 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"+ padding="none"+ 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.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+ />+ {aiReviewOn && (<ReviewAIPolicyFieldpolicy={aiReviewPolicy}placeholder={t("sql-review.ai-review.policy.project-placeholder")}+ title={t("sql-review.ai-review.policy.project-self")}+ description={t("sql-review.ai-review.policy.project-description")}+ emptyText={t("sql-review.ai-review.policy.project-none")}/>- </FormFieldGroup>- </FormSection>- </div>+ )}+ </FormFieldGroup>+ </FormSection>{isDirty && (<StickyActionFootercontentPadding={false}- contentClassName={STANDARD_RULES_COLUMN}left={<Buttonappearance="outline"diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsxindex 50cf5e68eb..8f547956d9 100644--- a/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.test.tsx@@ -2,6 +2,11 @@ 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 { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/app/router/handles";+import {+ AI_ASSISTANT_PRODUCT_INTRO,+ PRODUCT_INTRO_QUERY_KEY,+} from "@/lib/productIntro";import {type Policy,PolicyResourceType,@@ -40,8 +45,10 @@ vi.mock("@/utils", () => ({vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));vi.mock("@/components/RouterLink", () => ({- RouterLink: ({ children }: { children: ReactNode }) => (- <a href="/">{children}</a>+ RouterLink: ({ children, to }: { children: ReactNode; to: object }) => (+ <a href="/" data-route={JSON.stringify(to)}>+ {children}+ </a>),}));@@ -192,6 +199,7 @@ describe("SQLReviewAIReviewSection", () => {});test("loads the workspace policy, and saves an edit under the workspace", async () => {+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });seedPolicies({[`${WORKSPACE}/policies/review_ai`]: workspacePolicy("No DROP."),});@@ -224,6 +232,7 @@ describe("SQLReviewAIReviewSection", () => {});test("a failed policy save keeps the edit", async () => {+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });mocks.upsertPolicy.mockRejectedValueOnce(new Error("denied"));render(<Harness />);@@ -239,6 +248,7 @@ describe("SQLReviewAIReviewSection", () => {});test("shows the workspace policy as text without bb.policies.update or bb.policies.delete", async () => {+ seedServerInfo({ aiEnabled: true, aiSqlReviewEnabled: true });mocks.permissions["bb.policies.update"] = false;mocks.permissions["bb.policies.delete"] = false;seedPolicies({@@ -320,26 +330,50 @@ describe("SQLReviewAIReviewSection", () => {expect(screen.getByText("sql-review.standard-rules.on")).toBeInTheDocument();});- test("shows the state as text in SaaS mode, where the AI setting is read only", () => {+ test("allows switching the AI review in SaaS mode", () => {mocks.saas.value = true;render(<Harness />);- expect(screen.queryByRole("switch")).not.toBeInTheDocument();+ expect(screen.getByRole("switch", SWITCH)).toHaveAttribute(+ "aria-checked",+ "false"+ );+ });++ test("hides the policy while AI review is off", async () => {+ render(<Harness />);+ await act(async () => {});+expect(- screen.getByText("sql-review.standard-rules.off")- ).toBeInTheDocument();+ screen.queryByText("sql-review.ai-review.policy.self")+ ).not.toBeInTheDocument();});- test("warns while AI is off for the workspace, with a link to turn it on", () => {+ test("shows the AI review as off and hides its policy while AI is off", () => {seedServerInfo({ aiEnabled: false, aiSqlReviewEnabled: true });render(<Harness />);expect(screen.getByText("sql-review.ai-review.ai-off")).toBeInTheDocument();+ const link = screen.getByRole("link", {+ name: "sql-review.ai-review.turn-on-ai",+ });+ expect(link).toBeInTheDocument();+ expect(JSON.parse(link.getAttribute("data-route")!)).toEqual({+ name: SETTING_ROUTE_WORKSPACE_GENERAL,+ hash: "#ai-assistant",+ query: {+ [PRODUCT_INTRO_QUERY_KEY]: AI_ASSISTANT_PRODUCT_INTRO,+ },+ });+ expect(screen.queryByRole("switch", SWITCH)).not.toBeInTheDocument();expect(- screen.getByRole("link", { name: "sql-review.ai-review.turn-on-ai" })+ screen.getByText("sql-review.standard-rules.off")).toBeInTheDocument();+ expect(+ screen.queryByText("sql-review.ai-review.policy.self")+ ).not.toBeInTheDocument();});test.each([diff --git a/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsxindex 882dac4103..701914aa9a 100644--- a/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx+++ b/frontend/src/routes/workspace/SQLReviewAIReviewSection.tsx@@ -13,6 +13,10 @@ import { SwitchRow } from "@/components/sql-review/SwitchRow";import { Alert } from "@/components/ui/alert";import { FormFieldGroup, FormSection } from "@/components/ui/form";import { useServerState, useWorkspaceResourceName } from "@/hooks/useAppState";+import {+ AI_ASSISTANT_PRODUCT_INTRO,+ PRODUCT_INTRO_QUERY_KEY,+} from "@/lib/productIntro";import { useAppStore } from "@/stores/app";import { PolicyResourceType } from "@/types/proto-es/v1/org_policy_service_pb";import {@@ -28,7 +32,7 @@ export interface WorkspaceAIReview {// Whether AI is on for the workspace. While it is off no review runs,// whatever the switch says.aiEnabled: boolean;- // The switch is a field of the AI setting, which SaaS keeps read only.+ // The switch is a field of the AI setting.canEdit: boolean;setEnabled: (enabled: boolean) => void;isDirty: boolean;@@ -42,7 +46,6 @@ export interface WorkspaceAIReview {// The page owns the draft so the switch saves with the standard rules, from// the one sticky footer.export function useWorkspaceAIReview(): WorkspaceAIReview {- const { isSaaSMode } = useServerState();// The server info carries both flags, so a user who cannot read the AI// setting still sees whether the review is on.const stored = useAppStore(@@ -84,7 +87,7 @@ export function useWorkspaceAIReview(): WorkspaceAIReview {return {enabled: draft ?? stored,aiEnabled,- canEdit: hasWorkspacePermissionV2("bb.settings.set") && !isSaaSMode,+ canEdit: aiEnabled && hasWorkspacePermissionV2("bb.settings.set"),setEnabled: setDraft,isDirty,saving,@@ -115,16 +118,19 @@ export function SQLReviewAIReviewSection({policy: ReviewAIPolicyDraft;}) {const { t } = useTranslation();+ const { isSaaSMode } = useServerState();// AI is turned on in the general settings, whose AI section shows its// controls only to a user who can open that page and read the AI setting.const canTurnOnAI =- aiReview.canEdit &&+ !isSaaSMode &&+ hasWorkspacePermissionV2("bb.settings.set") &&hasWorkspacePermissionV2("bb.settings.get") &&hasWorkspacePermissionV2("bb.settings.getWorkspaceProfile");return (<FormSectionlayout="single-column"+ padding="none"title={t("sql-review.ai-review.self")}description={t("sql-review.ai-review.description")}>@@ -141,6 +147,9 @@ export function SQLReviewAIReviewSection({to={{name: SETTING_ROUTE_WORKSPACE_GENERAL,hash: "#ai-assistant",+ query: {+ [PRODUCT_INTRO_QUERY_KEY]: AI_ASSISTANT_PRODUCT_INTRO,+ },}}className="text-accent hover:underline">@@ -157,15 +166,17 @@ export function SQLReviewAIReviewSection({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}+ checked={aiReview.aiEnabled && aiReview.enabled}onCheckedChange={aiReview.setEnabled}disabled={aiReview.saving}readOnly={!aiReview.canEdit}/>- <ReviewAIPolicyField- policy={policy}- placeholder={t("sql-review.ai-review.policy.placeholder")}- />+ {aiReview.aiEnabled && aiReview.enabled && (+ <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.tsxindex 919a8e7edd..340a8e8e9d 100644--- a/frontend/src/routes/workspace/SQLReviewPage.test.tsx+++ b/frontend/src/routes/workspace/SQLReviewPage.test.tsx@@ -13,7 +13,14 @@ const mocks = vi.hoisted(() => ({revert: vi.fn(),save: vi.fn(),},- aiReview: { isDirty: false, saving: false, revert: vi.fn(), save: vi.fn() },+ aiReview: {+ aiEnabled: true,+ enabled: true,+ isDirty: false,+ saving: false,+ revert: vi.fn(),+ save: vi.fn(),+ },aiReviewPolicy: {isDirty: false,saving: false,@@ -94,6 +101,8 @@ describe("SQLReviewPage", () => {part.save.mockReset().mockResolvedValue(true);}mocks.aiReviewPolicy.error = undefined;+ mocks.aiReview.aiEnabled = true;+ mocks.aiReview.enabled = true;mocks.aiReviewPolicyEnabled.mockReset();mocks.pushNotification.mockReset();});@@ -113,6 +122,18 @@ describe("SQLReviewPage", () => {expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(true);});+ test("uses the normal workspace page width for SQL Review V2", () => {+ mocks.sqlReviewV2.value = true;+ const { container } = render(<SQLReviewPage />);++ expect(+ screen.getByText("standard-rules-section").parentElement+ ).not.toHaveClass("mx-auto", "max-w-3xl");+ expect(+ container.querySelector('[data-slot="workspace-page-layout"]')+ ).toContainElement(screen.getByText("standard-rules-section"));+ });+test("keeps the v1 review policies without SQL Review V2", () => {mocks.sqlReviewV2.value = false;render(<SQLReviewPage />);@@ -127,6 +148,14 @@ describe("SQLReviewPage", () => {expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(false);});+ test("keeps the review policy draft mounted while AI is unavailable", () => {+ mocks.sqlReviewV2.value = true;+ mocks.aiReview.aiEnabled = false;+ render(<SQLReviewPage />);++ expect(mocks.aiReviewPolicyEnabled).toHaveBeenLastCalledWith(true);+ });+test("the footer saves the AI review policy when only it changed", async () => {mocks.sqlReviewV2.value = true;mocks.aiReviewPolicy.isDirty = true;@@ -140,6 +169,30 @@ describe("SQLReviewPage", () => {expect(mocks.pushNotification).toHaveBeenCalledOnce();});+ test("does not save a hidden AI review policy draft", async () => {+ mocks.sqlReviewV2.value = true;+ mocks.aiReview.enabled = false;+ mocks.aiReview.isDirty = true;+ mocks.aiReviewPolicy.isDirty = true;+ render(<SQLReviewPage />);++ await update();++ expect(mocks.aiReview.save).toHaveBeenCalledOnce();+ expect(mocks.aiReviewPolicy.save).not.toHaveBeenCalled();+ });++ test("can save turning off AI review when its hidden policy is invalid", () => {+ mocks.sqlReviewV2.value = true;+ mocks.aiReview.enabled = false;+ mocks.aiReview.isDirty = true;+ mocks.aiReviewPolicy.isDirty = true;+ mocks.aiReviewPolicy.error = "too-large";+ render(<SQLReviewPage />);++ expect(screen.getByRole("button", { name: "common.update" })).toBeEnabled();+ });+test("the footer cannot update while the AI review policy is invalid", () => {mocks.sqlReviewV2.value = true;mocks.aiReviewPolicy.isDirty = true;diff --git a/frontend/src/routes/workspace/SQLReviewPage.tsx b/frontend/src/routes/workspace/SQLReviewPage.tsxindex fd625d2af5..413360466b 100644--- a/frontend/src/routes/workspace/SQLReviewPage.tsx+++ b/frontend/src/routes/workspace/SQLReviewPage.tsx@@ -257,10 +257,6 @@ function PolicyTable({// SQLReviewPage (exported)// ============================================================-// The standard rules read as one centered column, and the footer lines its-// actions up with it.-const STANDARD_RULES_COLUMN = "mx-auto w-full max-w-3xl";-export function SQLReviewPage() {const { t } = useTranslation();const sqlReviewStore = useSQLReviewStore();@@ -270,7 +266,12 @@ export function SQLReviewPage() {const standardRules = useWorkspaceStandardRules(sqlReviewV2);const aiReview = useWorkspaceAIReview();const aiReviewPolicy = useWorkspaceReviewAIPolicy(sqlReviewV2);- const parts = [standardRules, aiReview, aiReviewPolicy];+ const aiReviewPolicyVisible = aiReview.aiEnabled && aiReview.enabled;+ const parts = [+ standardRules,+ aiReview,+ ...(aiReviewPolicyVisible ? [aiReviewPolicy] : []),+ ];const isDirty = parts.some((part) => part.isDirty);const saving = parts.some((part) => part.saving);useUnsavedChangesGuard(isDirty);@@ -311,13 +312,13 @@ export function SQLReviewPage() {return (<WorkspacePageLayout className="gap-y-4">{sqlReviewV2 ? (- <div className={STANDARD_RULES_COLUMN}>+ <><SQLReviewStandardRulesSection standardRules={standardRules} /><SQLReviewAIReviewSectionaiReview={aiReview}policy={aiReviewPolicy}/>- </div>+ </>) : (<><WorkspacePageInfo@@ -362,7 +363,6 @@ export function SQLReviewPage() {{isDirty && (<StickyActionFootercontentPadding={false}- contentClassName={STANDARD_RULES_COLUMN}left={<Buttonappearance="outline"@@ -376,7 +376,10 @@ export function SQLReviewPage() {}right={<Button- disabled={saving || aiReviewPolicy.error !== undefined}+ disabled={+ saving ||+ (aiReviewPolicyVisible && aiReviewPolicy.error !== undefined)+ }onClick={async () => {const saves = parts.filter((part) => part.isDirty)diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsxindex a9409301e0..487f92ae3b 100644--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx@@ -136,6 +136,17 @@ describe("SQLReviewStandardRulesSection", () => {seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });});+ test("does not add outer padding around the page section", async () => {+ render(<Harness />);+ await findSwitches();++ const section = screen+ .getByRole("heading", { name: "sql-review.standard-rules.self" })+ .closest('[data-slot="form-section"]');+ expect(getComputedStyle(section!).paddingTop).toBe("0");+ expect(getComputedStyle(section!).paddingBottom).toBe("0");+ });+test("saves the edited rules as the enforced workspace policy", async () => {render(<Harness />);await findSwitches();diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsxindex c8d964f7fc..8834478f2e 100644--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx@@ -127,6 +127,7 @@ export function SQLReviewStandardRulesSection({return (<FormSectionlayout="single-column"+ padding="none"title={t("sql-review.standard-rules.self")}description={t("sql-review.standard-rules.description")}>diff --git a/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx b/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsxindex f05e757eb6..71ab42c199 100644--- a/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx+++ b/frontend/src/routes/workspace/general/AIAugmentationSection.test.tsx@@ -161,4 +161,17 @@ describe("AIAugmentationSection", () => {expect(mocks.upsertSetting).toHaveBeenCalledOnce();expect(mocks.refreshServerInfo).not.toHaveBeenCalled();});++ test("includes the selected provider when creating the AI setting", async () => {+ const ref = createRef<SectionHandle>();+ render(+ <AIAugmentationSection ref={ref} title="AI" onDirtyChange={vi.fn()} />+ );++ fireEvent.click(screen.getByRole("checkbox", { name: "enable-ai" }));+ await act(async () => ref.current?.update());++ const request = mocks.upsertSetting.mock.calls[0][0];+ expect(request.updateMask.paths).toContain("value.ai.provider");+ });});diff --git a/frontend/src/routes/workspace/general/AIAugmentationSection.tsx b/frontend/src/routes/workspace/general/AIAugmentationSection.tsxindex 8b6430ba67..48312310a7 100644--- a/frontend/src/routes/workspace/general/AIAugmentationSection.tsx+++ b/frontend/src/routes/workspace/general/AIAugmentationSection.tsx@@ -158,7 +158,8 @@ export const AIAugmentationSection = forwardRef<const init = getInitialState();const paths: string[] = [];if (state.enabled !== init.enabled) paths.push("value.ai.enabled");- if (state.provider !== init.provider) paths.push("value.ai.provider");+ if (!aiSetting || state.provider !== init.provider)+ paths.push("value.ai.provider");if (state.endpoint !== init.endpoint) paths.push("value.ai.endpoint");if (state.model !== init.model) paths.push("value.ai.model");if (state.apiKey || state.provider !== init.provider)