Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(review): run the AI review from the plan page (#21621)
h3n4l091e4593f5cd
diff --git a/docs/design/timestamp-display.md b/docs/design/timestamp-display.mdindex 27136cc162..e01be2b1bc 100644--- a/docs/design/timestamp-display.md+++ b/docs/design/timestamp-display.md@@ -174,6 +174,7 @@ Every current `HumanizeTs` call site, classified under the principle:| Schema sync status | `modules/sql-editor/components/SchemaPane/SyncSchemaButton.tsx`, `routes/project/ProjectSyncSchemaPage.tsx`, `components/database/DatabaseOverviewInfo.tsx` | Freshness | 30d switch || Agent chat | `modules/agent/components/AgentWindow.tsx` | Feed | 30d switch || Plan-check run time | `components/plan-check/PlanCheckSection.tsx` (bare `toLocaleString()` today — adopts `HumanizeTs`) | Freshness | 30d switch |+| AI review run finish time | `routes/project/plan-detail/components/PlanDetailAIReview.tsx` | Freshness | 30d switch || Access-grant creation time | `routes/project/ProjectAccessGrantsPage.tsx` (`AccessGrantRow`; full absolute today — adopts `HumanizeTs`). Shares the operational form with the expiration beside it: two dates in one row read in one format, and consistency outranks the freshness a relative age would add. The row's status, statement, creator and databases carry what a reader acts on — the status turns Expired by itself — so the dates take none of the spare width, and when the table is narrower than the defaults together they give way first, down to the timestamp minimum, then the statement, the creator and the databases, with the status last. A narrow screen cuts each date's time and zone and keeps its day; the full date-time stays on the hover | Operational | Operational (D6 tooltip) || **Database changelog** | `routes/project/database-detail/changelog/DatabaseChangelogTable.tsx` | **History view** | **Absolute always — compact tier (D7)** || **Database revisions** | `routes/project/database-detail/revision/DatabaseRevisionTable.tsx` | **History view** | **Absolute always — compact tier (D7)** |diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 0375133666..de159b8113 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1699,6 +1699,15 @@"plan": {"add-spec": "Add Change","add-spec-pending-draft": "Save or discard the pending change before adding another",+ "ai-review": {+ "failed-to-run": "Could not start the AI review",+ "finished": "Finished",+ "not-run": "Not run yet",+ "queued": "Queued",+ "run": "Run AI review",+ "save-first": "Save or discard your edits to run the AI review.",+ "status-unknown": "Status not available"+ },"blocker": {"clears-on-its-own": "Clears on its own"},diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 1c5f5138d8..c184b73d52 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1699,6 +1699,15 @@"plan": {"add-spec": "Agregar cambio","add-spec-pending-draft": "Guarda o descarta el cambio pendiente antes de agregar otro",+ "ai-review": {+ "failed-to-run": "No se pudo iniciar la revisión con IA",+ "finished": "Finalizada",+ "not-run": "Aún no se ha ejecutado",+ "queued": "En cola",+ "run": "Ejecutar revisión con IA",+ "save-first": "Guarda o descarta tus cambios para ejecutar la revisión con IA.",+ "status-unknown": "Estado no disponible"+ },"blocker": {"clears-on-its-own": "Se resuelve solo"},diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex b0e874a845..93f5f580e2 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1699,6 +1699,15 @@"plan": {"add-spec": "変更を追加","add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください",+ "ai-review": {+ "failed-to-run": "AI レビューを開始できませんでした",+ "finished": "完了",+ "not-run": "未実行",+ "queued": "待機中",+ "run": "AI レビューを実行",+ "save-first": "AI レビューを実行するには、編集内容を保存または破棄してください。",+ "status-unknown": "状態を取得できません"+ },"blocker": {"clears-on-its-own": "自動的に解消されます"},diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 604d5995e6..69c99bdf7d 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1699,6 +1699,15 @@"plan": {"add-spec": "Thêm thay đổi","add-spec-pending-draft": "Lưu hoặc hủy thay đổi đang chờ trước khi thêm thay đổi khác",+ "ai-review": {+ "failed-to-run": "Không thể bắt đầu đánh giá bằng AI",+ "finished": "Đã hoàn tất",+ "not-run": "Chưa chạy",+ "queued": "Đang chờ",+ "run": "Chạy đánh giá bằng AI",+ "save-first": "Hãy lưu hoặc hủy các thay đổi để chạy đánh giá bằng AI.",+ "status-unknown": "Chưa có trạng thái"+ },"blocker": {"clears-on-its-own": "Tự động hoàn tất"},diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b5b70e8d03..7de21b73f0 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1699,6 +1699,15 @@"plan": {"add-spec": "添加变更","add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更",+ "ai-review": {+ "failed-to-run": "无法启动 AI 审核",+ "finished": "已完成",+ "not-run": "尚未运行",+ "queued": "排队中",+ "run": "运行 AI 审核",+ "save-first": "请先保存或放弃修改,再运行 AI 审核。",+ "status-unknown": "暂时无法获取状态"+ },"blocker": {"clears-on-its-own": "将自动完成"},diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsxindex 575ee810c4..194f9d5a0f 100644--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx@@ -109,7 +109,7 @@ function ProjectPlanDetailPageInner({stageId,taskId,});- useIssueCommentThreadsSync(page.issue);+ useIssueCommentThreadsSync(page.issue, page.aiReviewRun);const unresolvedThreads = useUnresolvedThreadTotal(page.issue?.name);usePlacementSync({issueName: page.issue?.name,diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsxnew file mode 100644index 0000000000..75066e8049--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsx@@ -0,0 +1,383 @@+import { create } from "@bufbuild/protobuf";+import { Code, ConnectError } from "@connectrpc/connect";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { shownTimestampInstants } from "@/test-utils/humanizeTs";+import { IssueStatus } from "@/types/proto-es/v1/common_pb";+import {+ IssueSchema,+ type ReviewRun,+ ReviewRun_Status,+ ReviewRunSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_CreateDatabaseConfigSchema,+ type Plan_Spec,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import {+ DatabaseGroupSchema,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import { RolloutSchema } from "@/types/proto-es/v1/rollout_service_pb";++const mocks = vi.hoisted(() => ({+ dev: true,+ page: {} as Record<string, unknown>,+ permissions: new Set<string>(),+ pushNotification: vi.fn(),+ runReview: vi.fn(),+ serverInfo: { aiEnabled: true, aiSqlReviewEnabled: true } as+ | { aiEnabled: boolean; aiSqlReviewEnabled: boolean }+ | undefined,+ groups: undefined as+ | {+ setState: (state: {+ dbGroupsByName: Record<string, unknown>;+ dbGroupViewByName: Record<string, unknown>;+ }) => void;+ }+ | undefined,+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/components/HumanizeTs", async () => ({+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),+}));++vi.mock("@/api", () => ({+ issueServiceClientConnect: { runReview: mocks.runReview },+}));++vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));++// The groups sit in a real store, so a test that loads a group sees the+// component react through its own subscription.+vi.mock("@/stores/app", async () => {+ const { createStore, useStore } = await import("zustand");+ const groups = createStore(() => ({+ dbGroupsByName: {} as Record<string, unknown>,+ dbGroupViewByName: {} as Record<string, unknown>,+ }));+ mocks.groups = groups;+ return {+ useAppStore: (selector: (state: unknown) => unknown) =>+ useStore(groups, (state) =>+ selector({ serverInfo: mocks.serverInfo, ...state })+ ),+ };+});++vi.mock("@/utils/featureGates", () => ({+ sqlReviewV2Enabled: () => mocks.dev,+}));++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: (_project: unknown, permission: string) =>+ mocks.permissions.has(permission),+}));++vi.mock("../shell/PlanDetailContext", () => ({+ usePlanDetailContext: () => mocks.page,+}));++import { PlanDetailAIReview } from "./PlanDetailAIReview";++const ISSUE = "projects/p/issues/1";++const changeSpec = (release = ""): Plan_Spec["config"] => ({+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ targets: ["instances/i/databases/d"],+ release,+ }),+});++const GROUP = "projects/p/databaseGroups/g";++const groupSpec = (): Plan_Spec["config"] => ({+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, { targets: [GROUP] }),+});++const loadGroup = (databases: string[]) =>+ act(() =>+ mocks.groups?.setState({+ dbGroupsByName: {+ [GROUP]: create(DatabaseGroupSchema, {+ name: GROUP,+ matchedDatabases: databases.map((name) => ({ name })),+ }),+ },+ dbGroupViewByName: { [GROUP]: DatabaseGroupView.FULL },+ })+ );++const planWith = (+ fields: Record<string, unknown> = {},+ configs: Plan_Spec["config"][] = [changeSpec()]+) =>+ create(PlanSchema, {+ name: "projects/p/plans/1",+ issue: ISSUE,+ specs: configs.map((config, i) => ({ id: `${i}`, config })),+ ...fields,+ });++const reviewRun = (+ status: ReviewRun_Status,+ { endSeconds, error = "" }: { endSeconds?: number; error?: string } = {}+) =>+ create(ReviewRunSchema, {+ name: `${ISSUE}/reviewRuns/ai`,+ status,+ error,+ endTime:+ endSeconds === undefined+ ? undefined+ : { seconds: BigInt(endSeconds), nanos: 0 },+ });++const openPage = (+ aiReviewRun: ReviewRun | null | undefined,+ overrides: Record<string, unknown> = {}+) => {+ mocks.page = {+ aiReviewRun,+ issue: create(IssueSchema, { name: ISSUE, status: IssueStatus.OPEN }),+ patchState: vi.fn(),+ plan: planWith(),+ project: create(ProjectSchema, { name: "projects/p" }),+ refreshState: vi.fn(async () => undefined),+ rollout: undefined,+ ...overrides,+ };+ return mocks.page as {+ patchState: ReturnType<typeof vi.fn>;+ refreshState: ReturnType<typeof vi.fn>;+ };+};++const runButton = () =>+ screen.queryByRole("button", { name: "plan.ai-review.run" });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.dev = true;+ mocks.permissions = new Set(["bb.reviewRuns.get", "bb.reviewRuns.run"]);+ mocks.serverInfo = { aiEnabled: true, aiSqlReviewEnabled: true };+ mocks.groups?.setState({ dbGroupsByName: {}, dbGroupViewByName: {} });+});++afterEach(cleanup);++describe("PlanDetailAIReview", () => {+ test("says a slot that never ran has not run yet", () => {+ openPage(null);+ render(<PlanDetailAIReview />);+ expect(screen.getByText("plan.ai-review.not-run")).toBeDefined();+ expect(runButton()?.hasAttribute("disabled")).toBe(false);+ });++ test("sends RunReview for the issue's AI slot and adopts the started run", async () => {+ const page = openPage(null);+ const started = reviewRun(ReviewRun_Status.AVAILABLE);+ mocks.runReview.mockResolvedValueOnce(started);+ render(<PlanDetailAIReview />);++ await act(async () => {+ fireEvent.click(runButton()!);+ });++ expect(mocks.runReview).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ name: `${ISSUE}/reviewRuns/ai` }),+ expect.anything()+ );+ expect(page.patchState).toHaveBeenCalledExactlyOnceWith({+ aiReviewRun: started,+ });+ expect(page.refreshState).toHaveBeenCalledOnce();+ });++ test.each([+ [ReviewRun_Status.AVAILABLE, "plan.ai-review.queued"],+ [ReviewRun_Status.RUNNING, "common.running"],+ ])("disables Run while a run is queued or running: status %s", (status, label) => {+ openPage(reviewRun(status));+ render(<PlanDetailAIReview />);+ expect(screen.getByText(label)).toBeDefined();+ expect(runButton()?.hasAttribute("disabled")).toBe(true);+ });++ test("disables Run while the slot has not been read", () => {+ openPage(undefined);+ render(<PlanDetailAIReview />);+ expect(screen.getByText("plan.ai-review.status-unknown")).toBeDefined();+ expect(runButton()?.hasAttribute("disabled")).toBe(true);+ });++ test("disables Run while the page has unsaved edits, and says why", () => {+ openPage(null, { isEditing: true });+ const { rerender } = render(<PlanDetailAIReview />);+ expect(runButton()?.hasAttribute("disabled")).toBe(true);+ expect(screen.getByText("plan.ai-review.save-first")).toBeDefined();++ openPage(null, { isEditing: false });+ rerender(<PlanDetailAIReview />);+ expect(runButton()?.hasAttribute("disabled")).toBe(false);+ expect(screen.queryByText("plan.ai-review.save-first")).toBeNull();+ });++ test("shows when a finished run finished, and offers Run again", () => {+ openPage(+ reviewRun(ReviewRun_Status.DONE, { endSeconds: 1_700_000_000 })+ );+ const { container } = render(<PlanDetailAIReview />);+ expect(screen.getByText("plan.ai-review.finished")).toBeDefined();+ expect(shownTimestampInstants(container)).toEqual(["1700000000000"]);+ expect(runButton()?.hasAttribute("disabled")).toBe(false);+ });++ test("shows the error of a failed run as plain text", () => {+ const error = "provider unreachable: <b>dial tcp</b> lookup ai.invalid";+ openPage(reviewRun(ReviewRun_Status.FAILED, { error }));+ const { container } = render(<PlanDetailAIReview />);+ expect(screen.getByText("common.failed")).toBeDefined();+ expect(screen.getByTestId("ai-review-error").textContent).toBe(error);+ expect(container.querySelector("b")).toBeNull();+ });++ test("reports the server message when RunReview fails and changes nothing else", async () => {+ const page = openPage(null);+ mocks.runReview.mockRejectedValueOnce(+ new ConnectError(+ "AI review requires the workspace AI review switch",+ Code.FailedPrecondition+ )+ );+ render(<PlanDetailAIReview />);++ await act(async () => {+ fireEvent.click(runButton()!);+ });++ expect(mocks.pushNotification).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ style: "CRITICAL",+ title: "plan.ai-review.failed-to-run",+ description: "AI review requires the workspace AI review switch",+ })+ );+ expect(page.patchState).not.toHaveBeenCalled();+ expect(page.refreshState).not.toHaveBeenCalled();+ expect(screen.getByText("plan.ai-review.not-run")).toBeDefined();+ expect(runButton()?.hasAttribute("disabled")).toBe(false);+ });++ test("shows the status but no Run button without the run permission", () => {+ mocks.permissions = new Set(["bb.reviewRuns.get"]);+ openPage(null);+ render(<PlanDetailAIReview />);+ expect(screen.getByText("plan.ai-review.not-run")).toBeDefined();+ expect(runButton()).toBeNull();+ });++ test("hides the AI review while the plan's only group matches no databases", () => {+ openPage(null, { plan: planWith({}, [groupSpec()]) });+ render(<PlanDetailAIReview />);+ expect(runButton()).not.toBeNull();++ loadGroup([]);+ expect(screen.queryByTestId("ai-review")).toBeNull();++ loadGroup(["instances/i/databases/d"]);+ expect(runButton()).not.toBeNull();+ });++ test("shows for a draft issue", () => {+ openPage(null, {+ issue: create(IssueSchema, {+ name: ISSUE,+ status: IssueStatus.OPEN,+ draft: true,+ }),+ });+ render(<PlanDetailAIReview />);+ expect(screen.getByTestId("ai-review")).toBeDefined();+ });++ test.each<[string, () => void]>([+ ["outside dev builds", () => (mocks.dev = false)],+ [+ "without an issue",+ () =>+ openPage(null, {+ issue: undefined,+ plan: planWith({ issue: "" }),+ }),+ ],+ [+ "for a closed issue",+ () =>+ openPage(null, {+ issue: create(IssueSchema, { name: ISSUE, status: IssueStatus.DONE }),+ }),+ ],+ [+ "once the plan records a rollout",+ () =>+ openPage(null, {+ plan: planWith({ hasRollout: true }),+ }),+ ],+ [+ "once a rollout has loaded before the plan records it",+ () =>+ openPage(null, {+ rollout: create(RolloutSchema, { name: "projects/p/rollouts/1" }),+ }),+ ],+ [+ "for a plan that only creates databases",+ () =>+ openPage(null, {+ plan: planWith({}, [+ {+ case: "createDatabaseConfig",+ value: create(Plan_CreateDatabaseConfigSchema, {}),+ },+ ]),+ }),+ ],+ [+ "for a plan whose changes all come from a release",+ () =>+ openPage(null, {+ plan: planWith({}, [changeSpec("projects/p/releases/r")]),+ }),+ ],+ [+ "with AI off",+ () => (mocks.serverInfo = { aiEnabled: false, aiSqlReviewEnabled: true }),+ ],+ [+ "with the AI review switch off",+ () => (mocks.serverInfo = { aiEnabled: true, aiSqlReviewEnabled: false }),+ ],+ [+ "without permission to read review runs",+ () => (mocks.permissions = new Set(["bb.reviewRuns.run"])),+ ],+ ])("hides the AI review %s", (_condition, apply) => {+ openPage(null);+ apply();+ const { container } = render(<PlanDetailAIReview />);+ expect(container.innerHTML).toBe("");+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.tsxnew file mode 100644index 0000000000..7bce6dbe14--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.tsx@@ -0,0 +1,201 @@+import { create } from "@bufbuild/protobuf";+import { ConnectError, createContextValues } from "@connectrpc/connect";+import { Loader2, Play, XCircle } from "lucide-react";+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { issueServiceClientConnect } from "@/api";+import { skipErrorNotificationContextKey } from "@/api/context-key";+import { HumanizeTs } from "@/components/HumanizeTs";+import { Button } from "@/components/ui/button";+import { Separator } from "@/components/ui/separator";+import { pushNotification } from "@/stores";+import { useAppStore } from "@/stores/app";+import { getTimeForPbTimestampProtoEs } from "@/types";+import { IssueStatus } from "@/types/proto-es/v1/common_pb";+import {+ type ReviewRun,+ ReviewRun_Status,+ RunReviewRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import { usePlanDetailContext } from "../shell/PlanDetailContext";+import {+ aiReviewRunName,+ isAIReviewRunActive,+ loadedMatchedDatabaseCount,+ readsAIReviewRun,+} from "../utils/aiReviewRun";++// The issue's AI review, beside the plan checks at the foot of the CHANGES+// card: its status and a Run button. Findings are review comments, and+// nothing gates on a run, so a finished run is not a pass.+export function PlanDetailAIReview() {+ const { t } = useTranslation();+ const { allowRun, editing, run, runReview, shown, starting } =+ useAIReviewRun();+ if (!shown) return null;++ return (+ <>+ <Separator />+ <div className="flex flex-col gap-y-1 px-4 py-4" data-testid="ai-review">+ <div className="flex items-center justify-between gap-2">+ <h3 className="textlabel uppercase">+ {t("sql-review.ai-review.self")}+ </h3>+ {allowRun && (+ <Button+ appearance="outline"+ aria-label={t("plan.ai-review.run")}+ disabled={+ starting ||+ editing ||+ run === undefined ||+ isAIReviewRunActive(run)+ }+ onClick={() => void runReview()}+ size="xs"+ >+ <Play className="size-3.5" />+ {t("common.run")}+ </Button>+ )}+ </div>+ <AIReviewRunStatus run={run} />+ {allowRun && editing && (+ <span className="text-sm text-control-light">+ {t("plan.ai-review.save-first")}+ </span>+ )}+ </div>+ </>+ );+}++function AIReviewRunStatus({ run }: { run: ReviewRun | null | undefined }) {+ const { t } = useTranslation();+ if (run === undefined) {+ return (+ <span className="text-sm text-control-placeholder">+ {t("plan.ai-review.status-unknown")}+ </span>+ );+ }+ if (run === null) {+ return (+ <span className="text-sm text-control-placeholder">+ {t("plan.ai-review.not-run")}+ </span>+ );+ }+ switch (run.status) {+ case ReviewRun_Status.AVAILABLE:+ case ReviewRun_Status.RUNNING:+ return (+ <span className="flex items-center gap-x-1 text-sm text-control">+ <Loader2 className="size-4 animate-spin" />+ {run.status === ReviewRun_Status.AVAILABLE+ ? t("plan.ai-review.queued")+ : t("common.running")}+ </span>+ );+ case ReviewRun_Status.DONE:+ return (+ <span className="flex flex-wrap items-center gap-x-1 text-sm text-control">+ {t("plan.ai-review.finished")}+ <HumanizeTs+ className="text-control-light"+ tsMs={getTimeForPbTimestampProtoEs(run.endTime)}+ />+ </span>+ );+ case ReviewRun_Status.FAILED:+ return (+ <div className="flex flex-col gap-y-1 text-sm">+ <span className="flex flex-wrap items-center gap-x-1 text-error">+ <XCircle className="size-4" />+ {t("common.failed")}+ <HumanizeTs+ className="text-control-light"+ tsMs={getTimeForPbTimestampProtoEs(run.endTime)}+ />+ </span>+ <p+ className="wrap-break-word whitespace-pre-wrap text-control"+ data-testid="ai-review-error"+ >+ {run.error}+ </p>+ </div>+ );+ default:+ return null;+ }+}++// RunReview replaces whatever execution the slot holds and the backend has no+// same-version no-op, so the button stays disabled while a run is queued or+// running, and while the page has not read the slot, since an unseen run may+// be either. The started run joins the page snapshot, whose polling turns+// active until the run settles.+function useAIReviewRun() {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const { issue, patchState, refreshState } = page;+ const serverInfo = useAppStore((state) => state.serverInfo);+ const dbGroupsByName = useAppStore((state) => state.dbGroupsByName);+ const dbGroupViewByName = useAppStore((state) => state.dbGroupViewByName);+ const [starting, setStarting] = useState(false);+ const shown =+ readsAIReviewRun({+ plan: page.plan,+ project: page.project,+ serverInfo,+ matchedDatabaseCount: loadedMatchedDatabaseCount({+ dbGroupsByName,+ dbGroupViewByName,+ }),+ }) &&+ issue?.status === IssueStatus.OPEN &&+ !page.rollout;+ const allowRun =+ shown && hasProjectPermissionV2(page.project, "bb.reviewRuns.run");++ const runReview = useCallback(async () => {+ if (!issue) return;+ setStarting(true);+ try {+ const run = await issueServiceClientConnect.runReview(+ create(RunReviewRequestSchema, { name: aiReviewRunName(issue.name) }),+ {+ contextValues: createContextValues().set(+ skipErrorNotificationContextKey,+ true+ ),+ }+ );+ patchState({ aiReviewRun: run });+ await refreshState().catch(() => undefined);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("plan.ai-review.failed-to-run"),+ description: ConnectError.from(error).rawMessage,+ });+ } finally {+ setStarting(false);+ }+ }, [issue, patchState, refreshState, t]);++ // A run reviews the saved plan, so unsaved SQL would get findings about+ // the statement the user has already changed.+ return {+ allowRun,+ editing: page.isEditing,+ run: page.aiReviewRun,+ runReview,+ shown,+ starting,+ };+}diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 48b71c6d16..3ff1b51ec3 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -151,6 +151,7 @@ import {} from "../utils/targets";import { PlanChangeReference } from "./PlanChangeReference";import { PlanDetailAggregateChecks } from "./PlanDetailAggregateChecks";+import { PlanDetailAIReview } from "./PlanDetailAIReview";import { PlanDetailDraftChecks } from "./PlanDetailDraftChecks";import { PlanDetailStatementSection } from "./PlanDetailStatementSection";import { PlanDetailTabItem, PlanDetailTabStrip } from "./PlanDetailTabStrip";@@ -716,6 +717,7 @@ export function PlanDetailChangesBranch({</div>{!page.isCreating && !specHasRelease && <PlanDetailAggregateChecks />}+ <PlanDetailAIReview /><TargetSelectorSheetcurrentTargets={currentTargets}diff --git a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.ts b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.tsindex 7d3a08eade..54ba8cec14 100644--- a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.ts+++ b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.test.ts@@ -1,7 +1,11 @@import { create } from "@bufbuild/protobuf";import { renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueSchema,+ ReviewRun_Status,+ ReviewRunSchema,+} from "@/types/proto-es/v1/issue_service_pb";const mocks = vi.hoisted(() => ({fetchIssueCommentThreads: vi.fn(async () => undefined),@@ -63,6 +67,39 @@ describe("useIssueCommentThreadsSync", () => {expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(4);});+ test("re-lists once when an AI review run reaches DONE, not while it is queued, running, or failed", () => {+ const run = (status: ReviewRun_Status, endSeconds?: number) =>+ create(ReviewRunSchema, {+ name: "projects/p/issues/1/reviewRuns/ai",+ status,+ endTime:+ endSeconds === undefined+ ? undefined+ : { seconds: BigInt(endSeconds), nanos: 0 },+ });+ const { rerender } = renderHook(+ ({ reviewRun }) => useIssueCommentThreadsSync(issue(1), reviewRun),+ { initialProps: { reviewRun: run(ReviewRun_Status.AVAILABLE) } }+ );+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ rerender({ reviewRun: run(ReviewRun_Status.RUNNING) });+ rerender({ reviewRun: run(ReviewRun_Status.FAILED, 5) });+ rerender({ reviewRun: run(ReviewRun_Status.AVAILABLE) });+ rerender({ reviewRun: run(ReviewRun_Status.RUNNING) });+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(1);+ rerender({ reviewRun: run(ReviewRun_Status.DONE, 10) });+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(2);+ rerender({ reviewRun: run(ReviewRun_Status.DONE, 10) });+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(2);++ // The next run queues and runs without a re-list, then finishes once.+ rerender({ reviewRun: run(ReviewRun_Status.AVAILABLE) });+ rerender({ reviewRun: run(ReviewRun_Status.RUNNING) });+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(2);+ rerender({ reviewRun: run(ReviewRun_Status.DONE, 20) });+ expect(mocks.fetchIssueCommentThreads).toHaveBeenCalledTimes(3);+ });+test("does nothing without an issue and stops after unmount", () => {const { rerender, unmount } = renderHook((props) => useIssueCommentThreadsSync(props),diff --git a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.ts b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.tsindex 88217428d3..702da5f3d8 100644--- a/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.ts+++ b/frontend/src/routes/project/plan-detail/hooks/useIssueCommentThreadsSync.ts@@ -1,6 +1,10 @@-import { useEffect } from "react";+import { useEffect, useState } from "react";import { useAppStore } from "@/stores/app";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import {+ type Issue,+ type ReviewRun,+ ReviewRun_Status,+} from "@/types/proto-es/v1/issue_service_pb";// Comment writes never touch the issue's update time, so polling the issue// cannot reveal another reviewer's reply, edit, resolve, or reopen. The@@ -8,14 +12,28 @@ import type { Issue } from "@/types/proto-es/v1/issue_service_pb";const THREADS_REFRESH_INTERVAL_MS = 15_000;// Loads the issue's comments with thread replies when the issue changes-// server-side (polling bumps updateTime) or after local actions refresh it,-// and periodically in between for remote thread activity. Mounted once per-// plan page: both the Review Activity timeline and the statement editor read-// the same cache, so neither may depend on the other being expanded to have-// it filled.-export function useIssueCommentThreadsSync(issue: Issue | undefined) {+// server-side (polling bumps updateTime), when an AI review run finishes and+// has posted its findings, or after local actions refresh it, and+// periodically in between for remote thread activity. Mounted once per plan+// page: both the Review Activity timeline and the statement editor read the+// same cache, so neither may depend on the other being expanded to have it+// filled.+export function useIssueCommentThreadsSync(+ issue: Issue | undefined,+ aiReviewRun?: ReviewRun | null+) {const issueName = issue?.name;const updateKey = `${issue?.updateTime?.seconds ?? ""}:${issue?.updateTime?.nanos ?? ""}`;+ // The end time of the latest finish seen. Each execution ends at a new+ // time, so each finish re-lists once; starting the next run keeps the key.+ const finishedKey =+ aiReviewRun?.status === ReviewRun_Status.DONE+ ? `${aiReviewRun.endTime?.seconds ?? ""}:${aiReviewRun.endTime?.nanos ?? ""}`+ : undefined;+ const [reviewFinishedKey, setReviewFinishedKey] = useState(finishedKey ?? "");+ if (finishedKey !== undefined && finishedKey !== reviewFinishedKey) {+ setReviewFinishedKey(finishedKey);+ }useEffect(() => {if (!issueName) return;const refresh = () => {@@ -37,5 +55,5 @@ export function useIssueCommentThreadsSync(issue: Issue | undefined) {window.clearInterval(timer);document.removeEventListener("visibilitychange", onVisibilityChange);};- }, [issueName, updateKey]);+ }, [issueName, updateKey, reviewFinishedKey]);}diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.ts b/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.tsindex dc7b690cbe..9a38f0f9c1 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.test.ts@@ -1,8 +1,18 @@// @vitest-environment nodeimport { create } from "@bufbuild/protobuf";+import { Code, ConnectError } from "@connectrpc/connect";import { beforeEach, describe, expect, test, vi } from "vitest";+import { useAppStore } from "@/stores/app";import { IssueStatus } from "@/types/proto-es/v1/common_pb";-import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ DatabaseGroupSchema,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";+import {+ IssueSchema,+ ReviewRun_Status,+ ReviewRunSchema,+} from "@/types/proto-es/v1/issue_service_pb";import {PlanCheckRunSchema,PlanSchema,@@ -20,12 +30,22 @@ const mocks = vi.hoisted(() => ({getPlan: vi.fn(),getPlanCheckRun: vi.fn(),getProject: vi.fn(),+ getReviewRun: vi.fn(),getRollout: vi.fn(),listTaskRuns: vi.fn(),+ readsAIReviewRun: vi.fn(() => false),+}));++vi.mock("../../utils/aiReviewRun", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../utils/aiReviewRun")>()),+ readsAIReviewRun: mocks.readsAIReviewRun,}));vi.mock("@/api", () => ({- issueServiceClientConnect: { getIssue: mocks.getIssue },+ issueServiceClientConnect: {+ getIssue: mocks.getIssue,+ getReviewRun: mocks.getReviewRun,+ },planServiceClientConnect: {getPlan: mocks.getPlan,getPlanCheckRun: mocks.getPlanCheckRun,@@ -47,6 +67,12 @@ const plan = (hasRollout: boolean) =>hasRollout,});+const reviewRun = (status: ReviewRun_Status) =>+ create(ReviewRunSchema, {+ name: "projects/foo/issues/1/reviewRuns/ai",+ status,+ });+describe("fetchPlanSnapshot", () => {beforeEach(() => {vi.clearAllMocks();@@ -113,4 +139,111 @@ describe("fetchPlanSnapshot", () => {expect("issue" in patch).toBe(false);});++ describe("with an open issue", () => {+ beforeEach(() => {+ mocks.getPlan.mockResolvedValue(plan(false));+ mocks.getIssue.mockResolvedValue(+ create(IssueSchema, {+ name: "projects/foo/issues/1",+ status: IssueStatus.OPEN,+ })+ );+ });++ test("reads the issue's AI review slot, and a slot that never ran as null", async () => {+ mocks.readsAIReviewRun.mockReturnValue(true);+ mocks.getReviewRun.mockRejectedValueOnce(+ new ConnectError("review run not found", Code.NotFound)+ );++ const patch = await fetchPlanSnapshot("foo", "1");++ expect(mocks.readsAIReviewRun).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ plan: expect.objectContaining({ name: "projects/foo/plans/1" }),+ project: expect.objectContaining({ name: "projects/foo" }),+ })+ );+ expect(mocks.getReviewRun).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ name: "projects/foo/issues/1/reviewRuns/ai",+ }),+ expect.anything()+ );+ expect(patch.aiReviewRun).toBeNull();+ });++ test("patches the AI review run it read", async () => {+ mocks.readsAIReviewRun.mockReturnValue(true);+ const run = reviewRun(ReviewRun_Status.RUNNING);+ mocks.getReviewRun.mockResolvedValueOnce(run);++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect(patch.aiReviewRun).toBe(run);+ });++ test("keeps a failed AI review read out of the patch", async () => {+ mocks.readsAIReviewRun.mockReturnValue(true);+ mocks.getReviewRun.mockRejectedValueOnce(+ new ConnectError("temporary failure", Code.Unavailable)+ );++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect("aiReviewRun" in patch).toBe(false);+ });++ test("gives the AI review gate the database groups the page has loaded", async () => {+ mocks.readsAIReviewRun.mockReturnValue(false);+ const group = "projects/foo/databaseGroups/empty";+ useAppStore.setState({+ dbGroupsByName: {+ [group]: create(DatabaseGroupSchema, { name: group }),+ },+ dbGroupViewByName: { [group]: DatabaseGroupView.FULL },+ });+ try {+ await fetchPlanSnapshot("foo", "1");+ } finally {+ useAppStore.setState({ dbGroupsByName: {}, dbGroupViewByName: {} });+ }++ const [gate] = mocks.readsAIReviewRun.mock.calls[0] as unknown as [+ { matchedDatabaseCount: (group: string) => number | undefined },+ ];+ expect(gate.matchedDatabaseCount(group)).toBe(0);+ expect(+ gate.matchedDatabaseCount("projects/foo/databaseGroups/unloaded")+ ).toBeUndefined();+ });++ test("does not read the AI review slot when its gate is closed", async () => {+ mocks.readsAIReviewRun.mockReturnValue(false);++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect(mocks.getReviewRun).not.toHaveBeenCalled();+ expect("aiReviewRun" in patch).toBe(true);+ expect(patch.aiReviewRun).toBeUndefined();+ });+ });++ test.each([IssueStatus.DONE, IssueStatus.CANCELED])(+ "drops a running AI review run once the issue is closed: status %s",+ async (status) => {+ mocks.getPlan.mockResolvedValue(plan(false));+ mocks.getIssue.mockResolvedValue(+ create(IssueSchema, { name: "projects/foo/issues/1", status })+ );+ mocks.readsAIReviewRun.mockReturnValue(true);+ mocks.getReviewRun.mockResolvedValue(reviewRun(ReviewRun_Status.RUNNING));++ const patch = await fetchPlanSnapshot("foo", "1", {}, true);++ expect("aiReviewRun" in patch).toBe(true);+ expect(patch.aiReviewRun).toBeUndefined();+ }+ );});diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts b/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.tsindex b8d83e8e09..da1afb23a4 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts@@ -1,5 +1,5 @@import { create } from "@bufbuild/protobuf";-import { createContextValues } from "@connectrpc/connect";+import { Code, ConnectError, createContextValues } from "@connectrpc/connect";import {issueServiceClientConnect,planServiceClientConnect,@@ -9,10 +9,13 @@ import {} from "@/api";import { silentContextKey } from "@/api/context-key";import { listAllTaskRuns } from "@/api/taskRun";+import { useAppStore } from "@/stores/app";import { IssueStatus } from "@/types/proto-es/v1/common_pb";import {GetIssueRequestSchema,+ GetReviewRunRequestSchema,type Issue,+ type ReviewRun,} from "@/types/proto-es/v1/issue_service_pb";import {GetPlanCheckRunRequestSchema,@@ -31,6 +34,11 @@ import {} from "@/types/proto-es/v1/rollout_service_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";import { getRolloutFromPlan, hasProjectPermissionV2 } from "@/utils";+import {+ aiReviewRunName,+ loadedMatchedDatabaseCount,+ readsAIReviewRun,+} from "../../utils/aiReviewRun";import { createPlanSkeleton } from "../../utils/createPlan";import { PROJECT_NAME_PREFIX } from "../constants";@@ -46,8 +54,22 @@ export interface PlanDetailFetchPatch {rollout?: Rollout | undefined;planCheckRuns?: PlanCheckRun[];taskRuns?: TaskRun[];+ aiReviewRun?: ReviewRun | null;}+// A slot that has never run is NOT_FOUND, which reads as null. Always silent,+// even on the first load: a failed read leaves the last known run in place.+const requestAIReviewRun = (issueName: string) =>+ issueServiceClientConnect+ .getReviewRun(+ create(GetReviewRunRequestSchema, { name: aiReviewRunName(issueName) }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ )+ .catch((error: unknown) => {+ if (ConnectError.from(error).code === Code.NotFound) return null;+ throw error;+ });+// Keep the rollout and task-run request shape in one place. They are applied as// one consistency group below: if either request fails, neither field is// patched, so a transient poll failure cannot erase last-known-good deploy data.@@ -73,6 +95,24 @@ const requestRolloutState = async (rolloutName: string) => {return { rollout, taskRuns };};+// The run read alongside the issue was gated before the issue's status was+// known. A closed issue shows no AI review, so its run is dropped rather than+// left to hold the page on the active polling cadence.+const aiReviewRunPatch = (+ issueResult: PromiseSettledResult<Issue | undefined>,+ aiReviewRunResult: PromiseSettledResult<ReviewRun | null | undefined>+): Pick<PlanDetailFetchPatch, "aiReviewRun"> => {+ if (+ issueResult.status === "fulfilled" &&+ issueResult.value?.status !== IssueStatus.OPEN+ ) {+ return { aiReviewRun: undefined };+ }+ return aiReviewRunResult.status === "fulfilled"+ ? { aiReviewRun: aiReviewRunResult.value }+ : {};+};+const convertRouteQuery = (query: Record<string, unknown>) => {const kv: Record<string, string> = {};for (const [key, value] of Object.entries(query)) {@@ -150,26 +190,38 @@ export const fetchPlanSnapshot = async (// The rollout name is derived from the plan name, so task runs can load in// parallel with the rollout instead of being serialized behind it.let rolloutName = plan.hasRollout ? getRolloutFromPlan(plan.name) : "";- const [issueResult, planCheckRunsResult, rolloutStateResult] =- await Promise.allSettled([- plan.issue- ? issueServiceClientConnect.getIssue(- create(GetIssueRequestSchema, { name: plan.issue }),- silentCtx- )- : Promise.resolve(undefined),- planServiceClientConnect- .getPlanCheckRun(- create(GetPlanCheckRunRequestSchema, {- name: `${plan.name}/planCheckRun`,- }),+ const appState = useAppStore.getState();+ const readsAIReview = readsAIReviewRun({+ plan,+ project,+ serverInfo: appState.serverInfo,+ matchedDatabaseCount: loadedMatchedDatabaseCount(appState),+ });+ const [+ issueResult,+ planCheckRunsResult,+ rolloutStateResult,+ aiReviewRunResult,+ ] = await Promise.allSettled([+ plan.issue+ ? issueServiceClientConnect.getIssue(+ create(GetIssueRequestSchema, { name: plan.issue }),silentCtx)- .then((run) => [run] as PlanCheckRun[]),- rolloutName- ? requestRolloutState(rolloutName)- : Promise.resolve({ rollout: undefined, taskRuns: [] as TaskRun[] }),- ]);+ : Promise.resolve(undefined),+ planServiceClientConnect+ .getPlanCheckRun(+ create(GetPlanCheckRunRequestSchema, {+ name: `${plan.name}/planCheckRun`,+ }),+ silentCtx+ )+ .then((run) => [run] as PlanCheckRun[]),+ rolloutName+ ? requestRolloutState(rolloutName)+ : Promise.resolve({ rollout: undefined, taskRuns: [] as TaskRun[] }),+ readsAIReview ? requestAIReviewRun(plan.issue) : Promise.resolve(undefined),+ ]);// Rollout creation commits plan.hasRollout before marking the issue DONE. If// those two RPCs straddle that commit, refresh the older plan half once so a@@ -215,5 +267,6 @@ export const fetchPlanSnapshot = async (? { planCheckRuns: planCheckRunsResult.value }: {}),...(rolloutState ? rolloutState : {}),+ ...aiReviewRunPatch(issueResult, aiReviewRunResult),};};diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/types.ts b/frontend/src/routes/project/plan-detail/shell/hooks/types.tsindex 5cff7ba966..911899aaac 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/types.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/types.ts@@ -1,4 +1,4 @@-import { type Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Issue, ReviewRun } from "@/types/proto-es/v1/issue_service_pb";import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import {@@ -30,6 +30,9 @@ export interface PlanDetailPageSnapshot {rollout?: Rollout;planCheckRuns: PlanCheckRun[];taskRuns: TaskRun[];+ // The issue's AI review run: null when the slot has never run, undefined+ // when the page does not read it or has not read it yet.+ aiReviewRun?: ReviewRun | null;}export interface PlanDetailPageState extends PlanDetailPageSnapshot {diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsxindex f716df9980..adab999427 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx@@ -17,7 +17,11 @@ import {IssueStatus,State,} from "@/types/proto-es/v1/common_pb";-import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueSchema,+ ReviewRun_Status,+ ReviewRunSchema,+} from "@/types/proto-es/v1/issue_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";import {@@ -1423,6 +1427,62 @@ describe("usePlanDetailPage", () => {}});+ test("polls the AI review run actively from queued through running, then idles once it is done", async () => {+ vi.useFakeTimers();+ try {+ const patch = buildSnapshotPatch({ planId: "plan-1" });+ const withRun = (status: ReviewRun_Status) => ({+ ...patch,+ aiReviewRun: create(ReviewRunSchema, {+ name: "projects/foo/issues/1/reviewRuns/ai",+ status,+ }),+ });+ mocks.fetchPlanSnapshot+ .mockResolvedValueOnce(withRun(ReviewRun_Status.AVAILABLE))+ .mockResolvedValueOnce(withRun(ReviewRun_Status.RUNNING))+ .mockResolvedValue(withRun(ReviewRun_Status.DONE));++ const { result } = renderHook(+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),+ { wrapper }+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(result.current.aiReviewRun?.status).toBe(+ ReviewRun_Status.AVAILABLE+ );+ mocks.fetchPlanSnapshot.mockClear();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ expect(result.current.aiReviewRun?.status).toBe(ReviewRun_Status.RUNNING);+ mocks.fetchPlanSnapshot.mockClear();++ // A status change resets the active backoff to its 500ms floor.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(500);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ expect(result.current.aiReviewRun?.status).toBe(ReviewRun_Status.DONE);+ mocks.fetchPlanSnapshot.mockClear();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(999);+ });+ expect(mocks.fetchPlanSnapshot).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ });+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+test("keeps the active cadence from completed checks through approval finding", async () => {vi.useFakeTimers();try {diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.tsindex 101960a9ef..a5a575bf05 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts@@ -25,7 +25,10 @@ import {IssueStatus,State,} from "@/types/proto-es/v1/common_pb";-import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueSchema,+ ReviewRunSchema,+} from "@/types/proto-es/v1/issue_service_pb";import {PlanCheckRunSchema,PlanSchema,@@ -44,6 +47,7 @@ import { setDocumentTitle } from "@/utils";import { isTaskActivelyTransitioning } from "@/utils/v1/issue/rollout";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";+import { isAIReviewRunActive } from "../../utils/aiReviewRun";import {getPlanCheckSummary,isRolloutExpected,@@ -82,6 +86,7 @@ const buildDefaultSnapshot = (rollout: undefined,planCheckRuns: [],taskRuns: [],+ aiReviewRun: undefined,});const applyDerivedState = (@@ -132,6 +137,13 @@ const preserveSnapshotIdentities = (out.planCheckRuns = prev.planCheckRuns;}out.taskRuns = preserveTaskRunIdentities(prev.taskRuns, next.taskRuns);+ if (+ prev.aiReviewRun &&+ next.aiReviewRun &&+ sameMessage(ReviewRunSchema, prev.aiReviewRun, next.aiReviewRun)+ ) {+ out.aiReviewRun = prev.aiReviewRun;+ }const changed = (Object.keys(out) as (keyof PlanDetailPageSnapshot)[]).some((key) => out[key] !== prev[key]);@@ -443,10 +455,14 @@ export const usePlanDetailPage = ({snapshot.issue?.status,snapshot.issue?.approvalStatus,JSON.stringify(snapshot.plan.planCheckRunStatusCount),+ snapshot.aiReviewRun?.status,].join(":"),isPlanDone: false,pollingMode:- hasActivePlanChecks || approvalChecking || rolloutExpected+ hasActivePlanChecks ||+ approvalChecking ||+ rolloutExpected ||+ isAIReviewRunActive(snapshot.aiReviewRun)? "active": "idle",};@@ -492,11 +508,18 @@ export const usePlanDetailPage = ({isPlanDone: taskCount > 0 && allSettled && !hasActiveTaskRuns,pollingMode: shouldPollActively || hasActiveTaskRuns ? "active" : "idle",};- }, [snapshot.issue, snapshot.plan, snapshot.rollout, snapshot.taskRuns]);+ }, [+ snapshot.aiReviewRun,+ snapshot.issue,+ snapshot.plan,+ snapshot.rollout,+ snapshot.taskRuns,+ ]);// Poll the complete snapshot. Idle polling backs off from 1s to 16s. Active- // plan checks, approval finding, rollout creation, and task execution share a- // faster 500ms -> 1s -> 2s -> 4s cadence which resets when state changes.+ // plan checks, a queued or running AI review, approval finding, rollout+ // creation, and task execution share a faster 500ms -> 1s -> 2s -> 4s+ // cadence which resets when state changes.// Independent jitter prevents synchronized clients; hidden tabs pause until// they become visible again.const { restart: restartPolling } = usePlanPolling({diff --git a/frontend/src/routes/project/plan-detail/utils/aiReviewRun.test.ts b/frontend/src/routes/project/plan-detail/utils/aiReviewRun.test.tsnew file mode 100644index 0000000000..bee15de052--- /dev/null+++ b/frontend/src/routes/project/plan-detail/utils/aiReviewRun.test.ts@@ -0,0 +1,94 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import {+ DatabaseGroupSchema,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_CreateDatabaseConfigSchema,+ type Plan_Spec,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { hasReviewableSQL, loadedMatchedDatabaseCount } from "./aiReviewRun";++const GROUP = "projects/p/databaseGroups/g";+const DATABASE = "instances/i/databases/d";++const change = (targets: string[], release = ""): Plan_Spec["config"] => ({+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, { targets, release }),+});++const plan = (...configs: Plan_Spec["config"][]) =>+ create(PlanSchema, {+ specs: configs.map((config, i) => ({ id: `${i}`, config })),+ });++const groupMatching = (databases: string[]) =>+ loadedMatchedDatabaseCount({+ dbGroupsByName: {+ [GROUP]: create(DatabaseGroupSchema, {+ name: GROUP,+ matchedDatabases: databases.map((name) => ({ name })),+ }),+ },+ dbGroupViewByName: { [GROUP]: DatabaseGroupView.FULL },+ });++const notLoaded = loadedMatchedDatabaseCount({+ dbGroupsByName: {},+ dbGroupViewByName: {},+});++describe("hasReviewableSQL", () => {+ test("a change spec with database targets is reviewable", () => {+ expect(hasReviewableSQL(plan(change([DATABASE])), notLoaded)).toBe(true);+ });++ test("create-database and release-backed specs are not", () => {+ const createDatabase: Plan_Spec["config"] = {+ case: "createDatabaseConfig",+ value: create(Plan_CreateDatabaseConfigSchema, { database: "d" }),+ };+ expect(+ hasReviewableSQL(+ plan(createDatabase, change([DATABASE], "releases/r")),+ notLoaded+ )+ ).toBe(false);+ });++ test("a group that matches no databases is not", () => {+ expect(hasReviewableSQL(plan(change([GROUP])), groupMatching([]))).toBe(+ false+ );+ });++ test("a group with matched databases is", () => {+ expect(+ hasReviewableSQL(plan(change([GROUP])), groupMatching([DATABASE]))+ ).toBe(true);+ });++ test("a group not loaded yet counts as reviewable", () => {+ expect(hasReviewableSQL(plan(change([GROUP])), notLoaded)).toBe(true);+ });++ test("a group loaded without the full view counts as reviewable", () => {+ const basicView = loadedMatchedDatabaseCount({+ dbGroupsByName: { [GROUP]: create(DatabaseGroupSchema, { name: GROUP }) },+ dbGroupViewByName: { [GROUP]: DatabaseGroupView.BASIC },+ });+ expect(hasReviewableSQL(plan(change([GROUP])), basicView)).toBe(true);+ });++ test("an empty group beside a spec with a database is reviewable", () => {+ expect(+ hasReviewableSQL(+ plan(change([GROUP]), change([DATABASE])),+ groupMatching([])+ )+ ).toBe(true);+ });+});diff --git a/frontend/src/routes/project/plan-detail/utils/aiReviewRun.ts b/frontend/src/routes/project/plan-detail/utils/aiReviewRun.tsnew file mode 100644index 0000000000..17d426f30a--- /dev/null+++ b/frontend/src/routes/project/plan-detail/utils/aiReviewRun.ts@@ -0,0 +1,82 @@+import { isValidDatabaseGroupName } from "@/types/dbGroup";+import type { ActuatorInfo } from "@/types/proto-es/v1/actuator_service_pb";+import {+ type DatabaseGroup,+ DatabaseGroupView,+} from "@/types/proto-es/v1/database_group_service_pb";+import {+ type ReviewRun,+ ReviewRun_Status,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { sqlReviewV2Enabled } from "@/utils/featureGates";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";++// The issue's AI review slot. The name addresses the slot, not one execution.+export const aiReviewRunName = (issueName: string): string =>+ `${issueName}/reviewRuns/ai`;++// How many databases a database group matches, or undefined until the+// page has loaded the group's full view.+export type MatchedDatabaseCount = (group: string) => number | undefined;++export const loadedMatchedDatabaseCount =+ (state: {+ dbGroupsByName: Record<string, DatabaseGroup>;+ dbGroupViewByName: Record<string, DatabaseGroupView>;+ }): MatchedDatabaseCount =>+ (group) =>+ state.dbGroupViewByName[group] === DatabaseGroupView.FULL+ ? (state.dbGroupsByName[group]?.matchedDatabases.length ?? 0)+ : undefined;++// Mirrors the backend's DeriveReviewTargets, and RunReview refuses a plan it+// finds nothing in: create-database and release-backed specs carry no SQL,+// and a spec whose one target is a database group reviews the group's+// matched databases. A group not loaded yet counts as reviewable.+export const hasReviewableSQL = (+ plan: Plan,+ matchedDatabaseCount: MatchedDatabaseCount+): boolean =>+ plan.specs.some((spec) => {+ if (+ spec.config.case !== "changeDatabaseConfig" ||+ spec.config.value.release+ ) {+ return false;+ }+ const { targets } = spec.config.value;+ if (targets.length === 1 && isValidDatabaseGroupName(targets[0])) {+ return (matchedDatabaseCount(targets[0]) ?? 1) > 0;+ }+ return targets.length > 0;+ });++// Whether the plan page reads the issue's AI review run. The review is dark+// launched behind SQL Review V2, runs only while the workspace has AI and its+// review switch on, and reviews SQL that no rollout has frozen yet.+export const readsAIReviewRun = ({+ plan,+ project,+ serverInfo,+ matchedDatabaseCount,+}: {+ plan: Plan;+ project: Project;+ serverInfo: ActuatorInfo | undefined;+ matchedDatabaseCount: MatchedDatabaseCount;+}): boolean =>+ sqlReviewV2Enabled() &&+ Boolean(serverInfo?.aiEnabled && serverInfo.aiSqlReviewEnabled) &&+ Boolean(plan.issue) &&+ !plan.hasRollout &&+ hasReviewableSQL(plan, matchedDatabaseCount) &&+ hasProjectPermissionV2(project, "bb.reviewRuns.get");++// A queued or running execution; RunReview would replace it.+export const isAIReviewRunActive = (+ run: ReviewRun | null | undefined+): boolean =>+ run?.status === ReviewRun_Status.AVAILABLE ||+ run?.status === ReviewRun_Status.RUNNING;