Skip to content

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

feat(review): lay out the plan page around the automated reviewers (#21671)

rebelice35599755e330
diff --git a/frontend/src/components/ui/badge.tsx b/frontend/src/components/ui/badge.tsx
index 741f8860ae..bd3caa7bce 100644
--- a/frontend/src/components/ui/badge.tsx
+++ b/frontend/src/components/ui/badge.tsx
@@ -16,6 +16,8 @@ const badgeVariants = cva(
destructive: "bg-error/10 text-error",
warning: "bg-warning/10 text-warning",
success: "bg-success/10 text-success",
+ // A state someone must act on, kept readable on any surface.
+ attention: "border-warning bg-background text-warning-hover",
},
},
defaultVariants: {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index f9bf7b6d7c..3013d02510 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1780,12 +1780,54 @@
"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"
+ "run-again-description": "A run makes model calls for every database it reviews and may find different issues. Its findings replace the last run's, including the ones people resolved.",
+ "run-again-title": "Run the AI review again?",
+ "save-first": "Save or discard your edits to run the AI review."
+ },
+ "automated-review": {
+ "checks": "Plan check",
+ "details": "Details",
+ "failed": "Couldn't run",
+ "failed-to-rerun": "Could not start the review",
+ "ghost": "Online migration dry run",
+ "n-databases_one": "{{count}} database",
+ "n-databases_other": "{{count}} databases",
+ "n-errors_one": "{{count}} error",
+ "n-errors_other": "{{count}} errors",
+ "n-open": "{{count}} open",
+ "n-warnings_one": "{{count}} warning",
+ "n-warnings_other": "{{count}} warnings",
+ "needs-attention": "{{count}} of {{total}} needs attention",
+ "no-findings": "No findings",
+ "not-run": "Not run yet",
+ "nothing-needs-attention": "Nothing needs attention",
+ "opens-in-sql": "Click to step through them in the SQL.",
+ "out-of-date": "out of date",
+ "outdated": "SQL changed after this run",
+ "passed": "passed",
+ "passed-on_one": "Passed on {{count}} database",
+ "passed-on_other": "Passed on {{count}} databases",
+ "policy": "Review policy",
+ "project-rules": "Project rules: {{on}} of {{total}} on",
+ "report": "Statement report",
+ "rerun": "Rerun",
+ "rerun-all": "Re-run all",
+ "rerun-all-description_one": "This reruns the plan checks and Standard rules. {{count}} Standard rules finding people resolved will come back as open.",
+ "rerun-all-description_other": "This reruns the plan checks and Standard rules. {{count}} Standard rules findings people resolved will come back as open.",
+ "rerun-all-title": "Re-run all checks?",
+ "rerun-reopens_one": "{{count}} finding people resolved will come back as open and need resolving again.",
+ "rerun-reopens_other": "{{count}} findings people resolved will come back as open and need resolving again.",
+ "rerun-rule-title": "Rerun Standard rules?",
+ "retry": "Retry",
+ "running": "Running",
+ "sampled": "a sample of {{count}} of {{total}} databases",
+ "scope": "Reviewed {{databases}}",
+ "scope-label": "What this review covered",
+ "scope-with-engines": "Reviewed {{databases}} ({{engines}})",
+ "self": "Automated review",
+ "summary-part": "{{reviewer}}: {{status}}",
+ "workspace-rules": "Workspace rules: {{on}} of {{total}} on"
},
"blocker": {
"clears-on-its-own": "Clears on its own"
@@ -1800,6 +1842,28 @@
"started": "Plan checks started"
},
"create-plan": "Create Plan",
+ "deploy-waiting": {
+ "approval": "Approval",
+ "approval-from": "Approval from {{role}}",
+ "approval-rejected": "Approval rejected",
+ "auto-create": "Bytebase creates the rollout when all of these pass.",
+ "creating-rollout": "Everything passed; creating the rollout…",
+ "manual-rollout": "Bytebase doesn't create this plan's rollout automatically; deploy it once these pass.",
+ "open-discussions_one": "{{count}} open discussion",
+ "open-discussions_other": "{{count}} open discussions",
+ "overridden_one": "{{count}} P0 finding in {{reviewer}} was resolved without a change",
+ "overridden_other": "{{count}} P0 findings in {{reviewer}} were resolved without a change",
+ "ready-to-deploy": "Everything passed; ready to deploy.",
+ "reviewer-failed": "{{reviewer}} couldn't run",
+ "reviewer-findings": "{{reviewer}}: {{findings}}",
+ "reviewer-not-run": "{{reviewer}} has not run",
+ "reviewer-outdated": "SQL changed after {{reviewer}} ran",
+ "reviewer-running": "{{reviewer}} is running",
+ "show": "Show",
+ "submit": "Submit for review",
+ "waiting-on": "Waiting on",
+ "worth-a-look": "Does not hold the rollout, but worth a look"
+ },
"description": {
"placeholder": "Add description"
},
@@ -1807,6 +1871,21 @@
"editor": {
"save-changes-before-continuing": "Please save or cancel your changes before continuing"
},
+ "findings": {
+ "n-more": "{{count}} more",
+ "n-overridden": "{{count}} P0 resolved without a change",
+ "n-priority": "{{count}} {{priority}}",
+ "n-resolved": "{{count}} resolved",
+ "name-at-line": "{{name}} (L{{line}})",
+ "name-times": "{{name}} ×{{count}}",
+ "separator": ", ",
+ "set": {
+ "earlier": "earlier runs",
+ "open": "open",
+ "overridden": "P0 resolved without a change",
+ "resolved": "resolved"
+ }
+ },
"ghost": {
"configure": "Configure",
"parameters": "gh-ost parameters",
@@ -1829,19 +1908,18 @@
"checking": "Checking…",
"checks-failing": "Checks failing",
"deployed": "Deployed",
+ "gate-automated-review-passed": "Automated review passed",
"gate-checks-failed": "Some checks were not successful",
"gate-checks-failed-sub": "{{failing}} failing, {{passed}} passed",
"gate-checks-passed": "All checks passed",
"gate-checks-passed-sub": "{{count}} passed",
"gate-checks-running": "Checks are running",
"gate-checks-running-sub": "{{running}} running, {{passed}} passed",
+ "gate-no-open-discussions": "No open discussions",
"gate-review-approved": "Changes approved",
"gate-review-pending": "Review in progress",
"gate-review-rejected": "Changes requested",
"gate-threads-open-sub": "Resolve every thread to create the rollout",
- "gate-threads-open_one": "{{count}} unresolved thread",
- "gate-threads-open_other": "{{count}} unresolved threads",
- "gate-threads-resolved": "All threads resolved",
"incomplete": "Incomplete",
"preparing-rollout": "Preparing rollout…",
"rejected": "Rejected",
@@ -1888,11 +1966,15 @@
"add-a-comment": "Add a comment...",
"created-this-plan": "created this plan",
"marked-ready-for-review": "marked this plan ready for review",
+ "n-findings_one": "{{count}} finding",
+ "n-findings_other": "{{count}} findings",
"n-hidden-events_one": "{{count}} hidden event",
"n-hidden-events_other": "{{count}} hidden events",
+ "reviewed-the-sql": "reviewed the SQL",
"self": "Activity",
"show-all": "Show all"
},
+ "approval-after-submit": "Approval starts when you submit for review.",
"approval-flow": {
"and-n-more_one": "and {{count}} more",
"and-n-more_other": "and {{count}} more",
@@ -1968,6 +2050,7 @@
"n-replies-hidden_other": "{{count}} replies hidden",
"n-replies_one": "{{count}} reply",
"n-replies_other": "{{count}} replies",
+ "open": "Open",
"priority": {
"p0": "The SQL is wrong and must change.",
"p1": "Dangerous but legitimate. A person must accept it.",
@@ -1985,8 +2068,10 @@
"threads-on-line_one": "{{count}} thread on this line",
"threads-on-line_other": "{{count}} threads on this line",
"walker": {
+ "clear-filter": "Step through every open thread",
"count_one": "{{count}} unresolved thread on this version",
"count_other": "{{count}} unresolved threads on this version",
+ "filter": "{{reviewer}} · {{state}}",
"next": "Next unresolved thread",
"position": "Thread {{index}} of {{count}}",
"previous": "Previous unresolved thread",
@@ -2001,16 +2086,6 @@
"description_other": "Roll back {{count}} selected tasks from rollout #{{rolloutId}}.",
"title": "Rollback rollout #{{rolloutId}}"
},
- "rule-review": {
- "failed": "SQL review failed",
- "load-failed": "The SQL review status could not be loaded.",
- "no-open-findings": "No open findings",
- "not-run": "SQL review not run",
- "open-findings_one": "{{count}} open finding",
- "open-findings_other": "{{count}} open findings",
- "queued": "SQL review queued",
- "running": "SQL review running"
- },
"run": "Run checks",
"select-isolation-level": "Select isolation level",
"select-targets": "Select Targets",
@@ -2035,9 +2110,14 @@
"reopen-confirm": "Reopen this plan?",
"reopen-review-confirm": "Reopen this review?"
},
+ "statement-summary": {
+ "affected-rows_one": "~{{count}} row affected",
+ "affected-rows_other": "~{{count}} rows affected"
+ },
"submit-review-anyway": "Submit anyway",
"subtitle": "Draft database changes and run pre-checks before creating an issue for approval.",
"summary": {
+ "approved-by": "Approved by {{names}}",
"last-approved-by": "Last approved by {{name}}",
"n-changes": "{{n}} changes",
"n-database-groups": "{{n}} database groups",
@@ -2048,7 +2128,8 @@
"n-passed": "{{n}} passed",
"n-unresolved-threads_one": "{{count}} unresolved thread",
"n-unresolved-threads_other": "{{count}} unresolved threads",
- "n-warning": "{{n}} warning"
+ "n-warning": "{{n}} warning",
+ "no-approval-required": "No approval required"
},
"targets": {
"no-targets-found": "No targets found",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 09edfb0230..eb813bc87c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1780,12 +1780,54 @@
"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"
+ "run-again-description": "Cada ejecución llama al modelo por cada base de datos revisada y puede encontrar problemas distintos. Sus hallazgos sustituyen a los de la ejecución anterior, incluidos los que ya se resolvieron.",
+ "run-again-title": "¿Ejecutar de nuevo la revisión con IA?",
+ "save-first": "Guarda o descarta tus cambios para ejecutar la revisión con IA."
+ },
+ "automated-review": {
+ "checks": "Comprobación del plan",
+ "details": "Detalles",
+ "failed": "No se pudo ejecutar",
+ "failed-to-rerun": "No se pudo iniciar la revisión",
+ "ghost": "Simulación de migración en línea",
+ "n-databases_one": "{{count}} base de datos",
+ "n-databases_other": "{{count}} bases de datos",
+ "n-errors_one": "{{count}} error",
+ "n-errors_other": "{{count}} errores",
+ "n-open": "{{count}} abiertos",
+ "n-warnings_one": "{{count}} advertencia",
+ "n-warnings_other": "{{count}} advertencias",
+ "needs-attention": "{{count}} de {{total}} requieren atención",
+ "no-findings": "Sin hallazgos",
+ "not-run": "Aún no se ha ejecutado",
+ "nothing-needs-attention": "Nada requiere atención",
+ "opens-in-sql": "Haz clic para recorrerlos en el SQL.",
+ "out-of-date": "desactualizado",
+ "outdated": "El SQL cambió después de esta ejecución",
+ "passed": "aprobado",
+ "passed-on_one": "Aprobado en {{count}} base de datos",
+ "passed-on_other": "Aprobado en {{count}} bases de datos",
+ "policy": "Política de revisión",
+ "project-rules": "Reglas del proyecto: {{on}} de {{total}} activas",
+ "report": "Informe de sentencias",
+ "rerun": "Volver a ejecutar",
+ "rerun-all": "Volver a ejecutar todo",
+ "rerun-all-description_one": "Se vuelven a ejecutar las comprobaciones del plan y Standard rules. {{count}} hallazgo ya resuelto de Standard rules volverá a quedar abierto.",
+ "rerun-all-description_other": "Se vuelven a ejecutar las comprobaciones del plan y Standard rules. {{count}} hallazgos ya resueltos de Standard rules volverán a quedar abiertos.",
+ "rerun-all-title": "¿Volver a ejecutar todas las comprobaciones?",
+ "rerun-reopens_one": "{{count}} hallazgo ya resuelto volverá a quedar abierto y habrá que resolverlo de nuevo.",
+ "rerun-reopens_other": "{{count}} hallazgos ya resueltos volverán a quedar abiertos y habrá que resolverlos de nuevo.",
+ "rerun-rule-title": "¿Volver a ejecutar Standard rules?",
+ "retry": "Reintentar",
+ "running": "En ejecución",
+ "sampled": "una muestra de {{count}} de {{total}} bases de datos",
+ "scope": "Se revisó {{databases}}",
+ "scope-label": "Qué cubrió esta revisión",
+ "scope-with-engines": "Se revisó {{databases}} ({{engines}})",
+ "self": "Revisión automática",
+ "summary-part": "{{reviewer}}: {{status}}",
+ "workspace-rules": "Reglas del espacio de trabajo: {{on}} de {{total}} activas"
},
"blocker": {
"clears-on-its-own": "Se resuelve solo"
@@ -1800,6 +1842,28 @@
"started": "Se iniciaron las verificaciones del plan"
},
"create-plan": "Crear plan",
+ "deploy-waiting": {
+ "approval": "Aprobación",
+ "approval-from": "Aprobación de {{role}}",
+ "approval-rejected": "Aprobación rechazada",
+ "auto-create": "Bytebase crea el despliegue cuando todo esto se cumple.",
+ "creating-rollout": "Todo aprobado; creando el despliegue…",
+ "manual-rollout": "Bytebase no crea automáticamente el despliegue de este plan; despliégalo cuando todo esto se cumpla.",
+ "open-discussions_one": "{{count}} conversación abierta",
+ "open-discussions_other": "{{count}} conversaciones abiertas",
+ "overridden_one": "{{count}} hallazgo P0 de {{reviewer}} se resolvió sin cambios",
+ "overridden_other": "{{count}} hallazgos P0 de {{reviewer}} se resolvieron sin cambios",
+ "ready-to-deploy": "Todo superado; listo para desplegar.",
+ "reviewer-failed": "{{reviewer}} no se pudo ejecutar",
+ "reviewer-findings": "{{reviewer}}: {{findings}}",
+ "reviewer-not-run": "{{reviewer}} aún no se ha ejecutado",
+ "reviewer-outdated": "El SQL cambió después de ejecutar {{reviewer}}",
+ "reviewer-running": "{{reviewer}} en ejecución",
+ "show": "Mostrar",
+ "submit": "Enviar a revisión",
+ "waiting-on": "En espera de",
+ "worth-a-look": "No detiene el despliegue, pero conviene revisarlo"
+ },
"description": {
"placeholder": "Agregar descripción"
},
@@ -1807,6 +1871,21 @@
"editor": {
"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."
},
+ "findings": {
+ "n-more": "{{count}} más",
+ "n-overridden": "{{count}} P0 resueltos sin cambios",
+ "n-priority": "{{count}} {{priority}}",
+ "n-resolved": "{{count}} resueltos",
+ "name-at-line": "{{name}} (L{{line}})",
+ "name-times": "{{name}} ×{{count}}",
+ "separator": ", ",
+ "set": {
+ "earlier": "ejecuciones anteriores",
+ "open": "abiertos",
+ "overridden": "P0 resueltos sin cambios",
+ "resolved": "resueltos"
+ }
+ },
"ghost": {
"configure": "Configurar",
"parameters": "Parámetros de gh-ost",
@@ -1829,19 +1908,18 @@
"checking": "Comprobando…",
"checks-failing": "Comprobaciones fallidas",
"deployed": "Desplegado",
+ "gate-automated-review-passed": "La revisión automática se aprobó",
"gate-checks-failed": "Algunas comprobaciones fallaron",
"gate-checks-failed-sub": "{{failing}} con errores, {{passed}} correctas",
"gate-checks-passed": "Todas las comprobaciones correctas",
"gate-checks-passed-sub": "{{count}} correctas",
"gate-checks-running": "Comprobaciones en curso",
"gate-checks-running-sub": "{{running}} en curso, {{passed}} correctas",
+ "gate-no-open-discussions": "No hay conversaciones abiertas",
"gate-review-approved": "Cambios aprobados",
"gate-review-pending": "Revisión en curso",
"gate-review-rejected": "Cambios solicitados",
"gate-threads-open-sub": "Resuelve todos los hilos para crear el rollout",
- "gate-threads-open_one": "{{count}} hilo sin resolver",
- "gate-threads-open_other": "{{count}} hilos sin resolver",
- "gate-threads-resolved": "Todos los hilos resueltos",
"incomplete": "Incompleto",
"preparing-rollout": "Preparando despliegue…",
"rejected": "Rechazado",
@@ -1888,11 +1966,15 @@
"add-a-comment": "Añadir un comentario...",
"created-this-plan": "creó este plan",
"marked-ready-for-review": "marcó este plan como listo para revisión",
+ "n-findings_one": "{{count}} hallazgo",
+ "n-findings_other": "{{count}} hallazgos",
"n-hidden-events_one": "{{count}} evento oculto",
"n-hidden-events_other": "{{count}} eventos ocultos",
+ "reviewed-the-sql": "revisó el SQL",
"self": "Actividad",
"show-all": "Mostrar todo"
},
+ "approval-after-submit": "La aprobación empieza cuando envías a revisión.",
"approval-flow": {
"and-n-more_one": "y {{count}} más",
"and-n-more_other": "y {{count}} más",
@@ -1968,6 +2050,7 @@
"n-replies-hidden_other": "{{count}} respuestas ocultas",
"n-replies_one": "{{count}} respuesta",
"n-replies_other": "{{count}} respuestas",
+ "open": "Abierto",
"priority": {
"p0": "El SQL es incorrecto y debe cambiar.",
"p1": "Peligroso pero legítimo. Una persona debe aceptarlo.",
@@ -1985,8 +2068,10 @@
"threads-on-line_one": "{{count}} hilo en esta línea",
"threads-on-line_other": "{{count}} hilos en esta línea",
"walker": {
+ "clear-filter": "Recorrer todos los hilos abiertos",
"count_one": "{{count}} hilo sin resolver en esta versión",
"count_other": "{{count}} hilos sin resolver en esta versión",
+ "filter": "{{reviewer}} · {{state}}",
"next": "Siguiente hilo sin resolver",
"position": "Hilo {{index}} de {{count}}",
"previous": "Hilo sin resolver anterior",
@@ -2001,16 +2086,6 @@
"description_other": "Revertir {{count}} tareas seleccionadas del rollout #{{rolloutId}}.",
"title": "Revertir rollout #{{rolloutId}}"
},
- "rule-review": {
- "failed": "La revisión SQL falló",
- "load-failed": "No se pudo cargar el estado de la revisión SQL.",
- "no-open-findings": "No hay hallazgos abiertos",
- "not-run": "Revisión SQL no ejecutada",
- "open-findings_one": "{{count}} hallazgo abierto",
- "open-findings_other": "{{count}} hallazgos abiertos",
- "queued": "Revisión SQL en cola",
- "running": "Revisión SQL en curso"
- },
"run": "Volver a verificar",
"select-isolation-level": "Seleccionar nivel de aislamiento",
"select-targets": "Seleccionar destinos",
@@ -2035,9 +2110,14 @@
"reopen-confirm": "¿Reabrir este plan?",
"reopen-review-confirm": "¿Reabrir esta revisión?"
},
+ "statement-summary": {
+ "affected-rows_one": "~{{count}} fila afectada",
+ "affected-rows_other": "~{{count}} filas afectadas"
+ },
"submit-review-anyway": "Enviar de todos modos",
"subtitle": "Redactar cambios en la base de datos y ejecutar comprobaciones previas antes de crear un problema para su aprobación.",
"summary": {
+ "approved-by": "Aprobado por {{names}}",
"last-approved-by": "Última aprobación por {{name}}",
"n-changes": "{{n}} cambios",
"n-database-groups": "{{n}} grupos de bases de datos",
@@ -2048,7 +2128,8 @@
"n-passed": "{{n}} aprobadas",
"n-unresolved-threads_one": "{{count}} hilo sin resolver",
"n-unresolved-threads_other": "{{count}} hilos sin resolver",
- "n-warning": "{{n}} advertencia"
+ "n-warning": "{{n}} advertencia",
+ "no-approval-required": "No requiere aprobación"
},
"targets": {
"no-targets-found": "No se encontraron objetivos",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 762f5fbb7a..b32f2d3eaf 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1780,12 +1780,54 @@
"add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください",
"ai-review": {
"failed-to-run": "AI レビューを開始できませんでした",
- "finished": "完了",
- "not-run": "未実行",
- "queued": "待機中",
"run": "AI レビューを実行",
- "save-first": "AI レビューを実行するには、編集内容を保存または破棄してください。",
- "status-unknown": "状態を取得できません"
+ "run-again-description": "実行するたびにレビュー対象の各データベースでモデルを呼び出すため、結果が異なる場合があります。新しい検出事項は、解決済みのものを含め前回の結果を置き換えます。",
+ "run-again-title": "AI レビューを再実行しますか?",
+ "save-first": "AI レビューを実行するには、編集内容を保存または破棄してください。"
+ },
+ "automated-review": {
+ "checks": "プランチェック",
+ "details": "詳細",
+ "failed": "実行できませんでした",
+ "failed-to-rerun": "レビューを開始できませんでした",
+ "ghost": "オンラインマイグレーションのドライラン",
+ "n-databases_one": "{{count}} 個のデータベース",
+ "n-databases_other": "{{count}} 個のデータベース",
+ "n-errors_one": "{{count}} 件のエラー",
+ "n-errors_other": "{{count}} 件のエラー",
+ "n-open": "未解決 {{count}} 件",
+ "n-warnings_one": "{{count}} 件の警告",
+ "n-warnings_other": "{{count}} 件の警告",
+ "needs-attention": "{{total}} 件中 {{count}} 件に対応が必要",
+ "no-findings": "検出事項なし",
+ "not-run": "未実行",
+ "nothing-needs-attention": "対応が必要な項目はありません",
+ "opens-in-sql": "クリックすると SQL 内で順に確認できます。",
+ "out-of-date": "古い結果",
+ "outdated": "この実行後に SQL が変更されました",
+ "passed": "合格",
+ "passed-on_one": "{{count}} 個のデータベースで合格",
+ "passed-on_other": "{{count}} 個のデータベースで合格",
+ "policy": "レビューポリシー",
+ "project-rules": "プロジェクトのルール:{{total}} 件中 {{on}} 件が有効",
+ "report": "ステートメントレポート",
+ "rerun": "再実行",
+ "rerun-all": "すべて再実行",
+ "rerun-all-description_one": "プランチェックと Standard rules を再実行します。Standard rules の解決済みの検出事項 {{count}} 件が未解決に戻ります。",
+ "rerun-all-description_other": "プランチェックと Standard rules を再実行します。Standard rules の解決済みの検出事項 {{count}} 件が未解決に戻ります。",
+ "rerun-all-title": "すべて再実行しますか?",
+ "rerun-reopens_one": "解決済みの検出事項 {{count}} 件が未解決に戻り、再度対応が必要になります。",
+ "rerun-reopens_other": "解決済みの検出事項 {{count}} 件が未解決に戻り、再度対応が必要になります。",
+ "rerun-rule-title": "Standard rules を再実行しますか?",
+ "retry": "再試行",
+ "running": "実行中",
+ "sampled": "{{total}} 個中 {{count}} 個のデータベースを抽出",
+ "scope": "{{databases}} をレビュー",
+ "scope-label": "このレビューの対象",
+ "scope-with-engines": "{{databases}}({{engines}})をレビュー",
+ "self": "自動レビュー",
+ "summary-part": "{{reviewer}}: {{status}}",
+ "workspace-rules": "ワークスペースのルール:{{total}} 件中 {{on}} 件が有効"
},
"blocker": {
"clears-on-its-own": "自動的に解消されます"
@@ -1800,6 +1842,28 @@
"started": "プランチェックを開始しました"
},
"create-plan": "プランを作成",
+ "deploy-waiting": {
+ "approval": "承認",
+ "approval-from": "{{role}} の承認",
+ "approval-rejected": "承認が却下されました",
+ "auto-create": "これらがすべて合格すると、Bytebase がロールアウトを作成します。",
+ "creating-rollout": "すべて合格しました。ロールアウトを作成しています…",
+ "manual-rollout": "このプランのロールアウトは自動作成されません。上記がすべて通過したら手動でデプロイしてください。",
+ "open-discussions_one": "未解決のディスカッション {{count}} 件",
+ "open-discussions_other": "未解決のディスカッション {{count}} 件",
+ "overridden_one": "{{reviewer}} の P0 の検出事項 {{count}} 件が変更されずに解決されました",
+ "overridden_other": "{{reviewer}} の P0 の検出事項 {{count}} 件が変更されずに解決されました",
+ "ready-to-deploy": "すべて通過しました。デプロイできます。",
+ "reviewer-failed": "{{reviewer}} を実行できませんでした",
+ "reviewer-findings": "{{reviewer}}:{{findings}}",
+ "reviewer-not-run": "{{reviewer}} は未実行です",
+ "reviewer-outdated": "{{reviewer}} の実行後に SQL が変更されました",
+ "reviewer-running": "{{reviewer}} を実行中",
+ "show": "表示",
+ "submit": "レビューに提出",
+ "waiting-on": "待機中の項目",
+ "worth-a-look": "ロールアウトは止めませんが、確認をおすすめします"
+ },
"description": {
"placeholder": "説明を追加"
},
@@ -1807,6 +1871,21 @@
"editor": {
"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"
},
+ "findings": {
+ "n-more": "他 {{count}} 件",
+ "n-overridden": "変更せずに解決した P0 {{count}} 件",
+ "n-priority": "{{priority}} {{count}} 件",
+ "n-resolved": "解決済み {{count}} 件",
+ "name-at-line": "{{name}}(L{{line}})",
+ "name-times": "{{name}} ×{{count}}",
+ "separator": "、",
+ "set": {
+ "earlier": "以前の実行",
+ "open": "未解決",
+ "overridden": "変更せずに解決した P0",
+ "resolved": "解決済み"
+ }
+ },
"ghost": {
"configure": "設定",
"parameters": "gh-ost パラメータ",
@@ -1829,19 +1908,18 @@
"checking": "チェック中…",
"checks-failing": "チェック失敗",
"deployed": "デプロイ済み",
+ "gate-automated-review-passed": "自動レビューに合格",
"gate-checks-failed": "一部のチェックが失敗しました",
"gate-checks-failed-sub": "{{failing}} 件失敗、{{passed}} 件成功",
"gate-checks-passed": "すべてのチェックに合格",
"gate-checks-passed-sub": "{{count}} 件成功",
"gate-checks-running": "チェックを実行中",
"gate-checks-running-sub": "{{running}} 件実行中、{{passed}} 件成功",
+ "gate-no-open-discussions": "未解決のディスカッションはありません",
"gate-review-approved": "変更が承認されました",
"gate-review-pending": "レビュー中",
"gate-review-rejected": "変更がリクエストされました",
"gate-threads-open-sub": "すべてのスレッドを解決するとロールアウトが作成されます",
- "gate-threads-open_one": "未解決のスレッド {{count}} 件",
- "gate-threads-open_other": "未解決のスレッド {{count}} 件",
- "gate-threads-resolved": "すべてのスレッドが解決済み",
"incomplete": "未完了",
"preparing-rollout": "ロールアウトを準備中…",
"rejected": "却下されました",
@@ -1888,11 +1966,15 @@
"add-a-comment": "コメントを追加...",
"created-this-plan": "がこのプランを作成しました",
"marked-ready-for-review": "がこのプランをレビュー準備完了にしました",
+ "n-findings_one": "検出事項 {{count}} 件",
+ "n-findings_other": "検出事項 {{count}} 件",
"n-hidden-events_one": "{{count}} 件の非表示イベント",
"n-hidden-events_other": "{{count}} 件の非表示イベント",
+ "reviewed-the-sql": "が SQL をレビューしました",
"self": "アクティビティ",
"show-all": "すべて表示"
},
+ "approval-after-submit": "レビューに提出すると承認が始まります。",
"approval-flow": {
"and-n-more_one": "他 {{count}} 名",
"and-n-more_other": "他 {{count}} 名",
@@ -1968,6 +2050,7 @@
"n-replies-hidden_other": "{{count}} 件の返信が非表示",
"n-replies_one": "{{count}} 件の返信",
"n-replies_other": "{{count}} 件の返信",
+ "open": "未解決",
"priority": {
"p0": "SQL に誤りがあり、修正が必要です。",
"p1": "危険ですが正当な変更です。担当者による承認が必要です。",
@@ -1985,8 +2068,10 @@
"threads-on-line_one": "この行に {{count}} 件のスレッド",
"threads-on-line_other": "この行に {{count}} 件のスレッド",
"walker": {
+ "clear-filter": "すべての未解決スレッドを順に表示",
"count_one": "このバージョンに未解決のスレッドが {{count}} 件",
"count_other": "このバージョンに未解決のスレッドが {{count}} 件",
+ "filter": "{{reviewer}} · {{state}}",
"next": "次の未解決スレッド",
"position": "{{count}} 件中 {{index}} 件目",
"previous": "前の未解決スレッド",
@@ -2001,16 +2086,6 @@
"description_other": "ロールアウト #{{rolloutId}} の選択したタスク {{count}} 件をロールバックします。",
"title": "ロールアウト #{{rolloutId}} のロールバック"
},
- "rule-review": {
- "failed": "SQL レビューに失敗しました",
- "load-failed": "SQL レビューの状態を読み込めませんでした。",
- "no-open-findings": "未解決の指摘はありません",
- "not-run": "SQL レビュー未実行",
- "open-findings_one": "未解決の指摘 {{count}} 件",
- "open-findings_other": "未解決の指摘 {{count}} 件",
- "queued": "SQL レビュー待機中",
- "running": "SQL レビュー実行中"
- },
"run": "再チェック",
"select-isolation-level": "分離レベルを選択",
"select-targets": "対象を選択",
@@ -2035,9 +2110,14 @@
"reopen-confirm": "このプランを再開きますか?",
"reopen-review-confirm": "このレビューを再開しますか?"
},
+ "statement-summary": {
+ "affected-rows_one": "約 {{count}} 行に影響",
+ "affected-rows_other": "約 {{count}} 行に影響"
+ },
"submit-review-anyway": "それでも提出する",
"subtitle": "承認のためにイシューを作成する前に、データベースの変更を下書きし、事前チェックを実行します。",
"summary": {
+ "approved-by": "{{names}} が承認",
"last-approved-by": "{{name}} が最後に承認",
"n-changes": "{{n}} 件の変更",
"n-database-groups": "{{n}} 個のデータベースグループ",
@@ -2048,7 +2128,8 @@
"n-passed": "{{n}} 件合格",
"n-unresolved-threads_one": "未解決のスレッド {{count}} 件",
"n-unresolved-threads_other": "未解決のスレッド {{count}} 件",
- "n-warning": "{{n}} 件の警告"
+ "n-warning": "{{n}} 件の警告",
+ "no-approval-required": "承認不要"
},
"targets": {
"no-targets-found": "対象が見つかりません",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 7a0e4e948f..07a655419b 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1780,12 +1780,54 @@
"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"
+ "run-again-description": "Mỗi lần chạy sẽ gọi mô hình cho từng cơ sở dữ liệu được đánh giá và có thể cho kết quả khác. Phát hiện mới sẽ thay thế phát hiện của lần chạy trước, kể cả những mục đã được giải quyết.",
+ "run-again-title": "Chạy lại đánh giá AI?",
+ "save-first": "Hãy lưu hoặc hủy các thay đổi để chạy đánh giá bằng AI."
+ },
+ "automated-review": {
+ "checks": "Kiểm tra kế hoạch",
+ "details": "Chi tiết",
+ "failed": "Không thể chạy",
+ "failed-to-rerun": "Không thể bắt đầu đánh giá",
+ "ghost": "Chạy thử di chuyển trực tuyến",
+ "n-databases_one": "{{count}} cơ sở dữ liệu",
+ "n-databases_other": "{{count}} cơ sở dữ liệu",
+ "n-errors_one": "{{count}} lỗi",
+ "n-errors_other": "{{count}} lỗi",
+ "n-open": "{{count}} đang mở",
+ "n-warnings_one": "{{count}} cảnh báo",
+ "n-warnings_other": "{{count}} cảnh báo",
+ "needs-attention": "{{count}}/{{total}} cần xử lý",
+ "no-findings": "Không có phát hiện",
+ "not-run": "Chưa chạy",
+ "nothing-needs-attention": "Không có mục nào cần xử lý",
+ "opens-in-sql": "Nhấp để xem lần lượt trong SQL.",
+ "out-of-date": "đã cũ",
+ "outdated": "SQL đã thay đổi sau lần chạy này",
+ "passed": "đạt",
+ "passed-on_one": "Đạt trên {{count}} cơ sở dữ liệu",
+ "passed-on_other": "Đạt trên {{count}} cơ sở dữ liệu",
+ "policy": "Chính sách đánh giá",
+ "project-rules": "Quy tắc dự án: bật {{on}}/{{total}}",
+ "report": "Báo cáo câu lệnh",
+ "rerun": "Chạy lại",
+ "rerun-all": "Chạy lại tất cả",
+ "rerun-all-description_one": "Thao tác này chạy lại kiểm tra kế hoạch và Standard rules. {{count}} phát hiện đã được giải quyết của Standard rules sẽ mở lại.",
+ "rerun-all-description_other": "Thao tác này chạy lại kiểm tra kế hoạch và Standard rules. {{count}} phát hiện đã được giải quyết của Standard rules sẽ mở lại.",
+ "rerun-all-title": "Chạy lại tất cả kiểm tra?",
+ "rerun-reopens_one": "{{count}} phát hiện đã được giải quyết sẽ mở lại và cần giải quyết lại.",
+ "rerun-reopens_other": "{{count}} phát hiện đã được giải quyết sẽ mở lại và cần giải quyết lại.",
+ "rerun-rule-title": "Chạy lại Standard rules?",
+ "retry": "Thử lại",
+ "running": "Đang chạy",
+ "sampled": "lấy mẫu {{count}}/{{total}} cơ sở dữ liệu",
+ "scope": "Đã đánh giá {{databases}}",
+ "scope-label": "Phạm vi của lần đánh giá này",
+ "scope-with-engines": "Đã đánh giá {{databases}} ({{engines}})",
+ "self": "Đánh giá tự động",
+ "summary-part": "{{reviewer}}: {{status}}",
+ "workspace-rules": "Quy tắc không gian làm việc: bật {{on}}/{{total}}"
},
"blocker": {
"clears-on-its-own": "Tự động hoàn tất"
@@ -1800,6 +1842,28 @@
"started": "Đã bắt đầu kiểm tra kế hoạch"
},
"create-plan": "Tạo kế hoạch",
+ "deploy-waiting": {
+ "approval": "Phê duyệt",
+ "approval-from": "Phê duyệt từ {{role}}",
+ "approval-rejected": "Phê duyệt bị từ chối",
+ "auto-create": "Bytebase sẽ tạo bản triển khai khi tất cả các mục này đạt.",
+ "creating-rollout": "Tất cả đã đạt; đang tạo bản triển khai…",
+ "manual-rollout": "Bytebase không tự động tạo bản triển khai cho kế hoạch này; hãy triển khai khi các mục trên đều đạt.",
+ "open-discussions_one": "{{count}} thảo luận đang mở",
+ "open-discussions_other": "{{count}} thảo luận đang mở",
+ "overridden_one": "{{count}} phát hiện P0 trong {{reviewer}} đã được giải quyết mà không sửa",
+ "overridden_other": "{{count}} phát hiện P0 trong {{reviewer}} đã được giải quyết mà không sửa",
+ "ready-to-deploy": "Mọi thứ đã đạt; sẵn sàng triển khai.",
+ "reviewer-failed": "{{reviewer}} không thể chạy",
+ "reviewer-findings": "{{reviewer}}: {{findings}}",
+ "reviewer-not-run": "{{reviewer}} chưa chạy",
+ "reviewer-outdated": "SQL đã thay đổi sau khi {{reviewer}} chạy",
+ "reviewer-running": "{{reviewer}} đang chạy",
+ "show": "Xem",
+ "submit": "Gửi để đánh giá",
+ "waiting-on": "Đang chờ",
+ "worth-a-look": "Không chặn bản triển khai, nhưng nên xem qua"
+ },
"description": {
"placeholder": "Thêm mô tả"
},
@@ -1807,6 +1871,21 @@
"editor": {
"save-changes-before-continuing": "Vui lòng lưu hoặc hủy thay đổi của bạn trước khi tiếp tục"
},
+ "findings": {
+ "n-more": "{{count}} mục khác",
+ "n-overridden": "{{count}} P0 đã giải quyết mà không sửa",
+ "n-priority": "{{count}} {{priority}}",
+ "n-resolved": "{{count}} đã giải quyết",
+ "name-at-line": "{{name}} (L{{line}})",
+ "name-times": "{{name}} ×{{count}}",
+ "separator": ", ",
+ "set": {
+ "earlier": "các lần chạy trước",
+ "open": "đang mở",
+ "overridden": "P0 đã giải quyết mà không sửa",
+ "resolved": "đã giải quyết"
+ }
+ },
"ghost": {
"configure": "Cấu hình",
"parameters": "Tham số gh-ost",
@@ -1829,19 +1908,18 @@
"checking": "Đang kiểm tra…",
"checks-failing": "Kiểm tra thất bại",
"deployed": "Đã triển khai",
+ "gate-automated-review-passed": "Đánh giá tự động đã đạt",
"gate-checks-failed": "Một số kiểm tra không thành công",
"gate-checks-failed-sub": "{{failing}} thất bại, {{passed}} thành công",
"gate-checks-passed": "Tất cả kiểm tra đã qua",
"gate-checks-passed-sub": "{{count}} thành công",
"gate-checks-running": "Đang chạy kiểm tra",
"gate-checks-running-sub": "{{running}} đang chạy, {{passed}} thành công",
+ "gate-no-open-discussions": "Không có thảo luận đang mở",
"gate-review-approved": "Đã duyệt thay đổi",
"gate-review-pending": "Đang xem xét",
"gate-review-rejected": "Yêu cầu thay đổi",
"gate-threads-open-sub": "Giải quyết mọi luồng để tạo rollout",
- "gate-threads-open_one": "{{count}} luồng chưa giải quyết",
- "gate-threads-open_other": "{{count}} luồng chưa giải quyết",
- "gate-threads-resolved": "Tất cả luồng đã được giải quyết",
"incomplete": "Chưa hoàn tất",
"preparing-rollout": "Đang chuẩn bị triển khai…",
"rejected": "Đã từ chối",
@@ -1888,11 +1966,15 @@
"add-a-comment": "Thêm bình luận...",
"created-this-plan": "đã tạo kế hoạch này",
"marked-ready-for-review": "đã đánh dấu kế hoạch này sẵn sàng xét duyệt",
+ "n-findings_one": "{{count}} phát hiện",
+ "n-findings_other": "{{count}} phát hiện",
"n-hidden-events_one": "{{count}} sự kiện ẩn",
"n-hidden-events_other": "{{count}} sự kiện ẩn",
+ "reviewed-the-sql": "đã đánh giá SQL",
"self": "Hoạt động",
"show-all": "Hiển thị tất cả"
},
+ "approval-after-submit": "Phê duyệt bắt đầu khi bạn gửi để đánh giá.",
"approval-flow": {
"and-n-more_one": "và {{count}} người khác",
"and-n-more_other": "và {{count}} người khác",
@@ -1968,6 +2050,7 @@
"n-replies-hidden_other": "{{count}} phản hồi bị ẩn",
"n-replies_one": "{{count}} phản hồi",
"n-replies_other": "{{count}} phản hồi",
+ "open": "Đang mở",
"priority": {
"p0": "SQL sai và phải được sửa.",
"p1": "Nguy hiểm nhưng hợp lệ. Cần có người chấp nhận.",
@@ -1985,8 +2068,10 @@
"threads-on-line_one": "{{count}} chủ đề trên dòng này",
"threads-on-line_other": "{{count}} chủ đề trên dòng này",
"walker": {
+ "clear-filter": "Duyệt qua mọi chuỗi thảo luận đang mở",
"count_one": "{{count}} luồng chưa giải quyết ở phiên bản này",
"count_other": "{{count}} luồng chưa giải quyết ở phiên bản này",
+ "filter": "{{reviewer}} · {{state}}",
"next": "Luồng chưa giải quyết tiếp theo",
"position": "Luồng {{index}} trên {{count}}",
"previous": "Luồng chưa giải quyết trước đó",
@@ -2001,16 +2086,6 @@
"description_other": "Hoàn tác {{count}} tác vụ đã chọn từ bản triển khai #{{rolloutId}}.",
"title": "Hoàn tác bản triển khai #{{rolloutId}}"
},
- "rule-review": {
- "failed": "Đánh giá SQL thất bại",
- "load-failed": "Không thể tải trạng thái đánh giá SQL.",
- "no-open-findings": "Không có phát hiện chưa giải quyết",
- "not-run": "Chưa chạy đánh giá SQL",
- "open-findings_one": "{{count}} phát hiện chưa giải quyết",
- "open-findings_other": "{{count}} phát hiện chưa giải quyết",
- "queued": "Đánh giá SQL đang chờ",
- "running": "Đang đánh giá SQL"
- },
"run": "Kiểm tra lại",
"select-isolation-level": "Chọn mức độ cô lập",
"select-targets": "Chọn mục tiêu",
@@ -2035,9 +2110,14 @@
"reopen-confirm": "Mở lại kế hoạch này?",
"reopen-review-confirm": "Mở lại đợt xem xét này?"
},
+ "statement-summary": {
+ "affected-rows_one": "~{{count}} dòng bị ảnh hưởng",
+ "affected-rows_other": "~{{count}} dòng bị ảnh hưởng"
+ },
"submit-review-anyway": "Vẫn gửi",
"subtitle": "Soạn thảo các thay đổi cơ sở dữ liệu và chạy các bước kiểm tra sơ bộ trước khi tạo vấn đề để phê duyệt.",
"summary": {
+ "approved-by": "Được phê duyệt bởi {{names}}",
"last-approved-by": "Phê duyệt gần nhất bởi {{name}}",
"n-changes": "{{n}} thay đổi",
"n-database-groups": "{{n}} nhóm cơ sở dữ liệu",
@@ -2048,7 +2128,8 @@
"n-passed": "{{n}} đã vượt qua",
"n-unresolved-threads_one": "{{count}} luồng chưa giải quyết",
"n-unresolved-threads_other": "{{count}} luồng chưa giải quyết",
- "n-warning": "{{n}} cảnh báo"
+ "n-warning": "{{n}} cảnh báo",
+ "no-approval-required": "Không cần phê duyệt"
},
"targets": {
"no-targets-found": "Không tìm thấy mục tiêu",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 560cb5c97e..d6b6d020a2 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1780,12 +1780,54 @@
"add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更",
"ai-review": {
"failed-to-run": "无法启动 AI 审核",
- "finished": "已完成",
- "not-run": "尚未运行",
- "queued": "排队中",
"run": "运行 AI 审核",
- "save-first": "请先保存或放弃修改,再运行 AI 审核。",
- "status-unknown": "暂时无法获取状态"
+ "run-again-description": "每次运行都会为所审核的每个数据库调用模型,结果可能不同。新结果会替换上次运行的发现,包括已被解决的问题。",
+ "run-again-title": "再次运行 AI 审核?",
+ "save-first": "请先保存或放弃修改,再运行 AI 审核。"
+ },
+ "automated-review": {
+ "checks": "计划检查",
+ "details": "详情",
+ "failed": "无法运行",
+ "failed-to-rerun": "无法开始审核",
+ "ghost": "在线迁移试运行",
+ "n-databases_one": "{{count}} 个数据库",
+ "n-databases_other": "{{count}} 个数据库",
+ "n-errors_one": "{{count}} 个错误",
+ "n-errors_other": "{{count}} 个错误",
+ "n-open": "{{count}} 个待处理",
+ "n-warnings_one": "{{count}} 个警告",
+ "n-warnings_other": "{{count}} 个警告",
+ "needs-attention": "{{total}} 项中有 {{count}} 项需要处理",
+ "no-findings": "未发现问题",
+ "not-run": "尚未运行",
+ "nothing-needs-attention": "无需处理",
+ "opens-in-sql": "点击在 SQL 中逐条查看。",
+ "out-of-date": "已过期",
+ "outdated": "本次运行后 SQL 已变更",
+ "passed": "通过",
+ "passed-on_one": "在 {{count}} 个数据库上通过",
+ "passed-on_other": "在 {{count}} 个数据库上通过",
+ "policy": "审核策略",
+ "project-rules": "项目规则:开启 {{on}}/{{total}} 条",
+ "report": "语句报告",
+ "rerun": "重新运行",
+ "rerun-all": "全部重新运行",
+ "rerun-all-description_one": "这会重新运行计划检查和 Standard rules。Standard rules 中已被解决的 {{count}} 项问题会重新变为待处理。",
+ "rerun-all-description_other": "这会重新运行计划检查和 Standard rules。Standard rules 中已被解决的 {{count}} 项问题会重新变为待处理。",
+ "rerun-all-title": "全部重新运行?",
+ "rerun-reopens_one": "已被解决的 {{count}} 项问题会重新变为待处理,需要再次处理。",
+ "rerun-reopens_other": "已被解决的 {{count}} 项问题会重新变为待处理,需要再次处理。",
+ "rerun-rule-title": "重新运行 Standard rules?",
+ "retry": "重试",
+ "running": "运行中",
+ "sampled": "抽样 {{count}}/{{total}} 个数据库",
+ "scope": "审核了 {{databases}}",
+ "scope-label": "本次审核的范围",
+ "scope-with-engines": "审核了 {{databases}}({{engines}})",
+ "self": "自动审核",
+ "summary-part": "{{reviewer}}:{{status}}",
+ "workspace-rules": "工作区规则:开启 {{on}}/{{total}} 条"
},
"blocker": {
"clears-on-its-own": "将自动完成"
@@ -1800,6 +1842,28 @@
"started": "已开始计划检查"
},
"create-plan": "创建计划",
+ "deploy-waiting": {
+ "approval": "审批",
+ "approval-from": "{{role}} 的审批",
+ "approval-rejected": "审批被拒绝",
+ "auto-create": "以上各项全部通过后,Bytebase 会自动创建发布。",
+ "creating-rollout": "全部通过,正在创建发布…",
+ "manual-rollout": "Bytebase 不会为此计划自动创建发布;以上条件通过后请手动部署。",
+ "open-discussions_one": "{{count}} 个未解决的讨论",
+ "open-discussions_other": "{{count}} 个未解决的讨论",
+ "overridden_one": "{{reviewer}} 中有 {{count}} 个 P0 问题未修改就被解决",
+ "overridden_other": "{{reviewer}} 中有 {{count}} 个 P0 问题未修改就被解决",
+ "ready-to-deploy": "全部通过,可以部署。",
+ "reviewer-failed": "{{reviewer}} 无法运行",
+ "reviewer-findings": "{{reviewer}}:{{findings}}",
+ "reviewer-not-run": "{{reviewer}} 尚未运行",
+ "reviewer-outdated": "{{reviewer}} 运行后 SQL 已变更",
+ "reviewer-running": "{{reviewer}} 运行中",
+ "show": "查看",
+ "submit": "提交审核",
+ "waiting-on": "正在等待",
+ "worth-a-look": "不会挡住发布,但值得看一下"
+ },
"description": {
"placeholder": "添加描述"
},
@@ -1807,6 +1871,21 @@
"editor": {
"save-changes-before-continuing": "请保存或取消更改,然后再继续"
},
+ "findings": {
+ "n-more": "另 {{count}} 项",
+ "n-overridden": "{{count}} 个 P0 未修改就被解决",
+ "n-priority": "{{count}} 个 {{priority}}",
+ "n-resolved": "{{count}} 个已解决",
+ "name-at-line": "{{name}}(L{{line}})",
+ "name-times": "{{name}} ×{{count}}",
+ "separator": "、",
+ "set": {
+ "earlier": "更早的运行",
+ "open": "待处理",
+ "overridden": "P0 未修改就被解决",
+ "resolved": "已解决"
+ }
+ },
"ghost": {
"configure": "配置",
"parameters": "gh-ost 参数",
@@ -1829,19 +1908,18 @@
"checking": "检查中…",
"checks-failing": "检查失败",
"deployed": "已部署",
+ "gate-automated-review-passed": "自动审核已通过",
"gate-checks-failed": "部分检查未通过",
"gate-checks-failed-sub": "{{failing}} 项失败,{{passed}} 项通过",
"gate-checks-passed": "所有检查已通过",
"gate-checks-passed-sub": "{{count}} 项通过",
"gate-checks-running": "检查运行中",
"gate-checks-running-sub": "{{running}} 项运行中,{{passed}} 项通过",
+ "gate-no-open-discussions": "没有未解决的讨论",
"gate-review-approved": "变更已批准",
"gate-review-pending": "审批中",
"gate-review-rejected": "请求变更",
"gate-threads-open-sub": "解决所有讨论后才会创建发布",
- "gate-threads-open_one": "{{count}} 个未解决的讨论",
- "gate-threads-open_other": "{{count}} 个未解决的讨论",
- "gate-threads-resolved": "所有讨论已解决",
"incomplete": "不完整",
"preparing-rollout": "正在准备发布…",
"rejected": "已拒绝",
@@ -1888,11 +1966,15 @@
"add-a-comment": "添加评论...",
"created-this-plan": "创建了此计划",
"marked-ready-for-review": "将此计划提交审批",
+ "n-findings_one": "{{count}} 个发现",
+ "n-findings_other": "{{count}} 个发现",
"n-hidden-events_one": "{{count}} 条隐藏活动",
"n-hidden-events_other": "{{count}} 条隐藏活动",
+ "reviewed-the-sql": "审核了 SQL",
"self": "活动",
"show-all": "显示全部"
},
+ "approval-after-submit": "提交审核后开始审批。",
"approval-flow": {
"and-n-more_one": "还有 {{count}} 位",
"and-n-more_other": "还有 {{count}} 位",
@@ -1968,6 +2050,7 @@
"n-replies-hidden_other": "已隐藏 {{count}} 条回复",
"n-replies_one": "{{count}} 条回复",
"n-replies_other": "{{count}} 条回复",
+ "open": "待处理",
"priority": {
"p0": "SQL 有误,必须修改。",
"p1": "有风险但合理,需要有人确认接受。",
@@ -1985,8 +2068,10 @@
"threads-on-line_one": "此行有 {{count}} 个讨论",
"threads-on-line_other": "此行有 {{count}} 个讨论",
"walker": {
+ "clear-filter": "逐个查看所有待处理讨论",
"count_one": "此版本有 {{count}} 个未解决的讨论",
"count_other": "此版本有 {{count}} 个未解决的讨论",
+ "filter": "{{reviewer}} · {{state}}",
"next": "下一个未解决的讨论",
"position": "第 {{index}} 个,共 {{count}} 个",
"previous": "上一个未解决的讨论",
@@ -2001,16 +2086,6 @@
"description_other": "回滚发布 #{{rolloutId}} 中选中的 {{count}} 个任务。",
"title": "回滚发布 #{{rolloutId}}"
},
- "rule-review": {
- "failed": "SQL 审核失败",
- "load-failed": "无法加载 SQL 审核状态。",
- "no-open-findings": "没有未解决的问题",
- "not-run": "SQL 审核未运行",
- "open-findings_one": "{{count}} 个未解决的问题",
- "open-findings_other": "{{count}} 个未解决的问题",
- "queued": "SQL 审核排队中",
- "running": "SQL 审核运行中"
- },
"run": "重新检查",
"select-isolation-level": "选择隔离级别",
"select-targets": "选择目标",
@@ -2035,9 +2110,14 @@
"reopen-confirm": "确认重新打开这个计划?",
"reopen-review-confirm": "确认重新打开这个审批?"
},
+ "statement-summary": {
+ "affected-rows_one": "约影响 {{count}} 行",
+ "affected-rows_other": "约影响 {{count}} 行"
+ },
"submit-review-anyway": "仍然提交",
"subtitle": "草拟数据库变更并运行预检查,然后创建工单以请求审批。",
"summary": {
+ "approved-by": "已由 {{names}} 批准",
"last-approved-by": "最后由 {{name}} 审批",
"n-changes": "{{n}} 个变更",
"n-database-groups": "{{n}} 个数据库组",
@@ -2048,7 +2128,8 @@
"n-passed": "{{n}} 通过",
"n-unresolved-threads_one": "{{count}} 个未解决的讨论",
"n-unresolved-threads_other": "{{count}} 个未解决的讨论",
- "n-warning": "{{n}} 警告"
+ "n-warning": "{{n}} 警告",
+ "no-approval-required": "无需审批"
},
"targets": {
"no-targets-found": "未找到目标",
diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx
index 912a004a5b..9e546c2a3c 100644
--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx
+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx
@@ -3,7 +3,7 @@ import { act, useRef } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MAIN_SCROLL_RESTORATION_ID } from "@/app/router/NavigationScrollRestoration";
-import { State } from "@/types/proto-es/v1/common_pb";
+import { IssueStatus, State } from "@/types/proto-es/v1/common_pb";
import type { PlanDetailPageState } from "./shell/hooks/types";
(
@@ -11,6 +11,7 @@ import type { PlanDetailPageState } from "./shell/hooks/types";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
+ reviewState: undefined as unknown,
localStorage: {
clear: vi.fn(),
getItem: vi.fn(() => null),
@@ -73,7 +74,7 @@ vi.mock("./components/deploy/DeployBranch", () => ({
}));
vi.mock("./components/review/PlanReviewSection", () => ({
- PlanReviewSection: () => null,
+ PlanReviewSection: () => <div data-testid="plan-review-section" />,
}));
vi.mock("./components/PlanDetailChangesBranch", () => ({
@@ -124,6 +125,15 @@ vi.mock("./utils/phaseSummary", () => ({
buildChangesSummary: () => "",
buildDeploySummary: () => "",
buildReviewSummary: () => "",
+ buildReviewSummaryV2: () => "review summary v2",
+}));
+
+vi.mock("./hooks/usePlanReviewState", () => ({
+ usePlanReviewState: () => mocks.reviewState,
+}));
+
+vi.mock("./components/PlanDetailDeployWaiting", () => ({
+ PlanDetailDeployWaiting: () => <div data-testid="deploy-waiting" />,
}));
import { ProjectPlanDetailPage } from "./ProjectPlanDetailPage";
@@ -133,6 +143,7 @@ let root: ReturnType<typeof createRoot>;
beforeEach(() => {
vi.clearAllMocks();
+ mocks.reviewState = undefined;
mocks.branchMountCount.value = 0;
container = document.createElement("div");
document.body.appendChild(container);
@@ -505,6 +516,72 @@ describe("ProjectPlanDetailPage", () => {
expect(container.textContent).not.toContain("common.not-started");
});
+ it("under SQL Review V2 a draft opens Review and Deploy lists what it waits on", async () => {
+ const page = buildPage();
+ page.isCreating = false;
+ page.planId = "1";
+ page.plan.name = "projects/foo/plans/1";
+ page.plan.issue = "projects/foo/issues/1";
+ page.activePhases = new Set(["changes", "review"]);
+ page.issue = {
+ name: "projects/foo/issues/1",
+ draft: true,
+ status: IssueStatus.OPEN,
+ } as PlanDetailPageState["issue"];
+ mocks.usePlanDetailPage.mockReturnValue(page);
+ mocks.reviewState = {
+ rows: [
+ {
+ reviewer: "rule",
+ conclusion: "open",
+ findings: { open: 2, resolved: 0, openP0: 0 },
+ holdsRollout: true,
+ },
+ ],
+ gates: [],
+ openDiscussions: 0,
+ };
+
+ await act(async () => {
+ root.render(
+ <ProjectPlanDetailPage planId="1" projectId="foo" specId="spec-1" />
+ );
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector("[data-testid='plan-review-section']")).not.toBeNull();
+ expect(container.textContent).not.toContain("plan.phase.review-description");
+ expect(container.querySelector("[data-testid='deploy-waiting']")).not.toBeNull();
+ expect(container.querySelector("[data-testid='phase-attention']")).not.toBeNull();
+ });
+
+ it("under SQL Review V2 a canceled issue's Deploy waits on nothing", async () => {
+ const page = buildPage();
+ page.isCreating = false;
+ page.planId = "1";
+ page.plan.name = "projects/foo/plans/1";
+ page.plan.issue = "projects/foo/issues/1";
+ page.issue = {
+ name: "projects/foo/issues/1",
+ draft: false,
+ status: IssueStatus.CANCELED,
+ } as PlanDetailPageState["issue"];
+ mocks.usePlanDetailPage.mockReturnValue(page);
+ mocks.reviewState = { rows: [], gates: [], openDiscussions: 0 };
+
+ await act(async () => {
+ root.render(
+ <ProjectPlanDetailPage planId="1" projectId="foo" specId="spec-1" />
+ );
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector("[data-testid='deploy-waiting']")).toBeNull();
+ expect(
+ container.querySelector("[data-testid='deploy-future-control']")
+ ).not.toBeNull();
+ });
+
it("shows an incomplete state for a persisted plan without its Draft Review Issue", async () => {
const page = buildPage();
page.isCreating = false;
diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
index 8803e31534..21dc28e80d 100644
--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
@@ -1,4 +1,4 @@
-import { Code2, Loader2, MessageSquareMore, Rocket } from "lucide-react";
+import { Check, Code2, Loader2, MessageSquareMore, Rocket } from "lucide-react";
import type { ReactNode } from "react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -13,7 +13,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useOnKeyChange } from "@/hooks/useOnKeyChange";
import { cn } from "@/lib/utils";
-import { IssueStatus } from "@/types/proto-es/v1/common_pb";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
import { getRolloutStatus } from "@/utils";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
@@ -21,32 +21,33 @@ import { getReviewBadge } from "../utils/reviewBadge";
import { DeployBranch } from "./components/deploy/DeployBranch";
import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";
import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";
+import { PlanDetailDeployWaiting } from "./components/PlanDetailDeployWaiting";
import { PlanDetailHeader } from "./components/PlanDetailHeader";
import { PlanDetailHeaderDetails } from "./components/PlanDetailHeaderDetails";
import { PlanReviewSection } from "./components/review/PlanReviewSection";
import { useUnresolvedThreadTotal } from "./components/threads/useUnresolvedThreadCounts";
import { useIssueCommentThreadsSync } from "./hooks/useIssueCommentThreadsSync";
import { usePlacementSync } from "./hooks/usePlacementSync";
+import { usePlanReviewState } from "./hooks/usePlanReviewState";
import { SqlReviewV2Provider } from "./hooks/useSqlReviewV2";
import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";
import { planPhaseAnchorId } from "./shell/focusPhase";
import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";
-import { PlanDetailProvider } from "./shell/PlanDetailContext";
+import {
+ PlanDetailProvider,
+ usePlanDetailContext,
+} from "./shell/PlanDetailContext";
import {
buildChangesSummary,
buildDeploySummary,
buildReviewSummary,
+ buildReviewSummaryV2,
} from "./utils/phaseSummary";
+import { rowNeedsAttention } from "./utils/planGates";
import { isReleaseBackedPlan } from "./utils/spec";
type PhaseStatus = "completed" | "closed" | "active" | "future";
-function phaseLineClass(from: PhaseStatus, to: PhaseStatus): string {
- if (from === "completed" && (to === "completed" || to === "active"))
- return "bg-success";
- return "bg-control-border";
-}
-
export function ProjectPlanDetailPage(props: {
projectId: string;
planId: string;
@@ -112,13 +113,120 @@ function ProjectPlanDetailPageInner({
taskId,
});
useIssueCommentThreadsSync(page.issue, page.aiReviewRun);
- const unresolvedThreads = useUnresolvedThreadTotal(page.issue?.name);
usePlacementSync({
issueName: page.issue?.name,
projectId,
ready: page.ready,
specs: page.plan.specs,
});
+ // Route-driven spec changes reset during render, so the first paint after a
+ // Back/Forward or tab navigation already shows the destination spec. The
+ // keyed provider remounts this subtree when the plan itself changes.
+ useOnKeyChange(`${page.pageKey}:${specId ?? ""}`, () => {
+ if (!page.isCreating && specId) {
+ setSelectedSpecId(specId);
+ }
+ });
+
+ // A create route has no persisted spec resource in its URL. Derive the
+ // initial selection during render so the first ready paint already shows the
+ // first client-local spec, without a placeholder route or a follow-up effect.
+ const effectiveSelectedSpecId =
+ selectedSpecId || page.plan.specs[0]?.id || "";
+
+ return (
+ <PlanDetailProvider value={page}>
+ <SqlReviewV2Provider>
+ <div
+ ref={setPageHost}
+ data-testid="plan-detail-page"
+ className="relative min-h-full overflow-x-clip bg-control-bg/50"
+ >
+ <div
+ className={cn(
+ "flex min-h-full flex-col",
+ page.ready ? "" : "invisible pointer-events-none"
+ )}
+ >
+ {/* Only the title/action row is sticky (GitHub issue-header pattern);
+ the description + metadata below scroll away beneath it. The
+ dashboard main pane is the scroll container, so top-0 pins to it;
+ z-20 keeps it above the phase rail nodes (z-10). The border appears
+ only when stuck, so the row is flat at the top. */}
+ <header
+ className={cn(
+ "sticky top-0 z-20 shrink-0 bg-background",
+ headerStuck && "border-b"
+ )}
+ >
+ <PlanDetailHeader />
+ </header>
+ <PlanDetailHeaderDetails />
+
+ <main className="min-h-[calc(100vh-4rem)] min-w-0 flex-1">
+ <PlanPhaseRail
+ onSelectedSpecIdChange={setSelectedSpecId}
+ selectedSpecId={effectiveSelectedSpecId}
+ />
+ </main>
+ </div>
+
+ {!page.ready && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-y-3 bg-background">
+ <Loader2 className="h-8 w-8 animate-spin text-accent" />
+ <div className="text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ </div>
+ )}
+
+ <AlertDialog
+ open={page.pendingLeaveConfirm}
+ onOpenChange={(open) => {
+ if (!open) {
+ page.resolveLeaveConfirm(false);
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("common.leave-without-saving")}
+ </AlertDialogTitle>
+ <AlertDialogFooter>
+ <Button
+ appearance="outline"
+ onClick={() => page.resolveLeaveConfirm(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => page.resolveLeaveConfirm(true)}
+ >
+ {t("common.discard-changes")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ </SqlReviewV2Provider>
+ </PlanDetailProvider>
+ );
+}
+
+// The three phases. Before the rollout exists, Changes and Review form one
+// loop and Deploy lists what the rollout waits on; afterwards Deploy leads.
+function PlanPhaseRail({
+ onSelectedSpecIdChange,
+ selectedSpecId,
+}: {
+ onSelectedSpecIdChange: (specId: string) => void;
+ selectedSpecId: string;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const unresolvedThreads = useUnresolvedThreadTotal(page.issue?.name);
+ const reviewState = usePlanReviewState();
const isGitOpsPlan = useMemo(
() => isReleaseBackedPlan(page.plan.specs),
[page.plan.specs]
@@ -128,6 +236,9 @@ function ProjectPlanDetailPageInner({
// release-backed plans, which bypass review entirely, hide it.
const reviewVisible = !isGitOpsPlan;
const selectPhase = page.expandPhase;
+ // The machine reviews run on drafts too, so under SQL Review V2 Review is
+ // open from the first save of an issue.
+ const reviewFromDraft = !!reviewState;
const phaseConfigs = useMemo(() => {
const hasIssue = !!page.issue;
@@ -149,7 +260,7 @@ function ProjectPlanDetailPageInner({
);
let review: PhaseStatus = "future";
- if (hasSubmittedIssue) {
+ if (hasSubmittedIssue || (reviewFromDraft && hasIssue)) {
if (page.issue?.status === IssueStatus.CANCELED) {
review = "closed";
} else {
@@ -184,12 +295,18 @@ function ProjectPlanDetailPageInner({
hasRollout,
approvalStatus: page.issue?.approvalStatus,
});
- const reviewBadge = rawReviewBadge
- ? {
- label: t(rawReviewBadge.labelKey),
- variant: rawReviewBadge.variant,
- }
- : undefined;
+ // "Skipped" names the approval outcome, not the review; under SQL Review
+ // V2 the summary says "No approval required" instead.
+ const reviewBadge =
+ rawReviewBadge &&
+ !(
+ reviewFromDraft && page.issue?.approvalStatus === ApprovalStatus.SKIPPED
+ )
+ ? {
+ label: t(rawReviewBadge.labelKey),
+ variant: rawReviewBadge.variant,
+ }
+ : undefined;
const deployBadge = (() => {
if (deployStatus !== "active" || !effectiveRollout) return undefined;
const rolloutStatus = getRolloutStatus(effectiveRollout);
@@ -226,197 +343,127 @@ function ProjectPlanDetailPageInner({
})();
return {
- changes: {
- status: changesStatus,
- badge: changesBadge,
- lineClass: phaseLineClass(
- changesStatus,
- reviewVisible ? review : deployStatus
- ),
- },
- review: {
- status: review,
- badge: reviewBadge,
- lineClass: phaseLineClass(review, deployStatus),
- },
- deploy: {
- status: deployStatus,
- badge: deployBadge,
- },
+ changes: { status: changesStatus, badge: changesBadge },
+ review: { status: review, badge: reviewBadge },
+ deploy: { status: deployStatus, badge: deployBadge },
};
- }, [page.isCreating, page.issue, page.rollout, reviewVisible, t]);
+ }, [
+ page.isCreating,
+ page.issue,
+ page.rollout,
+ reviewFromDraft,
+ reviewVisible,
+ t,
+ ]);
- // Route-driven spec changes reset during render, so the first paint after a
- // Back/Forward or tab navigation already shows the destination spec. The
- // keyed provider remounts this subtree when the plan itself changes.
- useOnKeyChange(`${page.pageKey}:${specId ?? ""}`, () => {
- if (!page.isCreating && specId) {
- setSelectedSpecId(specId);
- }
- });
+ // A small dot on the Review node marks findings or discussions that need
+ // someone.
+ const reviewNeedsAttention =
+ !!reviewState &&
+ (reviewState.rows.some(rowNeedsAttention) ||
+ reviewState.openDiscussions > 0);
+ const reviewSummary = reviewState
+ ? buildReviewSummaryV2(
+ page.issue,
+ t,
+ reviewState.rows,
+ reviewState.openDiscussions
+ )
+ : buildReviewSummary(page.issue, t, unresolvedThreads);
- // A create route has no persisted spec resource in its URL. Derive the
- // initial selection during render so the first ready paint already shows the
- // first client-local spec, without a placeholder route or a follow-up effect.
- const effectiveSelectedSpecId =
- selectedSpecId || page.plan.specs[0]?.id || "";
+ let deployFuture: ReactNode;
+ // A closed issue waits on nothing, so Deploy describes the phase instead.
+ if (reviewState && page.issue?.status === IssueStatus.OPEN && !isGitOpsPlan) {
+ deployFuture = (
+ <PlanDetailDeployWaiting
+ issue={page.issue}
+ plan={page.plan}
+ state={reviewState}
+ />
+ );
+ } else if (page.issue?.draft) {
+ deployFuture = (
+ <p className="mt-0.5 text-sm text-control-light">
+ {sqlReviewV2Enabled()
+ ? t("plan.phase.deploy-description-v2")
+ : t("plan.phase.deploy-description")}
+ </p>
+ );
+ } else {
+ deployFuture = <PlanDetailDeployFuture />;
+ }
return (
- <PlanDetailProvider value={page}>
- <SqlReviewV2Provider>
- <div
- ref={setPageHost}
- data-testid="plan-detail-page"
- className="relative min-h-full overflow-x-clip bg-control-bg/50"
- >
- <div
- className={cn(
- "flex min-h-full flex-col",
- page.ready ? "" : "invisible pointer-events-none"
- )}
- >
- {/* Only the title/action row is sticky (GitHub issue-header pattern);
- the description + metadata below scroll away beneath it. The
- dashboard main pane is the scroll container, so top-0 pins to it;
- z-20 keeps it above the phase rail nodes (z-10). The border appears
- only when stuck, so the row is flat at the top. */}
- <header
- className={cn(
- "sticky top-0 z-20 shrink-0 bg-background",
- headerStuck && "border-b"
- )}
- >
- <PlanDetailHeader />
- </header>
- <PlanDetailHeaderDetails />
+ // No row gap here: each PhaseSection's pb-6 carries the spacing, which
+ // the connector line fills so it stays continuous.
+ <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
+ <PhaseSection
+ anchorId={planPhaseAnchorId("changes")}
+ badge={phaseConfigs.changes.badge}
+ expanded={page.activePhases.has("changes")}
+ icon={<Code2 className="size-3 md:size-4" />}
+ label={t("plan.navigator.changes")}
+ onSelect={() => selectPhase("changes")}
+ status={phaseConfigs.changes.status}
+ onToggle={() => page.togglePhase("changes")}
+ summary={buildChangesSummary(page.plan, t, {
+ includeChecks: !reviewState,
+ })}
+ >
+ <PlanDetailChangesBranch
+ onSelectedSpecIdChange={onSelectedSpecIdChange}
+ selectedSpecId={selectedSpecId}
+ />
+ </PhaseSection>
- <main className="min-h-[calc(100vh-4rem)] min-w-0 flex-1">
- {/* No row gap here: each PhaseSection's pb-6 carries the spacing,
- which the connector line fills so it stays continuous. */}
- <div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
- <PhaseSection
- anchorId={planPhaseAnchorId("changes")}
- badge={phaseConfigs.changes.badge}
- expanded={page.activePhases.has("changes")}
- icon={<Code2 className="size-3 md:size-4" />}
- lineClass={phaseConfigs.changes.lineClass}
- label={t("plan.navigator.changes")}
- onSelect={() => selectPhase("changes")}
- status={phaseConfigs.changes.status}
- onToggle={() => page.togglePhase("changes")}
- summary={buildChangesSummary(page.plan, t)}
- >
- <PlanDetailChangesBranch
- onSelectedSpecIdChange={setSelectedSpecId}
- selectedSpecId={effectiveSelectedSpecId}
- />
- </PhaseSection>
-
- {reviewVisible && (
- <PhaseSection
- anchorId={planPhaseAnchorId("review")}
- badge={phaseConfigs.review.badge}
- expanded={page.activePhases.has("review")}
- icon={<MessageSquareMore className="size-3 md:size-4" />}
- lineClass={phaseConfigs.review.lineClass}
- label={t("plan.navigator.review")}
- onSelect={() => selectPhase("review")}
- status={phaseConfigs.review.status}
- onToggle={() => page.togglePhase("review")}
- summary={buildReviewSummary(
- page.issue,
- t,
- unresolvedThreads
- )}
- future={
- <p className="mt-0.5 text-sm text-control-placeholder">
- {t("plan.phase.review-description")}
- </p>
- }
- >
- <PlanReviewSection />
- </PhaseSection>
- )}
-
- <PhaseSection
- anchorId={planPhaseAnchorId("deploy")}
- badge={phaseConfigs.deploy.badge}
- expanded={page.activePhases.has("deploy")}
- icon={<Rocket className="size-3 md:size-4" />}
- isLast
- label={t("plan.navigator.deploy")}
- status={phaseConfigs.deploy.status}
- onSelect={() => selectPhase("deploy")}
- onToggle={() => page.togglePhase("deploy")}
- summary={buildDeploySummary(
- page.issue?.draft ? undefined : page.rollout,
- t
- )}
- future={
- page.issue?.draft ? (
- <p className="mt-0.5 text-sm text-control-placeholder">
- {sqlReviewV2Enabled()
- ? t("plan.phase.deploy-description-v2")
- : t("plan.phase.deploy-description")}
- </p>
- ) : (
- <PlanDetailDeployFuture />
- )
- }
- >
- <DeployBranch />
- </PhaseSection>
- </div>
- </main>
- </div>
-
- {!page.ready && (
- <div className="absolute inset-0 flex flex-col items-center justify-center gap-y-3 bg-background">
- <Loader2 className="h-8 w-8 animate-spin text-accent" />
- <div className="text-sm text-control-light">
- {t("common.loading")}
- </div>
- </div>
- )}
+ {reviewVisible && (
+ <PhaseSection
+ anchorId={planPhaseAnchorId("review")}
+ attention={reviewNeedsAttention}
+ badge={phaseConfigs.review.badge}
+ expanded={page.activePhases.has("review")}
+ icon={<MessageSquareMore className="size-3 md:size-4" />}
+ label={t("plan.navigator.review")}
+ onSelect={() => selectPhase("review")}
+ status={phaseConfigs.review.status}
+ onToggle={() => page.togglePhase("review")}
+ summary={reviewSummary}
+ future={
+ <p className="mt-0.5 text-sm text-control-light">
+ {t("plan.phase.review-description")}
+ </p>
+ }
+ >
+ <PlanReviewSection />
+ </PhaseSection>
+ )}
- <AlertDialog
- open={page.pendingLeaveConfirm}
- onOpenChange={(open) => {
- if (!open) {
- page.resolveLeaveConfirm(false);
- }
- }}
- >
- <AlertDialogContent>
- <AlertDialogTitle>
- {t("common.leave-without-saving")}
- </AlertDialogTitle>
- <AlertDialogFooter>
- <Button
- appearance="outline"
- onClick={() => page.resolveLeaveConfirm(false)}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="destructive"
- onClick={() => page.resolveLeaveConfirm(true)}
- >
- {t("common.discard-changes")}
- </Button>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- </SqlReviewV2Provider>
- </PlanDetailProvider>
+ <PhaseSection
+ anchorId={planPhaseAnchorId("deploy")}
+ badge={phaseConfigs.deploy.badge}
+ expanded={page.activePhases.has("deploy")}
+ icon={<Rocket className="size-3 md:size-4" />}
+ isLast
+ label={t("plan.navigator.deploy")}
+ status={phaseConfigs.deploy.status}
+ onSelect={() => selectPhase("deploy")}
+ onToggle={() => page.togglePhase("deploy")}
+ summary={buildDeploySummary(
+ page.issue?.draft ? undefined : page.rollout,
+ t
+ )}
+ future={deployFuture}
+ >
+ <DeployBranch />
+ </PhaseSection>
+ </div>
);
}
function PhaseSection({
+ attention = false,
badge,
label,
- lineClass,
icon,
future,
isLast = false,
@@ -428,12 +475,12 @@ function PhaseSection({
onSelect,
anchorId,
}: {
+ attention?: boolean;
badge?: {
label: string;
variant: "default" | "secondary" | "warning" | "success" | "destructive";
};
label: string;
- lineClass?: string;
icon: ReactNode;
future?: ReactNode;
isLast?: boolean;
@@ -446,14 +493,16 @@ function PhaseSection({
anchorId?: string;
}) {
const { t } = useTranslation();
+ // Finished is quiet, in progress is outlined, and only something that needs
+ // a person gets saturated color: the attention dot.
const dotClass =
status === "completed"
- ? "bg-success text-accent-text ring-[3px] ring-success/15 md:ring-4"
+ ? "bg-control-bg text-control-light"
: status === "closed"
? "bg-control-placeholder text-accent-text"
: status === "active"
- ? "bg-accent text-accent-text ring-[3px] ring-accent/15 md:ring-4"
- : "border-2 border-dashed border-control-border text-control-placeholder";
+ ? "border-2 border-accent bg-background text-accent"
+ : "border-2 border-dashed border-control-border bg-control-bg text-control-light";
return (
<div className={cn("flex scroll-mt-16", isLast && "mb-48")} id={anchorId}>
@@ -468,25 +517,34 @@ function PhaseSection({
dotClass
)}
>
- {icon}
+ {status === "completed" ? (
+ <Check className="size-3 md:size-4" />
+ ) : (
+ icon
+ )}
</div>
+ {attention && (
+ <span
+ aria-hidden="true"
+ className="absolute -top-0.5 -right-0.5 size-2.5 rounded-full border-2 border-background bg-warning"
+ data-testid="phase-attention"
+ />
+ )}
</div>
- {/* -mt-1 tucks the rail under the node's halo so it reads as connected. */}
+ {/* -mt-1 tucks the rail under the node so it reads as connected. */}
{!isLast && (
- <div className={cn("-mt-1 w-0.5 flex-1 min-h-[20px]", lineClass)} />
+ <div className="-mt-1 min-h-[20px] w-0.5 flex-1 bg-block-border" />
)}
</div>
<div className="min-w-0 flex-1 pb-6">
{status === "future" ? (
<div className="py-0.5">
- <span className="textlabel uppercase text-control-placeholder">
+ <span className="textlabel uppercase text-control-light">
{label}
</span>
{future ?? (
- <div className="mt-0.5 text-sm text-control-placeholder">
- {summary}
- </div>
+ <div className="mt-0.5 text-sm text-control-light">{summary}</div>
)}
</div>
) : !expanded ? (
@@ -495,7 +553,7 @@ function PhaseSection({
<span className="textlabel uppercase">{label}</span>
{badge && <Badge variant={badge.variant}>{badge.label}</Badge>}
<div className="flex-1" />
- <span className="shrink-0 text-xs text-control-placeholder">
+ <span className="shrink-0 text-xs text-control-light">
{t("plan.phase.show-details")}
</span>
</div>
@@ -506,11 +564,11 @@ function PhaseSection({
) : (
<div className="flex flex-col">
<div className="flex items-center gap-2 py-0.5">
- <span className="textlabel uppercase text-accent">{label}</span>
+ <span className="textlabel uppercase text-main">{label}</span>
{badge && <Badge variant={badge.variant}>{badge.label}</Badge>}
<div className="flex-1" />
<span
- className="shrink-0 cursor-pointer text-xs text-control-placeholder hover:text-control"
+ className="shrink-0 cursor-pointer text-xs text-control-light hover:text-control"
onClick={onToggle}
>
{t("plan.phase.hide-details")}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsx
deleted file mode 100644
index 75066e8049..0000000000
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.test.tsx
+++ /dev/null
@@ -1,383 +0,0 @@
-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.tsx
deleted file mode 100644
index 7bce6dbe14..0000000000
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailAIReview.tsx
+++ /dev/null
@@ -1,201 +0,0 @@
-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/PlanDetailAggregateChecks.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx
index 9f0274d733..d3d8d23d53 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.test.tsx
@@ -1,22 +1,16 @@
import { act, render } from "@testing-library/react";
-import type { ReactNode } from "react";
import { beforeEach, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
page: {} as Record<string, unknown>,
- reload: vi.fn(),
runChecks: vi.fn(),
- section: {} as { onRun?: () => Promise<void>; trailingSummary?: ReactNode },
- sqlReview: undefined as unknown,
+ section: {} as { onRun?: () => Promise<void> },
}));
vi.mock("@/components/plan-check/PlanCheckSection", () => ({
- PlanCheckSection: (props: {
- onRun: () => Promise<void>;
- trailingSummary?: ReactNode;
- }) => {
+ PlanCheckSection: (props: { onRun: () => Promise<void> }) => {
mocks.section = props;
- return <div>{props.trailingSummary}</div>;
+ return <div />;
},
}));
@@ -33,18 +27,10 @@ vi.mock("../hooks/usePlanCheckActions", () => ({
}),
}));
-vi.mock("../hooks/useSqlReviewV2", () => ({
- useSqlReviewV2: () => mocks.sqlReview,
-}));
-
vi.mock("../shell/PlanDetailContext", () => ({
usePlanDetailContext: () => mocks.page,
}));
-vi.mock("./PlanDetailRuleReviewSummary", () => ({
- PlanDetailRuleReviewSummary: () => <span>rule review summary</span>,
-}));
-
vi.mock("./PlanTargetDisplay", () => ({ PlanTargetDisplay: () => null }));
import { PlanDetailAggregateChecks } from "./PlanDetailAggregateChecks";
@@ -53,41 +39,12 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.page = { plan: { name: "projects/foo/plans/7" }, planCheckRuns: [] };
mocks.runChecks.mockResolvedValue(undefined);
- mocks.reload.mockResolvedValue(undefined);
- mocks.sqlReview = {
- unresolvedThreads: 0,
- ruleReview: {
- loadFailed: false,
- openFindings: 0,
- reload: mocks.reload,
- run: null,
- stale: false,
- },
- };
-});
-
-test("joins the rule review to the checks under SQL Review V2", async () => {
- const { getByText } = render(<PlanDetailAggregateChecks />);
- expect(getByText("rule review summary")).toBeInTheDocument();
-
- await act(async () => {
- await mocks.section.onRun?.();
- });
- expect(mocks.runChecks).toHaveBeenCalledTimes(1);
- expect(mocks.reload).toHaveBeenCalledTimes(1);
});
-test.each([
- ["SQL Review V2 is off", undefined],
- ["the review cannot be read", { unresolvedThreads: 0 }],
-])("leaves the rule review out when %s", async (_, sqlReview) => {
- mocks.sqlReview = sqlReview;
- const { queryByText } = render(<PlanDetailAggregateChecks />);
- expect(queryByText("rule review summary")).not.toBeInTheDocument();
-
+test("runs the plan checks from the footer", async () => {
+ render(<PlanDetailAggregateChecks />);
await act(async () => {
await mocks.section.onRun?.();
});
expect(mocks.runChecks).toHaveBeenCalledTimes(1);
- expect(mocks.reload).not.toHaveBeenCalled();
});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
index 162b3bde51..bd60f91cda 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailAggregateChecks.tsx
@@ -2,9 +2,7 @@ import { useMemo } from "react";
import { PlanCheckSection } from "@/components/plan-check/PlanCheckSection";
import { getPlanCheckSummaryWithFallback } from "@/lib/plan/check";
import { usePlanCheckActions } from "../hooks/usePlanCheckActions";
-import { useSqlReviewV2 } from "../hooks/useSqlReviewV2";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
-import { PlanDetailRuleReviewSummary } from "./PlanDetailRuleReviewSummary";
import { PlanTargetDisplay } from "./PlanTargetDisplay";
// Plan-wide checks rendered as a verdict-line footer at the bottom of the
@@ -12,13 +10,11 @@ import { PlanTargetDisplay } from "./PlanTargetDisplay";
// every spec without clicking into each tab. Drill-down details still live
// in the PlanCheckSection drawer. Create mode renders nothing here — there
// is no plan yet to aggregate against; per-spec PlanDetailDraftChecks
-// covers that case. Under SQL Review V2 the standard rule review replaces the
-// checks' SQL review, so its status joins the verdict line.
+// covers that case.
export function PlanDetailAggregateChecks() {
const page = usePlanDetailContext();
const { allowRunChecks, isRunningChecks, refreshChecks, runChecks } =
usePlanCheckActions();
- const ruleReview = useSqlReviewV2()?.ruleReview;
const summary = useMemo(
() =>
getPlanCheckSummaryWithFallback(
@@ -32,12 +28,6 @@ export function PlanDetailAggregateChecks() {
return null;
}
- // Running the checks also starts the rule review on the server.
- const runAllChecks = async () => {
- await runChecks();
- await ruleReview?.reload();
- };
-
return (
<div className="border-t px-4 py-4">
<PlanCheckSection
@@ -45,15 +35,12 @@ export function PlanDetailAggregateChecks() {
includeRunFailure
isRunning={isRunningChecks}
onRefreshOnOpen={refreshChecks}
- onRun={runAllChecks}
+ onRun={runChecks}
planCheckRuns={page.planCheckRuns}
renderTarget={(target) => (
<PlanTargetDisplay showEnvironment target={target} />
)}
summaryOverride={summary}
- trailingSummary={
- ruleReview && <PlanDetailRuleReviewSummary state={ruleReview} />
- }
/>
</div>
);
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
index 3ff1b51ec3..b61634389a 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -115,6 +115,7 @@ import {
getInstanceResource,
hasProjectPermissionV2,
} from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { getStatementSize } from "@/utils/sheet";
import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";
import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
@@ -151,7 +152,6 @@ 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,8 +716,10 @@ export function PlanDetailChangesBranch({
</div>
</div>
- {!page.isCreating && !specHasRelease && <PlanDetailAggregateChecks />}
- <PlanDetailAIReview />
+ {/* Under SQL Review V2 the checks are reviewers in the Review section. */}
+ {!page.isCreating && !specHasRelease && !sqlReviewV2Enabled() && (
+ <PlanDetailAggregateChecks />
+ )}
<TargetSelectorSheet
currentTargets={currentTargets}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.test.tsx
new file mode 100644
index 0000000000..1bc31011e7
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.test.tsx
@@ -0,0 +1,217 @@
+import { create } from "@bufbuild/protobuf";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ IssueComment_ThreadState,
+ IssueCommentSchema,
+ IssueSchema,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ Plan_CreateDatabaseConfigSchema,
+ type Plan_Spec,
+ Plan_SpecSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import type { PlanReviewState } from "../hooks/usePlanReviewState";
+import {
+ type AutomatedReviewRow,
+ emptyFindings,
+ type PlanGate,
+} from "../utils/planGates";
+
+const mocks = vi.hoisted(() => ({
+ comments: [] as unknown[],
+ focusInStatement: vi.fn(),
+ focusPlanPhase: vi.fn(),
+ requestReviewRow: vi.fn(),
+ triggerDeploy: vi.fn(),
+ weight: "link" as "none" | "link" | "button",
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options ? `${key}:${JSON.stringify(options)}` : key,
+ }),
+}));
+
+vi.mock("@/lib/role", () => ({
+ displayRoleTitleFromList: (role: string) => `title(${role})`,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) =>
+ selector({ roleList: [], getIssueComments: () => mocks.comments }),
+}));
+
+vi.mock("../hooks/useFocusThread", () => ({
+ useFocusThread: () => ({
+ focusInActivity: vi.fn(),
+ focusInStatement: mocks.focusInStatement,
+ }),
+}));
+
+vi.mock("../shared/stores/usePlanDetailStore", () => ({
+ usePlanDetailStoreApi: () => ({
+ getState: () => ({ requestReviewRow: mocks.requestReviewRow }),
+ }),
+}));
+
+vi.mock("../shell/focusPhase", () => ({ focusPlanPhase: mocks.focusPlanPhase }));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => ({
+ expandPhase: vi.fn(),
+ issue: create(IssueSchema, { name: "projects/p/issues/1" }),
+ }),
+}));
+
+vi.mock("./review/bypassDeploy", () => ({
+ BypassAndDeploySheet: () => null,
+ useBypassDeploy: () => ({
+ creating: false,
+ triggerDeploy: mocks.triggerDeploy,
+ weight: mocks.weight,
+ }),
+}));
+
+import { PlanDetailDeployWaiting } from "./PlanDetailDeployWaiting";
+
+const openRule: AutomatedReviewRow = {
+ reviewer: "rule",
+ conclusion: "open",
+ findings: { ...emptyFindings(), open: 2, p1: 2 },
+ holdsRollout: true,
+};
+
+const changeSpec = create(Plan_SpecSchema, {
+ id: "change",
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema),
+ },
+});
+const createDatabaseSpec = create(Plan_SpecSchema, {
+ id: "create",
+ config: {
+ case: "createDatabaseConfig",
+ value: create(Plan_CreateDatabaseConfigSchema),
+ },
+});
+
+const renderWaiting = (
+ gates: PlanGate[],
+ draft = false,
+ rows: AutomatedReviewRow[] = [],
+ specs: Plan_Spec[] = [changeSpec]
+) =>
+ render(
+ <PlanDetailDeployWaiting
+ issue={create(IssueSchema, { name: "projects/p/issues/1", draft })}
+ plan={create(PlanSchema, {
+ name: "projects/p/plans/1",
+ state: State.ACTIVE,
+ specs,
+ })}
+ state={{ rows, gates, openDiscussions: 0 } as unknown as PlanReviewState}
+ />
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.comments = [];
+ mocks.weight = "link";
+});
+
+afterEach(cleanup);
+
+describe("PlanDetailDeployWaiting", () => {
+ test("lists what the rollout waits on, each leading to where it is settled", () => {
+ mocks.comments = [
+ create(IssueCommentSchema, {
+ name: "discussion",
+ threadState: IssueComment_ThreadState.OPEN,
+ }),
+ ];
+ renderWaiting([
+ { kind: "approval", rejected: false, role: "roles/workspaceDBA" },
+ { kind: "review", row: openRule },
+ { kind: "discussion", open: 1 },
+ ]);
+ expect(
+ screen.getByText(
+ 'plan.deploy-waiting.approval-from:{"role":"title(roles/workspaceDBA)"}'
+ )
+ ).toBeDefined();
+ const shows = screen.getAllByText("plan.deploy-waiting.show");
+ expect(shows).toHaveLength(3);
+
+ fireEvent.click(shows[1]);
+ expect(mocks.focusPlanPhase).toHaveBeenCalledWith(
+ "review",
+ expect.any(Function)
+ );
+ expect(mocks.requestReviewRow).toHaveBeenCalledWith("rule");
+
+ fireEvent.click(shows[2]);
+ expect(mocks.focusInStatement).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "discussion" })
+ );
+ });
+
+ test("says the rollout is being created once nothing holds it", () => {
+ renderWaiting([]);
+ expect(
+ screen.getByText("plan.deploy-waiting.creating-rollout")
+ ).toBeDefined();
+ expect(screen.getByText("plan.deploy-waiting.auto-create")).toBeDefined();
+ });
+
+ test("promises no automatic rollout for a plan that creates a database", () => {
+ renderWaiting([], false, [], [changeSpec, createDatabaseSpec]);
+ expect(
+ screen.queryByText("plan.deploy-waiting.creating-rollout")
+ ).toBeNull();
+ expect(screen.getByText("plan.deploy-waiting.ready-to-deploy")).toBeDefined();
+ expect(
+ screen.getByText("plan.deploy-waiting.manual-rollout")
+ ).toBeDefined();
+ expect(screen.queryByText("plan.deploy-waiting.auto-create")).toBeNull();
+ });
+
+ test("a draft waits on submission and offers no override", () => {
+ renderWaiting([{ kind: "submit" }, { kind: "review", row: openRule }], true);
+ expect(screen.getByText("plan.deploy-waiting.submit")).toBeDefined();
+ expect(
+ screen.queryByText("plan.review.footer.bypass-and-deploy")
+ ).toBeNull();
+ });
+
+ test("a submitted plan keeps the override beside the list", () => {
+ renderWaiting([{ kind: "review", row: openRule }]);
+ fireEvent.click(screen.getByText("plan.review.footer.bypass-and-deploy"));
+ expect(mocks.triggerDeploy).toHaveBeenCalledOnce();
+ });
+
+ test("flags a P0 resolved without a change without holding the rollout", () => {
+ renderWaiting([], false, [
+ {
+ reviewer: "rule",
+ conclusion: "resolved",
+ findings: { ...emptyFindings(), overridden: 1 },
+ holdsRollout: false,
+ },
+ ]);
+ expect(
+ screen.getByText("plan.deploy-waiting.creating-rollout")
+ ).toBeDefined();
+ const line = screen.getByTestId("deploy-overridden");
+ expect(line.textContent).toContain("plan.deploy-waiting.overridden");
+ fireEvent.click(screen.getAllByText("plan.deploy-waiting.show")[0]);
+ expect(mocks.requestReviewRow).toHaveBeenCalledWith("rule");
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.tsx
new file mode 100644
index 0000000000..2c0292de26
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailDeployWaiting.tsx
@@ -0,0 +1,254 @@
+import {
+ CircleAlert,
+ CircleCheck,
+ CircleDashed,
+ Clock3,
+ Loader2,
+ MessagesSquare,
+ Send,
+ TriangleAlert,
+ UserRound,
+} from "lucide-react";
+import type { ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { displayRoleTitleFromList } from "@/lib/role";
+import { useAppStore } from "@/stores/app";
+import { isThreadRoot } from "@/stores/app/issueComment";
+import {
+ type Issue,
+ type IssueComment,
+ IssueComment_ThreadState,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { useFocusThread } from "../hooks/useFocusThread";
+import type { PlanReviewState } from "../hooks/usePlanReviewState";
+import { usePlanDetailStoreApi } from "../shared/stores/usePlanDetailStore";
+import { focusPlanPhase } from "../shell/focusPhase";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { supportsAutomaticRollout } from "../utils/phaseSummary";
+import type { AutomatedReviewRow, PlanGate } from "../utils/planGates";
+import { reviewerLabel, reviewGateLabel } from "../utils/reviewLabels";
+import { BypassAndDeploySheet, useBypassDeploy } from "./review/bypassDeploy";
+
+const NO_COMMENTS: IssueComment[] = [];
+
+// Before the rollout exists, Deploy says what the automatic rollout waits on.
+// Each line leads to where it is settled; the bypass sits beside them.
+export function PlanDetailDeployWaiting({
+ issue,
+ plan,
+ state,
+}: {
+ issue: Issue;
+ plan: Plan;
+ state: PlanReviewState;
+}) {
+ const { t } = useTranslation();
+ const { gates } = state;
+ // The server creates no rollout for a plan with other kinds of changes,
+ // such as creating a database; someone deploys it once these pass.
+ const automatic = supportsAutomaticRollout(plan);
+ // Not a gate: the server rolls out past it, so it sits apart from what the
+ // rollout waits on, but an approver should look at it.
+ const overridden = state.rows.filter((row) => row.findings.overridden > 0);
+ return (
+ <div
+ className="mt-1.5 flex flex-col gap-y-2 rounded-sm border bg-background px-3 py-2.5"
+ data-testid="deploy-waiting"
+ >
+ {gates.length === 0 ? (
+ automatic ? (
+ <div className="flex items-center gap-x-2 text-sm text-control">
+ <Loader2 className="size-4 animate-spin text-control-light" />
+ {t("plan.deploy-waiting.creating-rollout")}
+ </div>
+ ) : (
+ <div className="flex items-center gap-x-2 text-sm text-control">
+ <CircleCheck className="size-4 text-success" />
+ {t("plan.deploy-waiting.ready-to-deploy")}
+ </div>
+ )
+ ) : (
+ <>
+ <span className="text-xs text-control-light">
+ {t("plan.deploy-waiting.waiting-on")}
+ </span>
+ <ul className="flex flex-col gap-y-1.5">
+ {gates.map((gate) => (
+ <GateLine gate={gate} key={gateKey(gate)} />
+ ))}
+ </ul>
+ </>
+ )}
+ {!issue.draft && (
+ <DeployWaitingFooter automatic={automatic} issue={issue} plan={plan} />
+ )}
+ {overridden.length > 0 && (
+ <div className="flex flex-col gap-y-1.5 border-t pt-2">
+ <span className="text-xs text-control-light">
+ {t("plan.deploy-waiting.worth-a-look")}
+ </span>
+ {overridden.map((row) => (
+ <OverriddenLine key={row.reviewer} row={row} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const gateKey = (gate: PlanGate) =>
+ gate.kind === "review" ? `review:${gate.row.reviewer}` : gate.kind;
+
+function GateLine({ gate }: { gate: PlanGate }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const storeApi = usePlanDetailStoreApi();
+ const roleList = useAppStore((state) => state.roleList);
+ const { focusInStatement } = useFocusThread();
+ const comments = useAppStore((state) =>
+ page.issue ? state.getIssueComments(page.issue.name) : NO_COMMENTS
+ );
+
+ let icon: ReactNode;
+ let label: string;
+ let onShow: (() => void) | undefined;
+ switch (gate.kind) {
+ case "submit":
+ icon = <Send className="size-4 text-control-light" />;
+ label = t("plan.deploy-waiting.submit");
+ break;
+ case "approval":
+ icon = <UserRound className="size-4 text-control-light" />;
+ label = gate.rejected
+ ? t("plan.deploy-waiting.approval-rejected")
+ : gate.role
+ ? t("plan.deploy-waiting.approval-from", {
+ role: displayRoleTitleFromList(gate.role, roleList),
+ })
+ : t("plan.deploy-waiting.approval");
+ onShow = () => focusPlanPhase("review", page.expandPhase);
+ break;
+ case "review": {
+ const { row } = gate;
+ icon =
+ row.conclusion === "open" ? (
+ <CircleAlert
+ className={
+ row.findings.p0 > 0 ? "size-4 text-error" : "size-4 text-warning"
+ }
+ />
+ ) : row.conclusion === "running" || row.conclusion === "loading" ? (
+ <Loader2 className="size-4 animate-spin text-control-light" />
+ ) : (
+ <CircleDashed className="size-4 text-control-light" />
+ );
+ label = reviewGateLabel(t, row);
+ onShow = () => {
+ focusPlanPhase("review", page.expandPhase);
+ storeApi.getState().requestReviewRow(row.reviewer);
+ };
+ break;
+ }
+ case "discussion":
+ icon = <MessagesSquare className="size-4 text-warning" />;
+ label = t("plan.deploy-waiting.open-discussions", { count: gate.open });
+ onShow = () => {
+ const first = comments.find(
+ (comment) =>
+ isThreadRoot(comment) &&
+ !comment.reviewMetadata &&
+ comment.threadState === IssueComment_ThreadState.OPEN
+ );
+ if (first) focusInStatement(first);
+ };
+ break;
+ }
+
+ return (
+ <li className="flex items-center gap-x-2 text-sm text-main">
+ <span className="flex size-4 shrink-0 items-center">{icon}</span>
+ <span className="min-w-0 flex-1">{label}</span>
+ {onShow && (
+ <Button
+ appearance="link"
+ className="text-control-light"
+ onClick={onShow}
+ size="xs"
+ >
+ {t("plan.deploy-waiting.show")}
+ </Button>
+ )}
+ </li>
+ );
+}
+
+function OverriddenLine({ row }: { row: AutomatedReviewRow }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const storeApi = usePlanDetailStoreApi();
+ return (
+ <div
+ className="flex items-center gap-x-2 text-sm text-main"
+ data-testid="deploy-overridden"
+ >
+ <TriangleAlert className="size-4 shrink-0 text-warning" />
+ <span className="min-w-0 flex-1">
+ {t("plan.deploy-waiting.overridden", {
+ count: row.findings.overridden,
+ reviewer: reviewerLabel(t, row.reviewer),
+ })}
+ </span>
+ <Button
+ appearance="link"
+ className="text-control-light"
+ onClick={() => {
+ focusPlanPhase("review", page.expandPhase);
+ storeApi.getState().requestReviewRow(row.reviewer);
+ }}
+ size="xs"
+ >
+ {t("plan.deploy-waiting.show")}
+ </Button>
+ </div>
+ );
+}
+
+function DeployWaitingFooter({
+ automatic,
+ issue,
+ plan,
+}: {
+ automatic: boolean;
+ issue: Issue;
+ plan: Plan;
+}) {
+ const { t } = useTranslation();
+ const bypass = useBypassDeploy(issue, plan);
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t pt-2">
+ <span className="flex min-w-0 flex-1 items-center gap-x-1.5 text-xs text-control-light">
+ <Clock3 className="size-3.5 shrink-0" />
+ {automatic
+ ? t("plan.deploy-waiting.auto-create")
+ : t("plan.deploy-waiting.manual-rollout")}
+ </span>
+ {bypass.weight !== "none" && (
+ <Button
+ appearance={bypass.weight === "button" ? "outline" : "link"}
+ className={
+ bypass.weight === "link" ? "text-control-light" : undefined
+ }
+ disabled={bypass.creating}
+ onClick={bypass.triggerDeploy}
+ size="xs"
+ >
+ {bypass.creating && <Loader2 className="size-3.5 animate-spin" />}
+ {t("plan.review.footer.bypass-and-deploy")}
+ </Button>
+ )}
+ <BypassAndDeploySheet bypass={bypass} issue={issue} />
+ </div>
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx
deleted file mode 100644
index 1e695adcc8..0000000000
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.test.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { expect, test, vi } from "vitest";
-import {
- type ReviewRun,
- ReviewRun_Status,
- ReviewRun_Type,
-} from "@/types/proto-es/v1/issue_service_pb";
-import type { RuleReviewRunState } from "../hooks/useRuleReviewRun";
-
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, options?: { count?: number }) =>
- options?.count === undefined ? key : `${key}:${options.count}`,
- }),
-}));
-
-vi.mock("@/components/HumanizeTs", async () => ({
- ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),
-}));
-
-import { PlanDetailRuleReviewSummary } from "./PlanDetailRuleReviewSummary";
-
-const reviewRun = (status: ReviewRun_Status, extra = {}) =>
- ({
- name: "projects/foo/issues/7/reviewRuns/rule",
- type: ReviewRun_Type.RULE,
- status,
- error: "",
- ...extra,
- }) as ReviewRun;
-
-const renderSummary = (state: Partial<RuleReviewRunState>) =>
- render(
- <PlanDetailRuleReviewSummary
- state={{
- loadFailed: false,
- openFindings: 0,
- reload: vi.fn(),
- run: undefined,
- stale: false,
- ...state,
- }}
- />
- );
-
-test("renders nothing while loading", () => {
- const { container } = renderSummary({});
- expect(container).toBeEmptyDOMElement();
-});
-
-test("says the review never ran", () => {
- renderSummary({ run: null });
- expect(screen.getByText("plan.rule-review.not-run")).toBeVisible();
-});
-
-test("says the review never ran on the plan's current SQL", () => {
- renderSummary({
- run: reviewRun(ReviewRun_Status.DONE, { outdated: true }),
- });
- expect(screen.getByText("plan.rule-review.not-run")).toBeVisible();
-});
-
-test.each([
- [ReviewRun_Status.AVAILABLE, "plan.rule-review.queued"],
- [ReviewRun_Status.RUNNING, "plan.rule-review.running"],
-])("shows a run in progress", (status, label) => {
- renderSummary({ run: reviewRun(status) });
- expect(screen.getByText(label)).toBeVisible();
-});
-
-test("counts the open findings of a completed run", () => {
- renderSummary({
- openFindings: 3,
- run: reviewRun(ReviewRun_Status.DONE, {
- endTime: { seconds: 5n, nanos: 0 },
- }),
- });
- expect(screen.getByText("plan.rule-review.open-findings:3")).toBeVisible();
- expect(screen.getByTestId("humanize-ts")).toHaveTextContent("5000");
-});
-
-test("says a completed run found nothing", () => {
- renderSummary({ run: reviewRun(ReviewRun_Status.DONE) });
- expect(screen.getByText("plan.rule-review.no-open-findings")).toBeVisible();
-});
-
-test("shows why a run failed", () => {
- renderSummary({
- run: reviewRun(ReviewRun_Status.FAILED, {
- error: "1 of 1 review units failed",
- }),
- });
- expect(screen.getByText("plan.rule-review.failed")).toBeVisible();
- expect(screen.getByText("1 of 1 review units failed")).toBeVisible();
-});
-
-test("offers a retry when the status could not be read", () => {
- const reload = vi.fn();
- renderSummary({ loadFailed: true, reload });
- expect(screen.getByText("plan.rule-review.load-failed")).toBeVisible();
- fireEvent.click(
- screen.getByRole("button", { name: "sql-review.standard-rules.retry" })
- );
- expect(reload).toHaveBeenCalledTimes(1);
-});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx
deleted file mode 100644
index 1b9ad576cd..0000000000
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailRuleReviewSummary.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { AlertCircle, CheckCircle, Loader2, XCircle } from "lucide-react";
-import { useTranslation } from "react-i18next";
-import { HumanizeTs } from "@/components/HumanizeTs";
-import { Button } from "@/components/ui/button";
-import { ReviewRun_Status } from "@/types/proto-es/v1/issue_service_pb";
-import { getTimeForPbTimestampProtoEs } from "@/types/timestamp";
-import type { RuleReviewRunState } from "../hooks/useRuleReviewRun";
-
-// The standard rule review's part of the Checks summary line.
-export function PlanDetailRuleReviewSummary({
- state,
-}: {
- state: RuleReviewRunState;
-}) {
- const { t } = useTranslation();
- const { loadFailed, openFindings, run } = state;
- if (loadFailed) {
- return (
- <span className="flex items-center gap-1 text-sm">
- <span className="text-error">{t("plan.rule-review.load-failed")}</span>
- <Button appearance="link" onClick={() => void state.reload()} size="xs">
- {t("sql-review.standard-rules.retry")}
- </Button>
- </span>
- );
- }
- if (run === undefined) return null;
- // An outdated run reviewed earlier SQL: the plan's current SQL has not run.
- if (run === null || run.outdated) {
- return (
- <span className="text-sm text-control-placeholder">
- {t("plan.rule-review.not-run")}
- </span>
- );
- }
- switch (run.status) {
- case ReviewRun_Status.AVAILABLE:
- case ReviewRun_Status.RUNNING:
- return (
- <span className="flex items-center gap-1 text-sm text-control">
- <Loader2 className="size-4 animate-spin" />
- {run.status === ReviewRun_Status.AVAILABLE
- ? t("plan.rule-review.queued")
- : t("plan.rule-review.running")}
- </span>
- );
- case ReviewRun_Status.DONE:
- return (
- <span className="flex items-center gap-x-3 text-sm">
- {openFindings > 0 ? (
- <span className="flex items-center gap-1 text-warning">
- <AlertCircle className="size-4" />
- {t("plan.rule-review.open-findings", { count: openFindings })}
- </span>
- ) : (
- <span className="flex items-center gap-1 text-success">
- <CheckCircle className="size-4" />
- {t("plan.rule-review.no-open-findings")}
- </span>
- )}
- <HumanizeTs
- className="text-xs text-control-placeholder"
- tsMs={getTimeForPbTimestampProtoEs(run.endTime)}
- />
- </span>
- );
- case ReviewRun_Status.FAILED:
- return (
- <span className="flex basis-full flex-col gap-y-1 text-sm">
- <span className="flex items-center gap-1 text-error">
- <XCircle className="size-4" />
- {t("plan.rule-review.failed")}
- </span>
- <span className="text-xs break-words text-control-light">
- {run.error}
- </span>
- </span>
- );
- default:
- return null;
- }
-}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx
index 5d6601f610..c0f8d17c0b 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx
@@ -44,6 +44,7 @@ import {
import { GetSheetRequestSchema } from "@/types/proto-es/v1/sheet_service_pb";
import { unknownDatabase } from "@/types/v1/database";
import { extractDatabaseResourceName, hasProjectPermissionV2 } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { engineSupportsSchemaEditor } from "@/utils/schemaEditor";
import { getStatementSize, MAX_UPLOAD_FILE_SIZE_MB } from "@/utils/sheet";
import { getInstanceResource } from "@/utils/v1/database";
@@ -63,6 +64,7 @@ import {
setLocalSheetStatement,
} from "../utils/localSheet";
import { getSQLAdviceMarkers } from "../utils/sqlAdvice";
+import { statementSummary } from "../utils/statementSummary";
import { SchemaEditorSheet } from "./SchemaEditorSheet";
import { StatementThreadsLayer } from "./threads/StatementThreadsLayer";
import {
@@ -225,6 +227,24 @@ export function PlanDetailStatementSection({
() => getSQLAdviceMarkers(planCheckRuns),
[planCheckRuns]
);
+ // Under SQL Review V2 the summary report is not a check; it describes the
+ // statement here.
+ const summary = useMemo(
+ () => (sqlReviewV2Enabled() ? statementSummary(planCheckRuns) : undefined),
+ [planCheckRuns]
+ );
+ const summaryText = summary
+ ? [
+ summary.types.join(", "),
+ summary.affectedRows > 0n
+ ? t("plan.statement-summary.affected-rows", {
+ count: Number(summary.affectedRows),
+ })
+ : "",
+ ]
+ .filter(Boolean)
+ .join(" · ")
+ : "";
useEffect(() => {
if (!isEditing) {
@@ -569,6 +589,14 @@ export function PlanDetailStatementSection({
>
<span>{statementTitle}</span>
{isEmpty && <span className="text-error">*</span>}
+ {summaryText && !isEmpty && (
+ <span
+ className="ml-2 text-xs font-normal normal-case text-control-light"
+ data-testid="statement-summary"
+ >
+ {summaryText}
+ </span>
+ )}
</div>
<Input
ref={inputRef}
diff --git a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskHeader.tsx b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskHeader.tsx
index e252201d4c..3cab25dc96 100644
--- a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskHeader.tsx
+++ b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskHeader.tsx
@@ -121,7 +121,7 @@ export function DeployTaskHeader({
key={item.key}
onClick={() => onAction(item.key)}
size="xs"
- appearance={item.key === "RUN" ? "solid" : "outline"}
+ appearance="outline"
>
{item.key === "RUN" && <Play className="size-3" />}
{item.key === "SKIP" && <SkipForward className="size-3" />}
diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
index eed5c70a4c..3b7d3c0604 100644
--- a/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
@@ -1,10 +1,10 @@
// The header's read-only "Plan status" control, shown when the current user does
// not own the next action (observer, not-your-turn) or the plan is in a pre-deploy
// blocker state. The trigger names the blocker; clicking opens a details panel
-// styled after GitHub's merge box — gate rows (Review, Plan checks, and under
-// SQL Review V2 the open threads), each a status icon + headline + subtext. The detail is ours: Review
-// expands to the (compact) approval flow; Plan checks expands to a severity
-// breakdown with a "View Details" link into the existing plan-check drawer. The
+// styled after GitHub's merge box — gate rows, each a status icon + headline +
+// subtext: Review, then Plan checks, or under SQL Review V2 the same gates the
+// Deploy waiting list shows (Automated review, Discussion). Review expands to
+// the (compact) approval flow; the other rows link to their details. The
// footer shows at most one state-dependent action: re-request review when
// rejected (mirroring the section's rejection banner), otherwise the demoted
// bypass-and-deploy override (BYT-9722).
@@ -12,11 +12,13 @@ import { create } from "@bufbuild/protobuf";
import {
ChevronDown,
ChevronRight,
+ CircleAlert,
CircleCheck,
CircleX,
Clock3,
Loader2,
MessagesSquare,
+ TriangleAlert,
} from "lucide-react";
import { type ReactNode, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -38,9 +40,15 @@ import { userNamePrefix } from "@/stores/modules/v1/common";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { RequestIssueRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
-import { useSqlReviewV2 } from "../../hooks/useSqlReviewV2";
+import {
+ type PlanReviewState,
+ usePlanReviewState,
+} from "../../hooks/usePlanReviewState";
+import { focusPlanPhase } from "../../shell/focusPhase";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import type { PlanCheckSummary } from "../../utils/phaseSummary";
+import { rowNeedsAttention } from "../../utils/planGates";
+import { reviewerLabel, reviewGateLabel } from "../../utils/reviewLabels";
import { BypassAndDeploySheet, useBypassDeploy } from "../review/bypassDeploy";
import { deriveSteps, ReviewApprovalFlow } from "../review/ReviewApprovalFlow";
import type { PlanStatusReason } from "./planLifecycleHeaderState";
@@ -63,7 +71,7 @@ export function PlanStatusAction({
const [open, setOpen] = useState(false);
const [checksDrawerOpen, setChecksDrawerOpen] = useState(false);
const bypass = useBypassDeploy(issue, page.plan);
- const sqlReview = useSqlReviewV2();
+ const reviewState = usePlanReviewState();
const tone = getPlanStatusTone(reason);
// Only the Review gate expands (to the approval flow); Checks is a static row
// with a View Details link. Open Review by default when it is the active gate.
@@ -84,10 +92,22 @@ export function PlanStatusAction({
return t("plan.lifecycle.rejected");
case "checks-failing":
return t("plan.lifecycle.checks-failing");
- case "threads-open":
+ case "threads-open": {
+ // Name what holds the rollout, from the same gates Deploy lists.
+ const gate = reviewState?.gates.find(
+ (candidate) =>
+ candidate.kind === "review" || candidate.kind === "discussion"
+ );
+ if (gate?.kind === "review") return reviewGateLabel(t, gate.row);
+ if (gate?.kind === "discussion") {
+ return t("plan.deploy-waiting.open-discussions", {
+ count: gate.open,
+ });
+ }
return t("plan.summary.n-unresolved-threads", {
count: bypass.unresolvedThreads,
});
+ }
}
})();
@@ -120,15 +140,25 @@ export function PlanStatusAction({
onToggle={() => setReviewOpen((v) => !v)}
open={reviewOpen}
/>
- <ChecksGateRow
- onViewDetails={() => {
- setOpen(false);
- setChecksDrawerOpen(true);
- }}
- summary={bypass.planCheckSummary}
- />
- {sqlReview && (
- <ThreadsGateRow count={sqlReview.unresolvedThreads} />
+ {reviewState ? (
+ <>
+ <AutomatedReviewGateRow
+ onViewDetails={() => {
+ setOpen(false);
+ focusPlanPhase("review", page.expandPhase);
+ }}
+ state={reviewState}
+ />
+ <DiscussionGateRow count={reviewState.openDiscussions} />
+ </>
+ ) : (
+ <ChecksGateRow
+ onViewDetails={() => {
+ setOpen(false);
+ setChecksDrawerOpen(true);
+ }}
+ summary={bypass.planCheckSummary}
+ />
)}
</div>
<PlanStatusFooter
@@ -455,10 +485,86 @@ function BypassAction({
);
}
-/* -------------------------- threads gate (ours) ------------------------- */
+/* ---------------------- SQL Review V2 gates (ours) ---------------------- */
+
+// The machine reviewers as one gate: what holds the rollout, or that they
+// passed. Details leads to the Automated review rows.
+function AutomatedReviewGateRow({
+ state,
+ onViewDetails,
+}: {
+ state: PlanReviewState;
+ onViewDetails: () => void;
+}) {
+ const { t } = useTranslation();
+ const held = state.rows.filter((row) => row.holdsRollout);
+ const overridden = state.rows.find((row) => row.findings.overridden > 0);
+ const attention = state.rows.filter(rowNeedsAttention).length;
+ let icon: ReactNode;
+ if (held.some((row) => row.conclusion === "failed")) {
+ icon = <CircleX className="size-5 shrink-0 text-error" />;
+ } else if (held.some((row) => row.findings.p0 > 0)) {
+ icon = <CircleAlert className="size-5 shrink-0 text-error" />;
+ } else if (
+ held.length > 0 &&
+ held.every((row) => row.conclusion === "running")
+ ) {
+ icon = (
+ <Loader2 className="size-5 shrink-0 animate-spin text-control-light" />
+ );
+ } else if (held.length > 0) {
+ icon = <CircleAlert className="size-5 shrink-0 text-warning" />;
+ } else if (overridden) {
+ icon = <TriangleAlert className="size-5 shrink-0 text-warning" />;
+ } else {
+ icon = <CircleCheck className="size-5 shrink-0 text-success" />;
+ }
+ let title: string;
+ if (held.length > 0) {
+ title = reviewGateLabel(t, held[0]);
+ } else if (overridden) {
+ title = t("plan.deploy-waiting.overridden", {
+ count: overridden.findings.overridden,
+ reviewer: reviewerLabel(t, overridden.reviewer),
+ });
+ } else {
+ title = t("plan.lifecycle.gate-automated-review-passed");
+ }
+ return (
+ <div className="flex items-center gap-3 px-4 py-3">
+ {icon}
+ <GateLabel
+ subtitle={
+ held.length > 0 && overridden
+ ? t("plan.deploy-waiting.overridden", {
+ count: overridden.findings.overridden,
+ reviewer: reviewerLabel(t, overridden.reviewer),
+ })
+ : attention > 0
+ ? t("plan.automated-review.needs-attention", {
+ count: attention,
+ total: state.rows.length,
+ })
+ : ""
+ }
+ title={title}
+ />
+ <Button
+ appearance="secondary"
+ size="xs"
+ className="inline-flex shrink-0 items-center gap-1 text-xs text-accent hover:underline"
+ onClick={onViewDetails}
+ type="button"
+ >
+ {t("common.view-details")}
+ <ChevronRight className="size-3.5" />
+ </Button>
+ </div>
+ );
+}
-// Under SQL Review V2 every open thread holds the automatic rollout.
-function ThreadsGateRow({ count }: { count: number }) {
+// Open threads people started; each holds the rollout.
+function DiscussionGateRow({ count }: { count: number }) {
const { t } = useTranslation();
return (
<div className="flex items-center gap-3 px-4 py-3">
@@ -471,8 +577,8 @@ function ThreadsGateRow({ count }: { count: number }) {
subtitle={count > 0 ? t("plan.lifecycle.gate-threads-open-sub") : ""}
title={
count > 0
- ? t("plan.lifecycle.gate-threads-open", { count })
- : t("plan.lifecycle.gate-threads-resolved")
+ ? t("plan.deploy-waiting.open-discussions", { count })
+ : t("plan.lifecycle.gate-no-open-discussions")
}
/>
</div>
diff --git a/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.test.tsx b/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.test.tsx
new file mode 100644
index 0000000000..819b246a7d
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.test.tsx
@@ -0,0 +1,487 @@
+import { create } from "@bufbuild/protobuf";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { cloneElement, type ReactElement, type ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { PositionSchema } from "@/types/proto-es/v1/common_pb";
+import {
+ IssueComment_ReviewMetadata_Priority,
+ IssueComment_ReviewMetadataSchema,
+ IssueComment_ThreadState,
+ IssueCommentSchema,
+ IssueSchema,
+ ReviewRun_Status,
+ ReviewRun_Type,
+ ReviewRunSchema,
+ StatementAnchorSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { Engine, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import type { PlanReviewState } from "../../hooks/usePlanReviewState";
+import {
+ type AutomatedReviewRow,
+ emptyFindings,
+ type ReviewerFindings,
+} from "../../utils/planGates";
+
+const mocks = vi.hoisted(() => ({
+ comments: [] as unknown[],
+ focusInStatement: vi.fn(),
+ setWalkerFilter: vi.fn(),
+ runChecks: vi.fn(async () => undefined),
+ reload: vi.fn(async () => undefined),
+ routerPush: vi.fn(),
+ ruleReview: undefined as unknown,
+ rules: undefined as unknown,
+ runReview: vi.fn(async () => ({})),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/api", () => ({
+ issueServiceClientConnect: { runReview: mocks.runReview },
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+
+vi.mock("@/utils/iam/permission", () => ({
+ hasProjectPermissionV2: () => true,
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options?.count === undefined ? key : `${key}:${options.count}`,
+ }),
+}));
+
+vi.mock("@/app/router", () => ({ router: { push: mocks.routerPush } }));
+
+// A hover's content renders beside its trigger, so a test can read it.
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({
+ content,
+ children,
+ render,
+ }: {
+ content: ReactNode;
+ children: ReactNode;
+ render?: ReactElement;
+ }) => (
+ <>
+ {render ? cloneElement(render, undefined, children) : children}
+ {content ? <span data-testid="tooltip">{content}</span> : null}
+ </>
+ ),
+}));
+
+vi.mock("@/components/HumanizeTs", async () => ({
+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),
+}));
+
+vi.mock("@/components/plan-check/PlanCheckSection", () => ({
+ PlanCheckResultsDrawer: ({ open }: { open: boolean }) =>
+ open ? <div data-testid="checks-drawer" /> : null,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ getIssueComments: () => mocks.comments,
+ databasesByName: {
+ "instances/i/databases/hr_test": {
+ instanceResource: { engine: Engine.POSTGRES },
+ },
+ },
+ dbGroupsByName: {},
+ dbGroupViewByName: {},
+ }),
+}));
+
+vi.mock("../../hooks/useEffectiveStandardRules", () => ({
+ useEffectiveStandardRules: () => mocks.rules,
+}));
+
+vi.mock("../../hooks/usePlanCheckActions", () => ({
+ usePlanCheckActions: () => ({
+ allowRunChecks: true,
+ isRunningChecks: false,
+ runChecks: mocks.runChecks,
+ }),
+}));
+
+vi.mock("../../hooks/useFocusThread", () => ({
+ useFocusThread: () => ({
+ focusInActivity: vi.fn(),
+ focusInStatement: mocks.focusInStatement,
+ }),
+}));
+
+vi.mock("../../hooks/useSqlReviewV2", () => ({
+ useSqlReviewV2: () => ({ ruleReview: mocks.ruleReview }),
+}));
+
+vi.mock("../../shared/stores/usePlanDetailStore", () => {
+ const state = {
+ reviewRowRequest: undefined,
+ setWalkerFilter: mocks.setWalkerFilter,
+ };
+ return {
+ usePlanDetailStore: (selector: (s: unknown) => unknown) => selector(state),
+ usePlanDetailStoreApi: () => ({ getState: () => state }),
+ };
+});
+
+vi.mock("../../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => ({
+ issue: create(IssueSchema, {
+ name: "projects/p/issues/1",
+ status: IssueStatus.OPEN,
+ }),
+ isEditing: false,
+ readonly: false,
+ rollout: undefined,
+ plan: create(PlanSchema, {
+ specs: [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, {
+ targets: ["instances/i/databases/hr_test"],
+ }),
+ },
+ },
+ ],
+ }),
+ planCheckRuns: [],
+ project: { ciSamplingSize: 0 },
+ projectId: "p",
+ }),
+}));
+
+import { AutomatedReviewSection } from "./AutomatedReviewSection";
+
+const finding = (
+ name: string,
+ line: number,
+ options: {
+ ruleType?: ReviewRuleType;
+ resolved?: boolean;
+ priority?: IssueComment_ReviewMetadata_Priority;
+ } = {}
+) =>
+ create(IssueCommentSchema, {
+ name,
+ threadState: options.resolved
+ ? IssueComment_ThreadState.RESOLVED
+ : IssueComment_ThreadState.OPEN,
+ statementAnchor: create(StatementAnchorSchema, {
+ spec: "spec-1",
+ startPosition: create(PositionSchema, { line }),
+ }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ ruleType: options.ruleType ?? ReviewRuleType.DISALLOW_DROP_OBJECT,
+ priority: options.priority ?? IssueComment_ReviewMetadata_Priority.P1,
+ }),
+ });
+
+const findings = (extra: Partial<ReviewerFindings> = {}): ReviewerFindings => ({
+ ...emptyFindings(),
+ ...extra,
+});
+
+const row = (
+ reviewer: AutomatedReviewRow["reviewer"],
+ conclusion: AutomatedReviewRow["conclusion"],
+ rowFindings = findings(),
+ extra: Partial<AutomatedReviewRow> = {}
+): AutomatedReviewRow => ({
+ reviewer,
+ conclusion,
+ findings: rowFindings,
+ holdsRollout: conclusion !== "passed" && conclusion !== "resolved",
+ ...extra,
+});
+
+const ai = (overrides: Partial<PlanReviewState["ai"]> = {}) => ({
+ allowRun: true,
+ canStart: true,
+ editing: false,
+ run: null,
+ runReview: vi.fn(async () => undefined),
+ shown: true,
+ starting: false,
+ ...overrides,
+});
+
+const renderSection = (
+ rows: AutomatedReviewRow[],
+ aiState: PlanReviewState["ai"] = ai()
+) =>
+ render(
+ <AutomatedReviewSection
+ state={{ rows, gates: [], openDiscussions: 0, ai: aiState }}
+ />
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.comments = [];
+ mocks.ruleReview = { loadFailed: false, reload: mocks.reload };
+ mocks.rules = { rules: [1, 2, 3], source: "project" };
+});
+
+afterEach(cleanup);
+
+describe("AutomatedReviewSection", () => {
+ test("puts each reviewer on one line with its open findings by priority", () => {
+ renderSection([
+ row("rule", "open", findings({ open: 3, p0: 1, p1: 2 })),
+ row("ai", "not-run"),
+ row("policy", "passed", undefined, { targets: 2 }),
+ ]);
+ expect(
+ screen.getByText("plan.automated-review.needs-attention:2")
+ ).toBeDefined();
+ const rule = screen.getByTestId("automated-review-rule");
+ expect(
+ screen.getByRole("button", { name: "plan.findings.n-priority:1" })
+ .textContent
+ ).toBe("P01");
+ expect(
+ screen.getByRole("button", { name: "plan.findings.n-priority:2" })
+ .textContent
+ ).toBe("P12");
+ expect(rule.textContent).not.toContain("P2");
+ expect(screen.getByText("plan.automated-review.not-run")).toBeDefined();
+ expect(screen.getByText("plan.automated-review.passed-on:2")).toBeDefined();
+ });
+
+ test("a count opens the first finding of its priority and narrows the walker", () => {
+ mocks.comments = [
+ finding("line-4", 4),
+ finding("line-2", 2),
+ finding("p0", 3, { priority: IssueComment_ReviewMetadata_Priority.P0 }),
+ ];
+ renderSection([row("rule", "open", findings({ open: 3, p0: 1, p1: 2 }))]);
+ fireEvent.click(
+ screen.getByRole("button", { name: "plan.findings.n-priority:2" })
+ );
+ expect(mocks.setWalkerFilter).toHaveBeenCalledWith({
+ runType: ReviewRun_Type.RULE,
+ group: "p1",
+ });
+ expect(mocks.focusInStatement).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "line-2" })
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: "plan.findings.n-priority:1" })
+ );
+ expect(mocks.focusInStatement).toHaveBeenLastCalledWith(
+ expect.objectContaining({ name: "p0" })
+ );
+ });
+
+ test("counts resolved findings and names them by rule on hover", () => {
+ mocks.comments = [
+ finding("drop-1", 1, { resolved: true }),
+ finding("drop-2", 2, { resolved: true }),
+ finding("where-3", 3, {
+ ruleType: ReviewRuleType.REQUIRE_WHERE,
+ resolved: true,
+ }),
+ ];
+ renderSection([row("rule", "resolved", findings({ resolved: 3 }))]);
+ const resolved = screen.getByRole("button", {
+ name: "plan.findings.n-resolved:3",
+ });
+ expect(resolved.nextElementSibling?.textContent).toContain(
+ "plan.findings.name-times:2"
+ );
+ fireEvent.click(resolved);
+ expect(mocks.setWalkerFilter).toHaveBeenCalledWith({
+ runType: ReviewRun_Type.RULE,
+ group: "resolved",
+ });
+ expect(mocks.focusInStatement).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "drop-1" })
+ );
+ expect(screen.queryByText(/plan.findings.n-overridden/)).toBeNull();
+ });
+
+ test("calls out a P0 resolved without a change and counts it as needing attention", () => {
+ mocks.comments = [
+ finding("null-3", 3, {
+ ruleType: ReviewRuleType.REQUIRE_IS_NULL,
+ priority: IssueComment_ReviewMetadata_Priority.P0,
+ resolved: true,
+ }),
+ ];
+ renderSection([row("rule", "resolved", findings({ overridden: 1 }))]);
+ expect(
+ screen.getByText("plan.automated-review.needs-attention:1")
+ ).toBeDefined();
+ const overridden = screen.getByRole("button", {
+ name: "plan.findings.n-overridden:1",
+ });
+ expect(overridden.nextElementSibling?.textContent).toContain(
+ "plan.findings.name-at-line"
+ );
+ fireEvent.click(overridden);
+ expect(mocks.setWalkerFilter).toHaveBeenCalledWith({
+ runType: ReviewRun_Type.RULE,
+ group: "overridden",
+ });
+ expect(mocks.focusInStatement).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "null-3" })
+ );
+ });
+
+ test("says on hover what the rule review covered", () => {
+ renderSection([row("rule", "passed")]);
+ expect(
+ screen.getByRole("button", { name: "plan.automated-review.scope-label" })
+ ).toBeDefined();
+ const scope = screen.getByTestId("review-scope");
+ expect(scope.textContent).toContain(
+ "plan.automated-review.scope-with-engines"
+ );
+ expect(scope.textContent).toContain("plan.automated-review.project-rules");
+ });
+
+ test("claims no coverage for a reviewer that has not run", () => {
+ renderSection([row("ai", "not-run"), row("rule", "running")]);
+ expect(screen.queryByTestId("review-scope")).toBeNull();
+ });
+
+ test("Run, Retry, and Rerun start the rule review alone", async () => {
+ const { unmount } = renderSection([row("rule", "outdated")]);
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /common.run/ }));
+ });
+ expect(mocks.runReview).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ name: "projects/p/issues/1/reviewRuns/rule" }),
+ expect.anything()
+ );
+ expect(mocks.reload).toHaveBeenCalledOnce();
+ expect(mocks.runChecks).not.toHaveBeenCalled();
+ unmount();
+
+ renderSection([row("rule", "failed", undefined, { error: "hr_test: metadata not synced" })]);
+ expect(
+ screen.getByRole("button", { name: /plan.automated-review.retry/ })
+ ).toBeDefined();
+ });
+
+ test("a rule review with a result offers Rerun, since settings and schema change results", async () => {
+ renderSection([row("rule", "open", findings({ open: 1, p1: 1 }))]);
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", { name: /plan.automated-review.rerun/ })
+ );
+ });
+ expect(mocks.runReview).toHaveBeenCalledOnce();
+ });
+
+ test("a rerun that would reopen resolved findings asks first", async () => {
+ renderSection([
+ row("rule", "open", findings({ open: 1, p1: 1, resolved: 1, overridden: 1 })),
+ ]);
+ fireEvent.click(
+ screen.getByRole("button", { name: /plan.automated-review.rerun/ })
+ );
+ expect(mocks.runReview).not.toHaveBeenCalled();
+ expect(
+ screen.getByText("plan.automated-review.rerun-rule-title")
+ ).toBeDefined();
+ expect(
+ screen.getByText("plan.automated-review.rerun-reopens:2")
+ ).toBeDefined();
+ const confirm = screen
+ .getAllByRole("button", { name: "plan.automated-review.rerun" })
+ .at(-1);
+ await act(async () => {
+ fireEvent.click(confirm!);
+ });
+ expect(mocks.runReview).toHaveBeenCalledOnce();
+ });
+
+ test("shows a failed run's error in full", () => {
+ renderSection([
+ row("rule", "failed", undefined, {
+ error: "hr_test: metadata not synced",
+ }),
+ ]);
+ expect(screen.getByText("hr_test: metadata not synced")).toBeDefined();
+ });
+
+ test("an AI review waits for unsaved edits and says so on hover", () => {
+ renderSection([row("ai", "not-run")], ai({ canStart: false, editing: true }));
+ const run = screen.getByRole("button", { name: "plan.ai-review.run" });
+ expect((run as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByTestId("tooltip").textContent).toBe(
+ "plan.ai-review.save-first"
+ );
+ });
+
+ test("a finished AI review offers Rerun behind a confirmation", async () => {
+ const aiState = ai({
+ run: create(ReviewRunSchema, { status: ReviewRun_Status.DONE }),
+ });
+ renderSection([row("ai", "passed")], aiState);
+ fireEvent.click(
+ screen.getByRole("button", { name: /plan.automated-review.rerun/ })
+ );
+ expect(aiState.runReview).not.toHaveBeenCalled();
+ expect(screen.getByText("plan.ai-review.run-again-title")).toBeDefined();
+ const confirm = screen
+ .getAllByRole("button", { name: "plan.automated-review.rerun" })
+ .at(-1);
+ await act(async () => {
+ fireEvent.click(confirm!);
+ });
+ expect(aiState.runReview).toHaveBeenCalledOnce();
+ });
+
+ test("Re-run all asks first when it would reopen resolved rule findings", async () => {
+ renderSection([row("rule", "resolved", findings({ resolved: 3 }))]);
+ fireEvent.click(screen.getByRole("button", { name: "common.more" }));
+ fireEvent.click(await screen.findByText("plan.automated-review.rerun-all"));
+ expect(mocks.runChecks).not.toHaveBeenCalled();
+ expect(
+ screen.getByText("plan.automated-review.rerun-all-description:3")
+ ).toBeDefined();
+ const confirm = screen
+ .getAllByRole("button", { name: "plan.automated-review.rerun-all" })
+ .at(-1);
+ await act(async () => {
+ fireEvent.click(confirm!);
+ });
+ expect(mocks.runChecks).toHaveBeenCalledOnce();
+ expect(mocks.reload).toHaveBeenCalledOnce();
+ });
+
+ test("a plan check row reruns the checks", async () => {
+ renderSection([row("policy", "passed", undefined, { targets: 1 })]);
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", { name: /plan.automated-review.rerun/ })
+ );
+ });
+ expect(mocks.runChecks).toHaveBeenCalledOnce();
+ });
+
+ test("a plan check row opens the check details", () => {
+ renderSection([
+ row("policy", "open", findings({ open: 1, p0: 1 }), { targets: 1 }),
+ ]);
+ expect(screen.getByText("plan.automated-review.n-errors:1")).toBeDefined();
+ fireEvent.click(screen.getByText("plan.automated-review.details"));
+ expect(screen.getByTestId("checks-drawer")).toBeDefined();
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.tsx b/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.tsx
new file mode 100644
index 0000000000..e573da161d
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/review/AutomatedReviewSection.tsx
@@ -0,0 +1,885 @@
+import type { TFunction } from "i18next";
+import {
+ CircleAlert,
+ CircleCheck,
+ CircleDashed,
+ CircleX,
+ EllipsisVertical,
+ Info,
+ Loader2,
+ Play,
+ RotateCw,
+ TriangleAlert,
+ UserCheck,
+} from "lucide-react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { router } from "@/app/router";
+import { PROJECT_V1_ROUTE_SQL_REVIEW } from "@/app/router/handles";
+import { HumanizeTs } from "@/components/HumanizeTs";
+import { PlanCheckResultsDrawer } from "@/components/plan-check/PlanCheckSection";
+import {
+ STANDARD_RULE_TYPES,
+ standardRuleText,
+} from "@/components/sql-review/standardRules";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { badgeVariants } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Tooltip } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { useAppStore } from "@/stores/app";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
+import {
+ type IssueComment,
+ IssueComment_ReviewMetadata_Priority,
+ ReviewRun_Status,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { extractDatabaseResourceName } from "@/utils";
+import { engineNameV1 } from "@/utils/v1/instance";
+import { useEffectiveStandardRules } from "../../hooks/useEffectiveStandardRules";
+import { useFocusThread } from "../../hooks/useFocusThread";
+import { usePlanCheckActions } from "../../hooks/usePlanCheckActions";
+import type { PlanReviewState } from "../../hooks/usePlanReviewState";
+import { useRuleReviewRerun } from "../../hooks/useRuleReviewRerun";
+import { useSqlReviewV2 } from "../../hooks/useSqlReviewV2";
+import {
+ usePlanDetailStore,
+ usePlanDetailStoreApi,
+} from "../../shared/stores/usePlanDetailStore";
+import { PROJECT_NAME_PREFIX } from "../../shell/constants";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { countByName, findingsInOrder } from "../../utils/findingIndex";
+import {
+ type AutomatedReviewer,
+ type AutomatedReviewRow,
+ type FindingGroup,
+ type FindingPriority,
+ findingTitle,
+ resolvedByPeople,
+ rowNeedsAttention,
+} from "../../utils/planGates";
+import { openFindingsLabel, reviewerLabel } from "../../utils/reviewLabels";
+import { reviewScope } from "../../utils/reviewScope";
+import {
+ priorityStyle,
+ ReviewerIcon,
+ reviewerName,
+} from "../threads/ReviewResult";
+
+// How many P0s resolved without a change a hover names before it counts the
+// rest.
+const NAMED_OVERRIDES = 3;
+// How many databases the scope names before it counts them.
+const NAMED_DATABASES = 3;
+const NO_COMMENTS: IssueComment[] = [];
+
+const runTypeOf = (reviewer: AutomatedReviewer): ReviewRun_Type | undefined =>
+ reviewer === "rule"
+ ? ReviewRun_Type.RULE
+ : reviewer === "ai"
+ ? ReviewRun_Type.AI
+ : undefined;
+
+// The machine reviewers, one line each, between Approval and Activity: the
+// conclusion, the open findings by priority, what people resolved, and what
+// the reviewer covered on hover. The findings themselves live in the editor;
+// every count opens it there.
+export function AutomatedReviewSection({ state }: { state: PlanReviewState }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { allowRunChecks, isRunningChecks, runChecks } = usePlanCheckActions();
+ const ruleReview = useSqlReviewV2()?.ruleReview;
+ const { rows } = state;
+ const attention = rows.filter(rowNeedsAttention).length;
+ const [checksDrawerOpen, setChecksDrawerOpen] = useState(false);
+ const [confirmChecks, setConfirmChecks] = useState(false);
+ const ruleRow = rows.find((row) => row.reviewer === "rule");
+ const ruleResolved = ruleRow ? resolvedByPeople(ruleRow.findings) : 0;
+
+ // Running the checks also starts the rule review on the server, which
+ // posts its findings again and reopens what people resolved.
+ const rerunAll = async () => {
+ await runChecks();
+ await ruleReview?.reload();
+ };
+ const requestRerunChecks = () => {
+ if (ruleResolved > 0) setConfirmChecks(true);
+ else void rerunAll();
+ };
+
+ if (rows.length === 0) return null;
+
+ return (
+ <div
+ className="flex flex-col gap-y-2 px-4 pt-4"
+ data-testid="automated-review"
+ >
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <h4 className="text-sm font-medium text-main">
+ {t("plan.automated-review.self")}
+ </h4>
+ <span className="text-sm text-control-light">
+ {attention > 0
+ ? t("plan.automated-review.needs-attention", {
+ count: attention,
+ total: rows.length,
+ })
+ : t("plan.automated-review.nothing-needs-attention")}
+ </span>
+ <div className="flex-1" />
+ <Button
+ appearance="link"
+ className="text-control-light"
+ onClick={() =>
+ void router.push({
+ name: PROJECT_V1_ROUTE_SQL_REVIEW,
+ params: { projectId: page.projectId },
+ })
+ }
+ size="xs"
+ >
+ {t("common.configure")}
+ </Button>
+ {allowRunChecks && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ aria-label={t("common.more")}
+ appearance="secondary"
+ size="xs"
+ />
+ }
+ >
+ <EllipsisVertical className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ disabled={isRunningChecks}
+ onClick={requestRerunChecks}
+ >
+ {t("plan.automated-review.rerun-all")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ <div className="flex flex-col divide-y rounded-sm border">
+ {rows.map((row) => (
+ <ReviewerRow
+ key={row.reviewer}
+ onRerunChecks={requestRerunChecks}
+ onViewChecks={() => setChecksDrawerOpen(true)}
+ row={row}
+ state={state}
+ />
+ ))}
+ </div>
+ <PlanCheckResultsDrawer
+ includeRunFailure
+ onOpenChange={setChecksDrawerOpen}
+ open={checksDrawerOpen}
+ planCheckRuns={page.planCheckRuns}
+ />
+ <RerunConfirmDialog
+ confirmLabel={t("plan.automated-review.rerun-all")}
+ description={t("plan.automated-review.rerun-all-description", {
+ count: ruleResolved,
+ })}
+ onConfirm={() => void rerunAll()}
+ onOpenChange={setConfirmChecks}
+ open={confirmChecks}
+ title={t("plan.automated-review.rerun-all-title")}
+ />
+ </div>
+ );
+}
+
+function RerunConfirmDialog({
+ open,
+ onOpenChange,
+ title,
+ description,
+ confirmLabel,
+ onConfirm,
+ disabled = false,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description: string;
+ confirmLabel: string;
+ onConfirm: () => void;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <AlertDialog onOpenChange={onOpenChange} open={open}>
+ <AlertDialogContent>
+ <AlertDialogTitle>{title}</AlertDialogTitle>
+ <AlertDialogDescription>{description}</AlertDialogDescription>
+ <AlertDialogFooter>
+ <Button appearance="secondary" onClick={() => onOpenChange(false)}>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={disabled}
+ onClick={() => {
+ onOpenChange(false);
+ onConfirm();
+ }}
+ >
+ {confirmLabel}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+function ReviewerRow({
+ row,
+ state,
+ onRerunChecks,
+ onViewChecks,
+}: {
+ row: AutomatedReviewRow;
+ state: PlanReviewState;
+ onRerunChecks: () => void;
+ onViewChecks: () => void;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const storeApi = usePlanDetailStoreApi();
+ const { focusInStatement } = useFocusThread();
+ const ruleReview = useSqlReviewV2()?.ruleReview;
+ const { allowRunChecks, isRunningChecks } = usePlanCheckActions();
+ const rerunRule = useRuleReviewRerun();
+ const runType = runTypeOf(row.reviewer);
+ const comments = useAppStore((s) =>
+ page.issue ? s.getIssueComments(page.issue.name) : NO_COMMENTS
+ );
+ const [confirm, setConfirm] = useState<"rule" | "ai">();
+ const rowRef = useRef<HTMLDivElement>(null);
+
+ // Activity's "Show" brings this row into view.
+ const reviewRowRequest = usePlanDetailStore((s) => s.reviewRowRequest);
+ useEffect(() => {
+ if (reviewRowRequest?.reviewer !== row.reviewer) return;
+ rowRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
+ }, [reviewRowRequest, row.reviewer]);
+
+ // A count opens the editor on the first finding of its group and narrows
+ // the walker to that group.
+ const openGroup = (group: FindingGroup) => {
+ if (runType === undefined) return;
+ const first = findingsInOrder(comments, runType, page.plan.specs, group)[0];
+ if (!first) return;
+ storeApi.getState().setWalkerFilter({ runType, group });
+ focusInStatement(first);
+ };
+
+ const ai = state.ai;
+ let name: ReactNode;
+ if (row.reviewer === "rule" || row.reviewer === "ai") {
+ name = (
+ <>
+ <ReviewerIcon
+ className="size-4 shrink-0 text-control-light"
+ runType={runType ?? ReviewRun_Type.RULE}
+ />
+ {reviewerName(t, runType ?? ReviewRun_Type.RULE)}
+ </>
+ );
+ } else {
+ name = reviewerLabel(t, row.reviewer);
+ }
+
+ const actions: ReactNode[] = [];
+ if (row.reviewer === "rule") {
+ if (ruleReview?.loadFailed) {
+ actions.push(
+ <Button
+ appearance="outline"
+ key="retry"
+ onClick={() => void ruleReview.reload()}
+ size="xs"
+ >
+ <RotateCw className="size-3.5" />
+ {t("plan.automated-review.retry")}
+ </Button>
+ );
+ } else if (
+ rerunRule.allowed &&
+ row.conclusion !== "running" &&
+ row.conclusion !== "loading"
+ ) {
+ // A rerun posts the findings again, reopening what people resolved.
+ const start = () => {
+ if (resolvedByPeople(row.findings) > 0) setConfirm("rule");
+ else void rerunRule.run();
+ };
+ actions.push(
+ <RunButton
+ conclusion={row.conclusion}
+ disabled={rerunRule.disabled}
+ key="run"
+ onClick={start}
+ />
+ );
+ }
+ }
+ if (
+ row.reviewer === "ai" &&
+ ai.allowRun &&
+ row.conclusion !== "running" &&
+ row.conclusion !== "loading"
+ ) {
+ // Every finished run is paid for in model calls, so running it again
+ // asks first.
+ const settled =
+ ai.run?.status === ReviewRun_Status.DONE && !ai.run.outdated;
+ actions.push(
+ <Tooltip
+ content={ai.editing ? t("plan.ai-review.save-first") : undefined}
+ key="run"
+ >
+ <RunButton
+ conclusion={settled ? "passed" : row.conclusion}
+ disabled={!ai.canStart}
+ label={settled ? undefined : t("plan.ai-review.run")}
+ onClick={() => (settled ? setConfirm("ai") : void ai.runReview())}
+ />
+ </Tooltip>
+ );
+ }
+ // Plan checks run together, and the run restarts the rule review too.
+ if (runType === undefined && allowRunChecks && row.conclusion !== "running") {
+ actions.push(
+ <RunButton
+ conclusion={row.conclusion}
+ disabled={isRunningChecks}
+ key="run"
+ onClick={onRerunChecks}
+ />
+ );
+ }
+ if (runType === undefined) {
+ actions.push(
+ <Button
+ appearance="link"
+ className="text-control-light"
+ key="details"
+ onClick={onViewChecks}
+ size="xs"
+ >
+ {t("plan.automated-review.details")}
+ </Button>
+ );
+ }
+
+ // A reviewer without a result has covered nothing yet.
+ const hasResult =
+ row.conclusion !== "not-run" &&
+ row.conclusion !== "loading" &&
+ row.conclusion !== "running";
+
+ return (
+ <div
+ className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-2 text-sm"
+ data-testid={`automated-review-${row.reviewer}`}
+ ref={rowRef}
+ >
+ <ConclusionIcon row={row} />
+ <span className="flex flex-1 items-center gap-x-1.5 font-medium text-main sm:w-44 sm:flex-none">
+ {name}
+ </span>
+ {/* Below the name on a narrow screen, lined up with it. */}
+ <span className="order-last flex min-w-0 basis-full flex-wrap items-center gap-x-1.5 gap-y-1 pl-7 text-control sm:order-none sm:flex-1 sm:pl-0">
+ <ConclusionText
+ comments={comments}
+ onOpen={openGroup}
+ row={row}
+ runType={runType}
+ />
+ {(row.reviewer === "rule" || row.reviewer === "ai") && hasResult && (
+ <ScopeInfo reviewer={row.reviewer} />
+ )}
+ </span>
+ {actions.length > 0 && (
+ <span className="flex shrink-0 items-center gap-x-2">{actions}</span>
+ )}
+ <RerunConfirmDialog
+ confirmLabel={t("plan.automated-review.rerun")}
+ description={
+ confirm === "ai"
+ ? t("plan.ai-review.run-again-description")
+ : t("plan.automated-review.rerun-reopens", {
+ count: resolvedByPeople(row.findings),
+ })
+ }
+ disabled={confirm === "ai" ? !ai.canStart : rerunRule.disabled}
+ onConfirm={() =>
+ confirm === "ai" ? void ai.runReview() : void rerunRule.run()
+ }
+ onOpenChange={(open) => !open && setConfirm(undefined)}
+ open={confirm !== undefined}
+ title={
+ confirm === "ai"
+ ? t("plan.ai-review.run-again-title")
+ : t("plan.automated-review.rerun-rule-title")
+ }
+ />
+ </div>
+ );
+}
+
+// Run before a first result or after the SQL changed, Retry after a failed
+// run, Rerun once there is a result.
+function RunButton({
+ conclusion,
+ disabled,
+ onClick,
+ label,
+}: {
+ conclusion: AutomatedReviewRow["conclusion"];
+ disabled: boolean;
+ onClick: () => void;
+ label?: string;
+}) {
+ const { t } = useTranslation();
+ const first = conclusion === "not-run" || conclusion === "outdated";
+ const text = first
+ ? t("common.run")
+ : conclusion === "failed"
+ ? t("plan.automated-review.retry")
+ : t("plan.automated-review.rerun");
+ return (
+ <Button
+ appearance="outline"
+ aria-label={label}
+ disabled={disabled}
+ onClick={onClick}
+ size="xs"
+ >
+ {first ? (
+ <Play className="size-3.5" />
+ ) : (
+ <RotateCw className="size-3.5" />
+ )}
+ {text}
+ </Button>
+ );
+}
+
+// Status color sits on the icon; the text stays readable. A P0 resolved
+// without a change keeps the row amber after everything is resolved.
+function ConclusionIcon({ row }: { row: AutomatedReviewRow }) {
+ const className = "size-4 shrink-0";
+ switch (row.conclusion) {
+ case "passed":
+ return <CircleCheck className={cn(className, "text-success")} />;
+ case "resolved":
+ return row.findings.overridden > 0 ? (
+ <TriangleAlert className={cn(className, "text-warning")} />
+ ) : (
+ <UserCheck className={cn(className, "text-control-light")} />
+ );
+ case "open":
+ return (
+ <CircleAlert
+ className={cn(
+ className,
+ row.findings.p0 > 0 ? "text-error" : "text-warning"
+ )}
+ />
+ );
+ case "failed":
+ return <CircleX className={cn(className, "text-error")} />;
+ case "running":
+ case "loading":
+ return (
+ <Loader2 className={cn(className, "animate-spin text-control-light")} />
+ );
+ default:
+ return <CircleDashed className={cn(className, "text-control-light")} />;
+ }
+}
+
+const PRIORITY: Record<FindingPriority, IssueComment_ReviewMetadata_Priority> =
+ {
+ p0: IssueComment_ReviewMetadata_Priority.P0,
+ p1: IssueComment_ReviewMetadata_Priority.P1,
+ p2: IssueComment_ReviewMetadata_Priority.P2,
+ };
+const PRIORITIES: readonly FindingPriority[] = ["p0", "p1", "p2"];
+
+// A count of findings that opens them in the statement editor, with what
+// they are and where the click goes on hover.
+function FindingCount({
+ label,
+ hint,
+ className,
+ onClick,
+ children,
+}: {
+ label: string;
+ hint: ReactNode;
+ className?: string;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Tooltip
+ content={
+ <span className="flex flex-col gap-y-1">
+ {hint}
+ <span className="text-main-text/70">
+ {t("plan.automated-review.opens-in-sql")}
+ </span>
+ </span>
+ }
+ popupClassName="max-w-72"
+ render={
+ <Button
+ appearance="link"
+ aria-label={label}
+ className={cn("h-auto p-0 font-normal", className)}
+ onClick={onClick}
+ size="xs"
+ />
+ }
+ >
+ {children}
+ </Tooltip>
+ );
+}
+
+// A finding's name: its rule, or for the AI review, its title.
+const findingName = (t: TFunction, comment: IssueComment): string => {
+ const ruleType =
+ comment.reviewMetadata?.ruleType ??
+ ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED;
+ return ruleType === ReviewRuleType.REVIEW_RULE_TYPE_UNSPECIFIED
+ ? findingTitle(comment)
+ : standardRuleText(t, ruleType).title;
+};
+
+// The names of a group's findings for a hover: by line for the few P0s that
+// need a look, by count per rule for the rest.
+function useGroupNames(
+ comments: readonly IssueComment[],
+ runType: ReviewRun_Type | undefined,
+ group: "overridden" | "resolved",
+ count: number
+): string {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ return useMemo(() => {
+ if (runType === undefined || count === 0) return "";
+ const findings = findingsInOrder(comments, runType, page.plan.specs, group);
+ if (group === "overridden") {
+ const named = findings.slice(0, NAMED_OVERRIDES).map((comment) => {
+ const line = comment.statementAnchor?.startPosition?.line;
+ return line
+ ? t("plan.findings.name-at-line", {
+ name: findingName(t, comment),
+ line,
+ })
+ : findingName(t, comment);
+ });
+ const rest = findings.length - named.length;
+ if (rest > 0) named.push(t("plan.findings.n-more", { count: rest }));
+ return named.join(t("plan.findings.separator"));
+ }
+ return countByName(findings, (comment) => findingName(t, comment))
+ .map(([name, times]) =>
+ times > 1 ? t("plan.findings.name-times", { name, count: times }) : name
+ )
+ .join(t("plan.findings.separator"));
+ }, [comments, count, group, page.plan.specs, runType, t]);
+}
+
+function ConclusionText({
+ row,
+ runType,
+ comments,
+ onOpen,
+}: {
+ row: AutomatedReviewRow;
+ runType: ReviewRun_Type | undefined;
+ comments: readonly IssueComment[];
+ onOpen: (group: FindingGroup) => void;
+}) {
+ const { t } = useTranslation();
+ const { findings } = row;
+ const overriddenNames = useGroupNames(
+ comments,
+ runType,
+ "overridden",
+ findings.overridden
+ );
+ const resolvedNames = useGroupNames(
+ comments,
+ runType,
+ "resolved",
+ findings.resolved
+ );
+ const time = row.time && (
+ <HumanizeTs
+ className="text-control-light"
+ tsMs={getTimeForPbTimestampProtoEs(row.time)}
+ />
+ );
+ const isPlanCheck = runType === undefined;
+ const parts: ReactNode[] = [];
+ switch (row.conclusion) {
+ case "loading":
+ parts.push(t("common.loading"));
+ break;
+ case "not-run":
+ parts.push(t("plan.automated-review.not-run"));
+ break;
+ case "running":
+ parts.push(t("plan.automated-review.running"));
+ break;
+ case "outdated":
+ parts.push(t("plan.automated-review.outdated"));
+ break;
+ case "failed":
+ parts.push(
+ <span className="break-words whitespace-normal text-main" key="error">
+ {row.error || t("plan.automated-review.failed")}
+ </span>
+ );
+ break;
+ case "passed":
+ parts.push(
+ isPlanCheck && row.targets
+ ? t("plan.automated-review.passed-on", { count: row.targets })
+ : t("plan.automated-review.no-findings")
+ );
+ if (row.warnings) {
+ parts.push(
+ t("plan.automated-review.n-warnings", { count: row.warnings })
+ );
+ }
+ break;
+ case "open":
+ case "resolved":
+ if (isPlanCheck) {
+ parts.push(
+ <span className="font-medium text-main" key="errors">
+ {openFindingsLabel(t, row)}
+ </span>
+ );
+ if (row.warnings) {
+ parts.push(
+ t("plan.automated-review.n-warnings", { count: row.warnings })
+ );
+ }
+ break;
+ }
+ if (findings.open > 0) {
+ parts.push(
+ <span className="flex items-center gap-x-1.5" key="open">
+ {PRIORITIES.filter((priority) => findings[priority] > 0).map(
+ (priority) => (
+ <PriorityCount
+ count={findings[priority]}
+ key={priority}
+ onClick={() => onOpen(priority)}
+ priority={priority}
+ />
+ )
+ )}
+ </span>
+ );
+ }
+ if (findings.resolved > 0) {
+ parts.push(
+ <FindingCount
+ className="text-sm text-control underline decoration-control-border underline-offset-2 hover:text-main"
+ hint={resolvedNames}
+ key="resolved"
+ label={t("plan.findings.n-resolved", { count: findings.resolved })}
+ onClick={() => onOpen("resolved")}
+ >
+ {t("plan.findings.n-resolved", { count: findings.resolved })}
+ </FindingCount>
+ );
+ }
+ if (findings.overridden > 0) {
+ parts.push(
+ <FindingCount
+ className="text-sm text-main underline decoration-warning underline-offset-2"
+ hint={overriddenNames}
+ key="overridden"
+ label={t("plan.findings.n-overridden", {
+ count: findings.overridden,
+ })}
+ onClick={() => onOpen("overridden")}
+ >
+ <TriangleAlert className="size-3.5 shrink-0 text-warning" />
+ {t("plan.findings.n-overridden", { count: findings.overridden })}
+ </FindingCount>
+ );
+ }
+ break;
+ }
+ if (time && row.conclusion !== "loading" && row.conclusion !== "not-run") {
+ parts.push(time);
+ }
+ return (
+ <>
+ {parts.map((part, index) => (
+ <span
+ className="flex items-center gap-x-1.5 whitespace-nowrap"
+ key={index}
+ >
+ {index > 0 && <span className="text-control-light">·</span>}
+ {part}
+ </span>
+ ))}
+ </>
+ );
+}
+
+// "P0 2", colored as the priority badge on each finding.
+function PriorityCount({
+ priority,
+ count,
+ onClick,
+}: {
+ priority: FindingPriority;
+ count: number;
+ onClick: () => void;
+}) {
+ const { t } = useTranslation();
+ const style = priorityStyle(t, PRIORITY[priority]);
+ return (
+ <FindingCount
+ className={badgeVariants({ variant: style?.variant })}
+ hint={style?.description}
+ label={t("plan.findings.n-priority", {
+ count,
+ priority: priority.toUpperCase(),
+ })}
+ onClick={onClick}
+ >
+ {priority.toUpperCase()}
+ <span className="font-semibold">{count}</span>
+ </FindingCount>
+ );
+}
+
+// What the reviewer covered, on hover: the databases, and for the rule
+// review, the rules it applies. A "No findings" means little without it.
+function ScopeInfo({ reviewer }: { reviewer: "rule" | "ai" }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const databasesByName = useAppStore((s) => s.databasesByName);
+ const dbGroupsByName = useAppStore((s) => s.dbGroupsByName);
+ const dbGroupViewByName = useAppStore((s) => s.dbGroupViewByName);
+ const rules = useEffectiveStandardRules(
+ `${PROJECT_NAME_PREFIX}${page.projectId}`
+ );
+ const scope = useMemo(
+ () =>
+ reviewScope(page.plan, {
+ reviewer,
+ sampleSize: page.project.ciSamplingSize ?? 0,
+ matchedDatabases: (group) =>
+ dbGroupViewByName[group] === DatabaseGroupView.FULL
+ ? (dbGroupsByName[group]?.matchedDatabases.map(
+ (database) => database.name
+ ) ?? [])
+ : undefined,
+ engineOf: (database) =>
+ databasesByName[database]?.instanceResource?.engine,
+ }),
+ [
+ databasesByName,
+ dbGroupViewByName,
+ dbGroupsByName,
+ page.plan,
+ page.project.ciSamplingSize,
+ reviewer,
+ ]
+ );
+ if (scope.databases.length === 0) return null;
+
+ const names =
+ scope.databases.length <= NAMED_DATABASES
+ ? scope.databases
+ .map((database) => extractDatabaseResourceName(database).databaseName)
+ .join(t("plan.findings.separator"))
+ : t("plan.automated-review.n-databases", {
+ count: scope.databases.length,
+ });
+ const lines = [
+ scope.engines.length > 0
+ ? t("plan.automated-review.scope-with-engines", {
+ databases: names,
+ engines: scope.engines.map(engineNameV1).join(", "),
+ })
+ : t("plan.automated-review.scope", { databases: names }),
+ ];
+ if (scope.total > scope.databases.length) {
+ lines.push(
+ t("plan.automated-review.sampled", {
+ count: scope.databases.length,
+ total: scope.total,
+ })
+ );
+ }
+ if (reviewer === "rule" && rules) {
+ const counts = {
+ on: rules.rules.length,
+ total: STANDARD_RULE_TYPES.length,
+ };
+ lines.push(
+ rules.source === "project"
+ ? t("plan.automated-review.project-rules", counts)
+ : t("plan.automated-review.workspace-rules", counts)
+ );
+ }
+ return (
+ <Tooltip
+ content={
+ <span className="flex flex-col gap-y-1" data-testid="review-scope">
+ {lines.map((line) => (
+ <span key={line}>{line}</span>
+ ))}
+ </span>
+ }
+ popupClassName="max-w-72"
+ render={
+ <Button
+ appearance="link"
+ aria-label={t("plan.automated-review.scope-label")}
+ className="h-auto cursor-help p-0 text-control-light hover:text-control"
+ size="xs"
+ />
+ }
+ >
+ <Info className="size-3.5" />
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
index 4e6504057e..baff317bea 100644
--- a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.test.tsx
@@ -54,6 +54,7 @@ const mocks = vi.hoisted(() => ({
name: "users/[email protected]",
title: "Me",
},
+ reviewState: undefined as unknown,
}));
// ---------------------------------------------------------------------------
@@ -309,6 +310,14 @@ vi.mock("./ReviewActivityTimeline", () => ({
ReviewActivityTimeline: () => null,
}));
+vi.mock("../../hooks/usePlanReviewState", () => ({
+ usePlanReviewState: () => mocks.reviewState,
+}));
+
+vi.mock("./AutomatedReviewSection", () => ({
+ AutomatedReviewSection: () => <div data-testid="automated-review" />,
+}));
+
// Import React for JSX — must come after vi.mock calls.
import React from "react";
@@ -437,6 +446,7 @@ const renderIntoContainer = (element: ReactElement) => {
// ---------------------------------------------------------------------------
beforeEach(() => {
+ mocks.reviewState = undefined;
mocks.comments = [];
mocks.getIssueComments.mockImplementation(() => mocks.comments);
vi.clearAllMocks();
@@ -671,4 +681,31 @@ describe("PlanReviewSection — five review states", () => {
unmount();
});
+
+ test.each([
+ ["keeps the automated reviewers below it under SQL Review V2", {}, true],
+ ["shows only that without SQL Review V2", undefined, false],
+ ])(
+ "while the approval flow is generated, %s",
+ (_, reviewState, showsReviewers) => {
+ mocks.reviewState = reviewState;
+ const issue = makeIssue({ approvalStatus: ApprovalStatus.CHECKING });
+ const { container, render, unmount } = renderIntoContainer(
+ <PlanDetailProvider value={makePageState(issue, makePlan())}>
+ <PlanReviewSection />
+ </PlanDetailProvider>
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ "custom-approval.issue-review.generating-approval-flow"
+ );
+ expect(
+ container.querySelector("[data-testid='automated-review']") !== null
+ ).toBe(showsReviewers);
+
+ unmount();
+ }
+ );
});
diff --git a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx
index e8dd9c6f95..c04efb2482 100644
--- a/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/PlanReviewSection.tsx
@@ -4,7 +4,9 @@ import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { usePlanReviewState } from "../../hooks/usePlanReviewState";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { AutomatedReviewSection } from "./AutomatedReviewSection";
import { ReviewActivityTimeline } from "./ReviewActivityTimeline";
import { ReviewApprovalFlow } from "./ReviewApprovalFlow";
import { ReviewReadinessFooter } from "./ReviewReadinessFooter";
@@ -35,43 +37,67 @@ export function PlanReviewSection() {
const comments = useAppStore((state) =>
issueName ? state.getIssueComments(issueName) : EMPTY_COMMENTS
);
+ // Under SQL Review V2 the machine reviews run from draft onward, so Review
+ // shows them, and Deploy lists what the rollout waits on.
+ const reviewState = usePlanReviewState();
if (!issue) return null;
if (issue.draft) {
return (
- <ReviewActivityTimeline
- comments={comments}
- issue={issue}
- plan={page.plan}
- />
- );
- }
-
- if (issue.approvalStatus === ApprovalStatus.CHECKING) {
- return (
- <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">
- <div className="size-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />
- <span>
- {t("custom-approval.issue-review.generating-approval-flow")}
- </span>
+ <div className="flex flex-col">
+ {reviewState && (
+ <div className="flex flex-col gap-y-1 px-4 pt-3">
+ <h3 className="text-base font-medium text-main">
+ {t("issue.approval-flow.self")}
+ </h3>
+ <p className="text-sm text-control-light">
+ {t("plan.review.approval-after-submit")}
+ </p>
+ </div>
+ )}
+ {reviewState && <AutomatedReviewSection state={reviewState} />}
+ <ReviewActivityTimeline
+ comments={comments}
+ issue={issue}
+ plan={page.plan}
+ />
</div>
);
}
+ const generatingFlow = (
+ <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">
+ <div className="size-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />
+ <span>{t("custom-approval.issue-review.generating-approval-flow")}</span>
+ </div>
+ );
+ const generating = issue.approvalStatus === ApprovalStatus.CHECKING;
+ if (generating && !reviewState) return generatingFlow;
+
+ // The automated reviewers stay reachable while the approval flow is being
+ // generated: a failed evaluation is retried by rerunning the plan checks.
return (
<div className="flex flex-col">
- <PlanReviewSectionHeader issue={issue} />
- {/* ReviewApprovalFlow renders the "no approval required" note itself when
- the approval is skipped / has no roles, so no guard is needed here. */}
- <ReviewApprovalFlow issue={issue} />
- <ReviewRejectionBanner comments={comments} issue={issue} />
+ {generating ? (
+ generatingFlow
+ ) : (
+ <>
+ <PlanReviewSectionHeader issue={issue} />
+ {/* ReviewApprovalFlow renders the "no approval required" note itself
+ when the approval is skipped / has no roles, so no guard is
+ needed here. */}
+ <ReviewApprovalFlow issue={issue} />
+ <ReviewRejectionBanner comments={comments} issue={issue} />
+ </>
+ )}
+ {reviewState && <AutomatedReviewSection state={reviewState} />}
<ReviewActivityTimeline
comments={comments}
issue={issue}
plan={page.plan}
/>
- <ReviewReadinessFooter issue={issue} plan={page.plan} />
+ {!reviewState && <ReviewReadinessFooter issue={issue} plan={page.plan} />}
</div>
);
}
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
index 7cf3690421..ae0a75219f 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
@@ -6,10 +6,12 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { shownTimestampModes } from "@/test-utils/humanizeTs";
import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
+ IssueComment_ReviewMetadataSchema,
IssueComment_ReviewSubmissionSchema,
IssueComment_ThreadState,
IssueCommentSchema,
IssueSchema,
+ ReviewRun_Type,
StatementAnchorSchema,
} from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -19,7 +21,10 @@ import {
} from "@/types/proto-es/v1/plan_service_pb";
const mocks = vi.hoisted(() => ({
+ activityFocus: undefined as { commentName: string; nonce: number } | undefined,
+ clearActivityFocus: vi.fn(),
requestThreadFocus: vi.fn(),
+ setWalkerFilter: vi.fn(),
expandPhase: vi.fn(),
placements: new Map<string, unknown>(),
placementTargets: new Map<string, string>(),
@@ -39,11 +44,13 @@ vi.mock("@/components/issue-activity/IssueCommentActivity", () => ({
ActivityRowFrame: ({
children,
icon,
+ id,
}: {
children: ReactNode;
icon: ReactNode;
+ id?: string;
}) => (
- <li data-testid="thread-row">
+ <li data-testid="thread-row" id={id}>
{icon}
{children}
</li>
@@ -127,9 +134,14 @@ vi.mock("../../shared/stores/usePlanDetailStore", () => ({
selectedSpecId: "spec-1",
placements: mocks.placements,
placementTargets: mocks.placementTargets,
+ activityFocus: mocks.activityFocus,
+ clearActivityFocus: mocks.clearActivityFocus,
}),
usePlanDetailStoreApi: () => ({
- getState: () => ({ requestThreadFocus: mocks.requestThreadFocus }),
+ getState: () => ({
+ requestThreadFocus: mocks.requestThreadFocus,
+ setWalkerFilter: mocks.setWalkerFilter,
+ }),
}),
}));
@@ -191,6 +203,7 @@ vi.mock("../../shell/PlanDetailContext", () => ({
usePlanDetailContext: () => ({
projectId: "p1",
planId: "1",
+ plan: { specs: [{ id: "spec-1" }] },
expandPhase: mocks.expandPhase,
}),
}));
@@ -222,6 +235,7 @@ const reviewSubmission = (name: string) =>
describe("ReviewActivityTimeline", () => {
afterEach(() => {
vi.clearAllMocks();
+ mocks.activityFocus = undefined;
mocks.placements.clear();
mocks.placementTargets.clear();
});
@@ -288,6 +302,95 @@ describe("ReviewActivityTimeline", () => {
act(() => root.unmount());
});
+ test("a run's line steps through its open findings in the editor", () => {
+ const plan = create(PlanSchema, {
+ name: "projects/p1/plans/1",
+ specs: [create(Plan_SpecSchema, { id: "spec-1" })],
+ });
+ const finding = (
+ id: string,
+ line: number,
+ threadState: IssueComment_ThreadState
+ ) =>
+ create(IssueCommentSchema, {
+ name: `projects/p1/issues/1/issueComments/${id}`,
+ comment: "No WHERE clause",
+ threadState,
+ createTime: timestampFromMs(0),
+ statementAnchor: create(StatementAnchorSchema, {
+ spec: "spec-1",
+ startPosition: create(PositionSchema, { line, column: 0 }),
+ }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ }),
+ });
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <ReviewActivityTimeline
+ comments={[
+ finding("resolved", 1, IssueComment_ThreadState.RESOLVED),
+ finding("open-5", 5, IssueComment_ThreadState.OPEN),
+ finding("open-3", 3, IssueComment_ThreadState.OPEN),
+ ]}
+ issue={create(IssueSchema, { name: "projects/p1/issues/1" })}
+ plan={plan}
+ />
+ );
+ });
+ const show = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "plan.deploy-waiting.show"
+ );
+ act(() => show?.click());
+ expect(mocks.setWalkerFilter).toHaveBeenCalledWith({
+ runType: ReviewRun_Type.RULE,
+ group: "open",
+ });
+ expect(mocks.requestThreadFocus).toHaveBeenCalledWith(
+ expect.objectContaining({
+ commentName: "projects/p1/issues/1/issueComments/open-3",
+ })
+ );
+ act(() => root.unmount());
+ });
+
+ test("unfolds the timeline to reach a card asked for from elsewhere", () => {
+ const name = (i: number) => `projects/p1/issues/1/issueComments/t${i}`;
+ const comments = Array.from({ length: 12 }, (_, i) =>
+ create(IssueCommentSchema, {
+ name: name(i),
+ comment: `thread ${i}`,
+ threadState: IssueComment_ThreadState.OPEN,
+ createTime: timestampFromMs(i * 1000),
+ })
+ );
+ const scrollIntoView = vi.fn();
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = scrollIntoView;
+ mocks.activityFocus = { commentName: name(6), nonce: 4 };
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <ReviewActivityTimeline
+ comments={comments}
+ issue={create(IssueSchema, { name: "projects/p1/issues/1" })}
+ plan={create(PlanSchema, { name: "projects/p1/plans/1" })}
+ />
+ );
+ });
+ const card = document.getElementById(name(6));
+ expect(card).not.toBeNull();
+ expect(scrollIntoView.mock.contexts).toContain(card);
+ expect(mocks.clearActivityFocus).toHaveBeenCalledWith(4);
+ act(() => root.unmount());
+ container.remove();
+ Element.prototype.scrollIntoView = original;
+ });
+
test("hands a thread card the plan spec its anchor names, and none for a spec the plan lacks", () => {
const plan = create(PlanSchema, {
name: "projects/p1/plans/1",
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
index 80e2bd648b..01d10a82c6 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
@@ -8,8 +8,6 @@ import {
useState,
} from "react";
import { useTranslation } from "react-i18next";
-import { router } from "@/app/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";
import { HumanizeTs } from "@/components/HumanizeTs";
import {
ActivityRowFrame,
@@ -39,24 +37,31 @@ import {
import { projectNamePrefix } from "@/stores/modules/v1/common";
import { getTimeForPbTimestampProtoEs } from "@/types";
import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { IssueComment_ThreadState } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+import { useFocusThread } from "../../hooks/useFocusThread";
import { usePlanChangeReferenceData } from "../../hooks/usePlanChangeReferenceData";
import { placementOf } from "../../shared/stores/placementSlice";
import {
usePlanDetailStore,
usePlanDetailStoreApi,
} from "../../shared/stores/usePlanDetailStore";
-import { focusPlanPhase } from "../../shell/focusPhase";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { findingsInOrder } from "../../utils/findingIndex";
import { PlanSpecChangeReference } from "../PlanChangeReference";
import { CommentThreadCard } from "../threads/CommentThreadCard";
+import { ReviewerIcon, reviewerName } from "../threads/ReviewResult";
import { StatementAnchorContext } from "../threads/StatementAnchorContext";
import {
type CommentThread,
groupThreads,
+ isShownInEditor,
+ needsActivityCard,
targetSha256OfSpec,
} from "../threads/threadModel";
+import { usePreviewEndLines } from "../threads/useUnresolvedThreadCounts";
import { consolidateConsecutive } from "./consolidateTimeline";
import { foldTimeline } from "./foldTimeline";
import { ReviewCommentComposer } from "./ReviewCommentComposer";
@@ -107,6 +112,44 @@ export function ReviewActivityTimeline({
setExpanded(false);
}, [page.pageKey]);
+ // A card asked for from elsewhere may sit in the folded middle, so the
+ // timeline unfolds first and scrolls once the card renders.
+ const activityFocus = usePlanDetailStore((s) => s.activityFocus);
+ const clearActivityFocus = usePlanDetailStore((s) => s.clearActivityFocus);
+ useEffect(() => {
+ if (activityFocus) setExpanded(true);
+ }, [activityFocus]);
+
+ // Under SQL Review V2, Activity records each run as one line.
+ const placements = usePlanDetailStore((s) => s.placements);
+ const placementTargets = usePlanDetailStore((s) => s.placementTargets);
+ const previewEndLines = usePreviewEndLines(
+ plan.specs,
+ `${projectNamePrefix}${page.projectId}`
+ );
+ const keepFindingCard = useMemo(() => {
+ if (!sqlReviewV2Enabled()) return undefined;
+ return (root: IssueComment) => {
+ const thread = threads.find((candidate) => candidate.root === root);
+ if (!thread) return true;
+ return needsActivityCard(
+ thread,
+ isShownInEditor(
+ root,
+ plan.specs,
+ (commentName, specId, sheetSha256) =>
+ placementOf(
+ { placements, placementTargets },
+ commentName,
+ specId,
+ sheetSha256
+ ),
+ (specId) => previewEndLines.get(specId)
+ )
+ );
+ };
+ }, [placementTargets, placements, plan.specs, previewEndLines, threads]);
+
const entries = useMemo(
() =>
buildTimelineEntries({
@@ -116,12 +159,14 @@ export function ReviewActivityTimeline({
issueCreateTime: issue.createTime,
issueDraft: issue.draft,
comments,
+ keepFindingCard,
}),
[
comments,
issue.createTime,
issue.creator,
issue.draft,
+ keepFindingCard,
plan.createTime,
plan.creator,
]
@@ -131,6 +176,13 @@ export function ReviewActivityTimeline({
const consolidated = consolidateConsecutive(renderable);
return foldTimeline(consolidated, expanded);
}, [entries, expanded]);
+ useEffect(() => {
+ if (!activityFocus || !expanded) return;
+ document
+ .getElementById(activityFocus.commentName)
+ ?.scrollIntoView({ behavior: "smooth", block: "center" });
+ clearActivityFocus(activityFocus.nonce);
+ }, [activityFocus, clearActivityFocus, expanded, items]);
// Permission-gated only — comments are allowed regardless of issue status
// (the backend and the issue-detail list allow commenting on done issues).
const allowComment = Boolean(
@@ -243,6 +295,9 @@ function ActivityRow({
threads: CommentThread[];
}) {
const source = entry.source;
+ if (source.type === "review-run") {
+ return <ReviewRunActivityRow isLast={isLast} plan={plan} source={source} />;
+ }
if (source.type === "comment" && isThreadRoot(source.comment)) {
const thread = threads.find(
(candidate) => candidate.root.name === source.comment.name
@@ -282,6 +337,82 @@ function ActivityRow({
);
}
+// One line per run in place of a card per finding, which the editor shows:
+// how many findings it posted and how many are still open. "Show" steps
+// through the open ones in the editor.
+function ReviewRunActivityRow({
+ isLast,
+ plan,
+ source,
+}: {
+ isLast: boolean;
+ plan: Plan;
+ source: Extract<TimelineSource, { type: "review-run" }>;
+}) {
+ const { t } = useTranslation();
+ const storeApi = usePlanDetailStoreApi();
+ const { focusInStatement } = useFocusThread();
+ const open = source.findings.filter(
+ (finding) => finding.threadState === IssueComment_ThreadState.OPEN
+ ).length;
+ const showOpen = () => {
+ const first = findingsInOrder(
+ source.findings,
+ source.runType,
+ plan.specs,
+ "open"
+ )[0];
+ if (!first) return;
+ storeApi
+ .getState()
+ .setWalkerFilter({ runType: source.runType, group: "open" });
+ focusInStatement(first);
+ };
+ return (
+ <ActivityRowShell
+ header={
+ <>
+ <span className="font-medium text-main">
+ {reviewerName(t, source.runType)}
+ </span>
+ <span className="wrap-break-word min-w-0 text-control-light">
+ {t("plan.review.activity.reviewed-the-sql")}
+ </span>
+ <span className="text-control-light">·</span>
+ <span className="text-control">
+ {t("plan.review.activity.n-findings", {
+ count: source.findings.length,
+ })}
+ {open > 0 &&
+ `, ${t("plan.automated-review.n-open", { count: open })}`}
+ </span>
+ <HumanizeTs
+ className="text-xs text-control-light"
+ tsMs={getTimeForPbTimestampProtoEs(source.time)}
+ />
+ {open > 0 && (
+ <Button
+ appearance="link"
+ className="text-control-light"
+ onClick={showOpen}
+ size="xs"
+ >
+ {t("plan.deploy-waiting.show")}
+ </Button>
+ )}
+ </>
+ }
+ icon={
+ <CommentIconBadge
+ className="bg-control-bg text-control"
+ icon={<ReviewerIcon className="size-4" runType={source.runType} />}
+ />
+ }
+ isLast={isLast}
+ />
+ );
+}
+
function SyntheticIcon({
type,
}: {
@@ -492,8 +623,7 @@ function ThreadActivityRow({
}) {
const page = usePlanDetailContext();
const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);
- const storeApi = usePlanDetailStoreApi();
- const selectedSpecId = usePlanDetailStore((s) => s.selectedSpecId);
+ const { focusInStatement } = useFocusThread();
const anchor = thread.root.statementAnchor;
const spec = useMemo(
() => plan.specs.find((candidate) => candidate.id === anchor?.spec),
@@ -506,31 +636,11 @@ function ThreadActivityRow({
: undefined
);
- // Open the Changes phase on the anchored spec; the statement editor picks
- // up the focus request once it shows that spec.
- const viewInStatement = () => {
- const specId = anchor?.spec;
- if (!specId) return;
- const lineNumber =
- placement?.state === "CURRENT"
- ? placement.range.startLine
- : anchor?.startPosition?.line;
- storeApi.getState().requestThreadFocus({
- commentName: thread.root.name,
- specId,
- lineNumber,
- });
- focusPlanPhase("changes", page.expandPhase);
- if (selectedSpecId !== specId) {
- void router.push(
- {
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- params: { planId: page.planId, projectId: page.projectId, specId },
- },
- { preventScrollReset: true }
- );
- }
- };
+ const viewInStatement = () =>
+ focusInStatement(
+ thread.root,
+ placement?.state === "CURRENT" ? placement.range.startLine : undefined
+ );
return (
<ActivityRowFrame
diff --git a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.test.ts b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.test.ts
index aa07542d48..628dae0fd6 100644
--- a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.test.ts
@@ -4,8 +4,11 @@ import { TimestampSchema } from "@bufbuild/protobuf/wkt";
import { describe, expect, test } from "vitest";
import {
IssueComment_Approval_Status,
+ IssueComment_ReviewMetadataSchema,
IssueComment_ReviewSubmissionSchema,
+ IssueComment_ThreadState,
IssueCommentSchema,
+ ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
import { buildTimelineEntries } from "./timelineEvents";
@@ -99,4 +102,51 @@ describe("buildTimelineEntries", () => {
expect(entries.map((entry) => entry.id)).toEqual(["c-submit"]);
});
+
+ test("folds each run's findings into one line and keeps only the cards asked for", () => {
+ const finding = (
+ name: string,
+ runType: ReviewRun_Type,
+ seconds: bigint,
+ nanos = 0
+ ) =>
+ create(IssueCommentSchema, {
+ name,
+ threadState: IssueComment_ThreadState.OPEN,
+ createTime: create(TimestampSchema, { seconds, nanos }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, { runType }),
+ });
+ const entries = buildTimelineEntries({
+ comments: [
+ finding("r1", ReviewRun_Type.RULE, 10n, 0),
+ finding("r2", ReviewRun_Type.RULE, 10n, 1000),
+ userComment("u", "hello"),
+ finding("r3", ReviewRun_Type.RULE, 60n),
+ finding("a1", ReviewRun_Type.AI, 61n),
+ ],
+ keepFindingCard: (root) => root.name === "r2",
+ });
+ expect(
+ entries.map((entry) =>
+ entry.source.type === "review-run"
+ ? `run:${entry.source.findings.map((f) => f.name).join("+")}`
+ : entry.id
+ )
+ ).toEqual(["run:r1+r2", "r2", "u", "run:r3", "run:a1"]);
+ });
+
+ test("without the log, every finding stays its own entry", () => {
+ const entries = buildTimelineEntries({
+ comments: [
+ create(IssueCommentSchema, {
+ name: "r1",
+ threadState: IssueComment_ThreadState.OPEN,
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ }),
+ }),
+ ],
+ });
+ expect(entries.map((entry) => entry.source.type)).toEqual(["comment"]);
+ });
});
diff --git a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts
index 21b6279fd0..6e89a44637 100644
--- a/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts
+++ b/frontend/src/routes/project/plan-detail/components/review/timelineEvents.ts
@@ -3,13 +3,27 @@
// card or a one-line system row is decided at render time by body presence,
// so no weight/tier is stored here. Plan check results are never entries.
import type { Timestamp } from "@bufbuild/protobuf/wkt";
-import { isThreadReply } from "@/stores/app/issueComment";
-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { isThreadReply, isThreadRoot } from "@/stores/app/issueComment";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import type {
+ IssueComment,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
export type TimelineSource =
| { type: "plan-created"; creator: string; time?: Timestamp }
| { type: "ready-for-review"; creator: string; time?: Timestamp }
- | { type: "comment"; comment: IssueComment };
+ | { type: "comment"; comment: IssueComment }
+ // One line for a reviewer's run, standing in for the findings it posted.
+ | {
+ type: "review-run";
+ runType: ReviewRun_Type;
+ time?: Timestamp;
+ findings: IssueComment[];
+ };
+
+// A run posts its findings in one batch, a microsecond apart.
+const RUN_BATCH_GAP_MS = 1000;
export interface TimelineEntry {
id: string;
@@ -27,6 +41,9 @@ export function buildTimelineEntries(input: {
issueCreateTime?: Timestamp;
issueDraft?: boolean;
comments: IssueComment[];
+ // Under SQL Review V2, findings become one line per run; a finding keeps
+ // its own card only where this says so.
+ keepFindingCard?: (root: IssueComment) => boolean;
}): TimelineEntry[] {
const reviewSubmission = input.comments.find(
(comment) => comment.event.case === "reviewSubmission"
@@ -52,6 +69,13 @@ export function buildTimelineEntries(input: {
},
});
}
+ const runs = new Map<
+ ReviewRun_Type,
+ {
+ at: number;
+ source: Extract<TimelineSource, { type: "review-run" }>;
+ }
+ >();
for (const comment of input.comments) {
// Replies render inside their thread's entry, never as their own row.
if (isThreadReply(comment)) continue;
@@ -68,6 +92,25 @@ export function buildTimelineEntries(input: {
}
continue;
}
+ const review = comment.reviewMetadata;
+ if (input.keepFindingCard && review && isThreadRoot(comment)) {
+ const time = getTimeForPbTimestampProtoEs(comment.createTime, 0);
+ const last = runs.get(review.runType);
+ if (last && time - last.at <= RUN_BATCH_GAP_MS) {
+ last.source.findings.push(comment);
+ last.at = time;
+ } else {
+ const source = {
+ type: "review-run" as const,
+ runType: review.runType,
+ time: comment.createTime,
+ findings: [comment],
+ };
+ runs.set(review.runType, { at: time, source });
+ entries.push({ id: `review-run:${comment.name}`, source });
+ }
+ if (!input.keepFindingCard(comment)) continue;
+ }
entries.push({ id: comment.name, source: { type: "comment", comment } });
}
return entries;
diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx
index 9334eb9475..7fb14b3b66 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.test.tsx
@@ -16,12 +16,17 @@ import {
import type { Project } from "@/types/proto-es/v1/project_service_pb";
const mocks = vi.hoisted(() => ({
+ sqlReviewV2: false,
createIssueComment: vi.fn(),
notify: vi.fn(),
updateIssueComment: vi.fn(),
hasPermission: vi.fn((_project: unknown, _permission: unknown) => true),
}));
+vi.mock("@/utils/featureGates", () => ({
+ sqlReviewV2Enabled: () => mocks.sqlReviewV2,
+}));
+
vi.mock("react-i18next", () => ({
initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({
@@ -154,6 +159,7 @@ let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
+ mocks.sqlReviewV2 = false;
HTMLElement.prototype.scrollIntoView = vi.fn();
vi.clearAllMocks();
mocks.hasPermission.mockReturnValue(true);
@@ -218,6 +224,13 @@ describe("CommentThreadCard", () => {
expect(mocks.createIssueComment).toHaveBeenCalledExactlyOnceWith({ issueName: ISSUE, comment: "New reply", root: rootName });
});
+ test("under SQL Review V2 a draft takes replies", () => {
+ mocks.sqlReviewV2 = true;
+ const [thread] = groupThreads([comment("root", "Root question")]);
+ render(<CommentThreadCard project={project} thread={thread} issue={create(IssueSchema, { ...issue, draft: true })} />);
+ expect(buttonByText("plan.review.thread.reply-placeholder")).toBeDefined();
+ });
+
test("places statement context above the root author as a separate full-width region", () => {
const [thread] = groupThreads([comment("root", "Root question")]);
render(
diff --git a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx
index ae73174dcc..d6a5f30c55 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/CommentThreadCard.tsx
@@ -2,7 +2,6 @@ import {
Check,
ChevronDown,
ChevronUp,
- CircleCheck,
Loader2,
RotateCcw,
} from "lucide-react";
@@ -22,7 +21,6 @@ import { HumanizeTs } from "@/components/HumanizeTs";
import { MarkdownEditor } from "@/components/MarkdownEditor";
import { MonacoViewZoneRevealContext } from "@/components/monaco/MonacoViewZone";
import { UserAvatar } from "@/components/UserAvatar";
-import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { useCurrentUser } from "@/hooks/useAppState";
@@ -34,6 +32,7 @@ import type { Project } from "@/types/proto-es/v1/project_service_pb";
import "./CommentThreadCard.css";
import { ReviewPriorityBadge, useCommentAuthor } from "./ReviewResult";
import { ThreadComment } from "./ThreadComment";
+import { ThreadStateBadge } from "./ThreadStateBadge";
import type { CommentThread } from "./threadModel";
import {
canReplyToThread,
@@ -257,12 +256,7 @@ export function CommentThreadCard({
status={
<>
{label}
- {thread.resolved && (
- <Badge className="gap-x-1 px-2 text-xs" variant="success">
- <CircleCheck className="size-3" />
- {t("plan.review.thread.resolved")}
- </Badge>
- )}
+ <ThreadStateBadge resolved={thread.resolved} />
</>
}
/>
@@ -437,10 +431,7 @@ function ThreadSummary({
className="hidden shrink-0 text-xs text-control-light sm:inline"
tsMs={getTimeForPbTimestampProtoEs(thread.root.createTime)}
/>
- <Badge className="shrink-0 gap-x-1 px-2 text-xs" variant="success">
- <CircleCheck className="size-3" />
- {t("plan.review.thread.resolved")}
- </Badge>
+ <ThreadStateBadge resolved />
<ChevronDown className="size-4 shrink-0 text-control-light" />
</Button>
);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
index 4f41845cb0..cec53cde3c 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ReviewResult.tsx
@@ -97,7 +97,7 @@ export function ReviewPriorityBadge({
);
}
-function priorityStyle(
+export function priorityStyle(
t: TFunction,
priority: IssueComment_ReviewMetadata_Priority
): { description: string; variant: BadgeProps["variant"] } | undefined {
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
index c2b0d8ccb3..089410eb58 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
@@ -1,4 +1,4 @@
-import { ChevronDown, ChevronUp, MessagesSquare } from "lucide-react";
+import { ChevronDown, ChevronUp, MessagesSquare, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
@@ -9,12 +9,15 @@ import { Tooltip } from "@/components/ui/tooltip";
const ARROW_CLASS =
"rounded-none border-l border-control-border text-control-light hover:text-control focus-visible:ring-inset focus-visible:ring-offset-0 pointer-coarse:focus-visible:ring-0";
-// Steps through the unresolved threads placed on the displayed statement.
-// `count` is what the arrows can visit; `remainder` is how many unresolved
-// threads of this change are not placed on this version.
+// Steps through the unresolved threads placed on the displayed statement, or
+// with a filter, through one reviewer's findings in one state across the
+// plan. `count` is what the arrows can visit; `remainder` is how many of this
+// change's matching threads are not placed on this version.
export function StatementThreadWalker({
announcement,
count,
+ filterLabel,
+ onClearFilter,
position,
onNext,
onPrevious,
@@ -22,6 +25,8 @@ export function StatementThreadWalker({
}: {
announcement: string;
count: number;
+ filterLabel?: string;
+ onClearFilter?: () => void;
position: number;
onNext: () => void;
onPrevious: () => void;
@@ -52,6 +57,7 @@ export function StatementThreadWalker({
}
>
<MessagesSquare className="size-3.5" />
+ {filterLabel && <span className="text-control">{filterLabel}</span>}
{position}/{count}
</Tooltip>
<Button
@@ -72,6 +78,17 @@ export function StatementThreadWalker({
>
<ChevronDown className="size-4" />
</Button>
+ {filterLabel && onClearFilter && (
+ <Button
+ appearance="secondary"
+ aria-label={t("plan.review.thread.walker.clear-filter")}
+ className={ARROW_CLASS}
+ onClick={onClearFilter}
+ size="sm"
+ >
+ <X className="size-4" />
+ </Button>
+ )}
<span aria-live="polite" className="sr-only">
{announcement}
</span>
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
index 1a6a1eb765..7e2b289f7f 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
@@ -11,9 +11,12 @@ import type {
import { fakeEditorLayout, lineTop } from "@/test-utils/monacoLayout";
import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
+ IssueComment_ReviewMetadata_Priority,
+ IssueComment_ReviewMetadataSchema,
IssueComment_ThreadState,
IssueCommentSchema,
IssueSchema,
+ ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
import {
Plan_ChangeDatabaseConfigSchema,
@@ -32,6 +35,11 @@ const mocks = vi.hoisted(() => ({
| { commentName: string; specId: string; nonce: number }
| undefined,
clearThreadFocus: vi.fn(),
+ focusInStatement: vi.fn(),
+ focusInActivity: vi.fn(),
+ sqlReviewV2: false,
+ walkerFilter: undefined as { runType: number; group: string } | undefined,
+ setWalkerFilter: vi.fn(),
placements: new Map<string, unknown>(),
placementTargets: new Map<string, string>(),
hasPermission: vi.fn((_project: unknown, _permission: unknown) => true),
@@ -84,11 +92,24 @@ vi.mock("../../shared/stores/usePlanDetailStore", () => ({
selector({
threadFocus: mocks.threadFocus,
clearThreadFocus: mocks.clearThreadFocus,
+ walkerFilter: mocks.walkerFilter,
+ setWalkerFilter: mocks.setWalkerFilter,
placements: mocks.placements,
placementTargets: mocks.placementTargets,
}),
}));
+vi.mock("../../hooks/useFocusThread", () => ({
+ useFocusThread: () => ({
+ focusInActivity: mocks.focusInActivity,
+ focusInStatement: mocks.focusInStatement,
+ }),
+}));
+
+vi.mock("@/utils/featureGates", () => ({
+ sqlReviewV2Enabled: () => mocks.sqlReviewV2,
+}));
+
vi.mock("../../shell/PlanDetailContext", () => ({
usePlanDetailContext: () => ({
projectId: "p",
@@ -404,6 +425,8 @@ beforeEach(() => {
mocks.findController = null;
vi.clearAllMocks();
mocks.threadFocus = undefined;
+ mocks.sqlReviewV2 = false;
+ mocks.walkerFilter = undefined;
mocks.placements = new Map();
mocks.placementTargets = new Map();
mocks.hasPermission.mockReturnValue(true);
@@ -540,13 +563,13 @@ describe("StatementThreadsLayer", () => {
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/first`);
});
- test("distinguishes the current range from non-stacking passive ranges", () => {
+ test("distinguishes the current range from passive ranges and leaves resolved lines untinted", () => {
mocks.comments = [threadRoot("single", 2, 2), threadRoot("multi", 1, 2, { createdAt: 2, resolved: true })];
const fake = createFakeEditor();
mount(fake.editor);
const highlighted = () => fake.decorations.current.filter((d) => d.options.className === "bb-thread-line").map((d) => d.range.startLineNumber);
expect(highlighted()).toEqual([2]);
- expect(classesOf(fake.decorations.current, 1)).toContain("bb-thread-line--passive");
+ expect(classesOf(fake.decorations.current, 1)).not.toContain("bb-thread-line--passive");
expect(fake.decorations.current.filter((d) => d.options.isWholeLine && d.range.startLineNumber === 2)).toHaveLength(1);
fake.fire("move", 1, MouseTargetType.GUTTER_LINE_NUMBERS);
expect(highlighted()).toEqual([2]);
@@ -557,10 +580,74 @@ describe("StatementThreadsLayer", () => {
expect(highlighted()).toEqual([2]);
act(() => picker?.querySelector("[data-testid='close-thread']")?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
expect(highlighted()).toEqual([]);
- expect(fake.decorations.current.filter((d) => d.options.className === "bb-thread-line--passive").map((d) => d.range.startLineNumber)).toEqual([1, 2]);
+ expect(fake.decorations.current.filter((d) => d.options.className === "bb-thread-line--passive").map((d) => d.range.startLineNumber)).toEqual([2]);
expect(fake.decorations.current.filter((d) => d.options.glyphMarginClassName?.includes("bb-thread-glyph--count-2"))).toHaveLength(1);
});
+ test("open findings tint their lines by priority", () => {
+ const finding = (id: string, line: number, priority: IssueComment_ReviewMetadata_Priority) =>
+ create(IssueCommentSchema, {
+ ...threadRoot(id, line, line),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ priority,
+ }),
+ });
+ mocks.comments = [
+ threadRoot("discussion", 2, 2),
+ finding("p0", 4, IssueComment_ReviewMetadata_Priority.P0),
+ finding("p1", 6, IssueComment_ReviewMetadata_Priority.P1),
+ ];
+ const fake = createFakeEditor();
+ mount(fake.editor);
+ expect(lines(fake.decorations.current, "bb-thread-line")).toEqual([2]);
+ expect(lines(fake.decorations.current, "bb-thread-line--blocking")).toEqual([4]);
+ expect(lines(fake.decorations.current, "bb-thread-line--attention")).toEqual([6]);
+ });
+
+ test("a filtered walker steps through one reviewer's findings across changes", () => {
+ const finding = (id: string, line: number, spec = "spec-1") =>
+ create(IssueCommentSchema, {
+ ...threadRoot(id, line, line),
+ statementAnchor: create(StatementAnchorSchema, {
+ spec,
+ sheetSha256: SHA,
+ startPosition: create(PositionSchema, { line, column: 0 }),
+ endPosition: create(PositionSchema, { line, column: 0 }),
+ }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ priority: IssueComment_ReviewMetadata_Priority.P1,
+ }),
+ });
+ mocks.comments = [threadRoot("discussion", 1, 1), finding("first", 3), finding("other-spec", 2, "spec-2")];
+ mocks.walkerFilter = { runType: ReviewRun_Type.RULE, group: "p1" };
+ const fake = createFakeEditor();
+ mount(fake.editor);
+ const walker = () => hosted(fake.widgets, "[data-testid='thread-walker']");
+ expect(walker()?.textContent).toContain("plan.review.thread.walker.filter");
+ expect(walker()?.textContent).toContain("/2");
+ const next = () =>
+ act(() =>
+ walker()
+ ?.querySelector("[aria-label='plan.review.thread.walker.next']")
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }))
+ );
+ next();
+ expect(cardRoots(fake.widgets)).toContain(`${ISSUE}/issueComments/first`);
+ expect(walker()?.textContent).toContain("1/2");
+ next();
+ expect(mocks.focusInStatement).toHaveBeenCalledWith(
+ expect.objectContaining({ name: `${ISSUE}/issueComments/other-spec` })
+ );
+ act(() =>
+ walker()
+ ?.querySelector("[aria-label='plan.review.thread.walker.clear-filter']")
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }))
+ );
+ expect(mocks.setWalkerFilter).toHaveBeenCalledWith(undefined);
+ });
+
test("a pending selection replaces the reading highlight; an open composer keeps both", () => {
mocks.comments = [threadRoot("single", 2, 2)];
const fake = createFakeEditor(1);
@@ -861,6 +948,16 @@ describe("StatementThreadsLayer", () => {
).not.toHaveBeenCalled();
});
+ test("under SQL Review V2 a draft takes new threads", () => {
+ mocks.sqlReviewV2 = true;
+ mocks.comments = [];
+ const fake = createFakeEditor();
+ mount(fake.editor, create(IssueSchema, { name: ISSUE, draft: true }));
+ expect(fake.editor.addAction).toHaveBeenCalled();
+ fake.fire("move", 2, MouseTargetType.CONTENT_TEXT);
+ expect(classesOf(fake.decorations.current, 2)).toContain("bb-thread-add-glyph");
+ });
+
test("draft issues show existing threads but enable creation only after submission", () => {
mocks.comments = [threadRoot("existing", 3, 4)];
const fake = createFakeEditor();
@@ -956,6 +1053,21 @@ describe("StatementThreadsLayer", () => {
expect(fake.setScrollTop).toHaveBeenCalledExactlyOnceWith(lineTop(10) + 1 - 8);
expect(mocks.clearThreadFocus).toHaveBeenCalledWith(7);
});
+ test("a focus request for a thread past the loaded preview opens its Activity card", () => {
+ mocks.comments = [threadRoot("near", 3, 4), threadRoot("far", 30, 31)];
+ mocks.threadFocus = {
+ commentName: `${ISSUE}/issueComments/far`,
+ specId: "spec-1",
+ nonce: 9,
+ };
+ const fake = createFakeEditor();
+ mount(fake.editor, issue, 20);
+ expect(mocks.focusInActivity).toHaveBeenCalledWith(
+ expect.objectContaining({ name: `${ISSUE}/issueComments/far` })
+ );
+ expect(mocks.clearThreadFocus).toHaveBeenCalledWith(9);
+ });
+
test("the walker steps through unresolved threads in editor order and wraps", () => {
mocks.comments = [
threadRoot("a", 2, 2, { createdAt: 1 }),
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
index 58672693f0..a1064269ed 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
@@ -18,17 +18,25 @@ import { useMonacoFindWidgetVisible } from "@/components/monaco/useMonacoFindWid
import { useProjectByName } from "@/hooks/useProjectByName";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ type Issue,
+ IssueComment_ReviewMetadata_Priority,
+} from "@/types/proto-es/v1/issue_service_pb";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { useFocusThread } from "../../hooks/useFocusThread";
import { placementsForSheet } from "../../shared/stores/placementSlice";
import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { inFindingGroup } from "../../utils/planGates";
+import { findingGroupLabel } from "../../utils/reviewLabels";
import { InlineThreadComposer } from "./InlineThreadComposer";
+import { reviewerName } from "./ReviewResult";
import "./statementThreads.css";
import { StatementThreadWalker } from "./StatementThreadWalker";
import { ThreadStack } from "./ThreadStack";
import {
buildWholeLineAnchor,
+ type CommentThread,
defaultExpandedThread,
type EditorThread,
groupMarkersByLine,
@@ -48,6 +56,12 @@ const firstToExpand = (threads: EditorThread[] | undefined): string[] => {
return entry ? [entry.thread.root.name] : [];
};
+const LINE_CLASS_BY_WEIGHT = [
+ "bb-thread-line--passive",
+ "bb-thread-line--attention",
+ "bb-thread-line--blocking",
+] as const;
+
// An unpublished comment form, keyed by the last line of its range so one
// line carries at most one form. Drafts live in their own record so typing
// leaves the decorations and listeners keyed on this map alone.
@@ -100,6 +114,19 @@ export function StatementThreadsLayer({
previewEndLine === undefined && canReplyToThread(project, issue);
const threads = useMemo(() => groupThreads(comments), [comments]);
+ // A click on a finding count narrows the walker to one group of that
+ // reviewer's findings, across every change of the plan.
+ const walkerFilter = usePlanDetailStore((s) => s.walkerFilter);
+ const setWalkerFilter = usePlanDetailStore((s) => s.setWalkerFilter);
+ const { focusInActivity, focusInStatement } = useFocusThread();
+ const matchesWalker = useCallback(
+ (thread: CommentThread) =>
+ walkerFilter
+ ? thread.root.reviewMetadata?.runType === walkerFilter.runType &&
+ inFindingGroup(thread.root, walkerFilter.group)
+ : !thread.resolved,
+ [walkerFilter]
+ );
const editorThreads = useMemo(
() =>
selectEditorThreads(
@@ -112,30 +139,60 @@ export function StatementThreadsLayer({
// What the walker can visit, in editor order, and how many unresolved
// threads of this change it cannot because they are not placed here.
const visitableThreads = useMemo(
- () => editorThreads.filter(({ thread }) => !thread.resolved),
- [editorThreads]
+ () => editorThreads.filter(({ thread }) => matchesWalker(thread)),
+ [editorThreads, matchesWalker]
);
const unplacedUnresolved = useMemo(
() =>
threads.filter(
(thread) =>
- !thread.resolved && thread.root.statementAnchor?.spec === spec.id
+ matchesWalker(thread) && thread.root.statementAnchor?.spec === spec.id
).length - visitableThreads.length,
- [spec.id, threads, visitableThreads.length]
+ [matchesWalker, spec.id, threads, visitableThreads.length]
);
+ // A filtered walk spans the plan: the matching anchored threads in change
+ // and line order.
+ const specOrder = page.plan.specs;
+ const planMatches = useMemo(() => {
+ if (!walkerFilter) return undefined;
+ const specIndex = (id: string | undefined) => {
+ const index = specOrder.findIndex((candidate) => candidate.id === id);
+ return index === -1 ? Number.MAX_SAFE_INTEGER : index;
+ };
+ return threads
+ .filter((thread) => thread.root.statementAnchor && matchesWalker(thread))
+ .sort(
+ (a, b) =>
+ specIndex(a.root.statementAnchor?.spec) -
+ specIndex(b.root.statementAnchor?.spec) ||
+ (a.root.statementAnchor?.startPosition?.line ?? 0) -
+ (b.root.statementAnchor?.startPosition?.line ?? 0)
+ );
+ }, [matchesWalker, specOrder, threads, walkerFilter]);
const markersByLine = useMemo(
() => groupMarkersByLine(editorThreads),
[editorThreads]
);
- // A union of commented lines, so overlapping threads never darken a line.
+ // One background per commented line, so overlapping threads never darken
+ // it. Open findings tint by priority, open discussions stay neutral, and
+ // resolved threads leave the line untinted.
const commentedLines = useMemo(() => {
- const lines = new Set<number>();
- for (const { range } of editorThreads) {
+ const rank = new Map<number, number>();
+ for (const { range, thread } of editorThreads) {
+ if (thread.resolved) continue;
+ const priority = thread.root.reviewMetadata?.priority;
+ const weight = !thread.root.reviewMetadata
+ ? 0
+ : priority === IssueComment_ReviewMetadata_Priority.P0
+ ? 2
+ : 1;
for (let line = range.startLine; line <= range.endLine; line++)
- lines.add(line);
+ rank.set(line, Math.max(rank.get(line) ?? 0, weight));
}
- return [...lines].sort((a, b) => a - b);
+ return [...rank]
+ .sort(([a], [b]) => a - b)
+ .map(([line, weight]) => [line, LINE_CLASS_BY_WEIGHT[weight]] as const);
}, [editorThreads]);
// Open lines and expanded roots are independent: opening another thread
@@ -175,14 +232,14 @@ export function StatementThreadsLayer({
const entry = markersByLine
.get(line)
?.find((candidate) => candidate.thread.root.name === rootName);
- if (entry && !entry.thread.resolved) setSelectedRoot(rootName);
+ if (entry && matchesWalker(entry.thread)) setSelectedRoot(rootName);
setRevealRequest((previous) => ({
line,
rootName,
nonce: (previous?.nonce ?? 0) + 1,
}));
},
- [markersByLine]
+ [markersByLine, matchesWalker]
);
const collapseThread = useCallback((rootName: string) => {
setExpandedRoots((previous) => {
@@ -280,6 +337,10 @@ export function StatementThreadsLayer({
[expandedRoots, selectedRoot, visitableThreads]
);
const walk = (step: 1 | -1) => {
+ if (planMatches) {
+ walkPlan(step);
+ return;
+ }
const count = visitableThreads.length;
if (!count) return;
const from =
@@ -297,6 +358,50 @@ export function StatementThreadsLayer({
);
};
+ // Steps through the plan's matching threads, handing a thread on another
+ // change to that change's editor. Threads this version cannot place are
+ // skipped.
+ const walkPlan = (step: 1 | -1) => {
+ const matches = planMatches ?? [];
+ const count = matches.length;
+ if (!count) return;
+ const currentName =
+ visitableThreads[currentVisitableIndex]?.thread.root.name;
+ let index = matches.findIndex((thread) => thread.root.name === currentName);
+ for (let tries = 0; tries < count; tries++) {
+ index =
+ index === -1
+ ? step > 0
+ ? 0
+ : count - 1
+ : (index + step + count) % count;
+ const target = matches[index];
+ if (target.root.statementAnchor?.spec !== spec.id) {
+ focusInStatement(target.root);
+ return;
+ }
+ const placed = visitableThreads.find(
+ (entry) => entry.thread.root.name === target.root.name
+ );
+ if (!placed) continue;
+ expandThread(placed.range.endLine, placed.thread.root.name);
+ setSelection(undefined);
+ setFlashRoot(placed.thread.root.name);
+ editor.getDomNode()?.scrollIntoView({ block: "nearest" });
+ setWalkerAnnouncement(
+ t("plan.review.thread.walker.position", { index: index + 1, count })
+ );
+ return;
+ }
+ };
+ const planPosition = planMatches
+ ? planMatches.findIndex(
+ (thread) =>
+ thread.root.name ===
+ visitableThreads[currentVisitableIndex]?.thread.root.name
+ ) + 1
+ : undefined;
+
// The line that carries the comment action: the end of the selection, or
// the hovered line when nothing is selected.
const actionLine = canCreate
@@ -312,9 +417,16 @@ export function StatementThreadsLayer({
(entry) => entry.thread.root.name === threadFocus.commentName
);
if (!target) {
- // Anchors are current only for the saved version; a thread that is not
- // placed here has nothing to reveal.
- if (comments.length > 0) clearThreadFocus(threadFocus.nonce);
+ // Anchors are current only for the saved version, and an oversized
+ // statement loads only its head: a thread this editor cannot show is
+ // read in its Activity card.
+ if (comments.length > 0) {
+ const root = threads.find(
+ (thread) => thread.root.name === threadFocus.commentName
+ )?.root;
+ if (root) focusInActivity(root);
+ clearThreadFocus(threadFocus.nonce);
+ }
return;
}
expandThread(target.range.endLine, target.thread.root.name);
@@ -328,8 +440,10 @@ export function StatementThreadsLayer({
editor,
editorThreads,
expandThread,
+ focusInActivity,
spec.id,
threadFocus,
+ threads,
]);
// Track the editor's selection as a line range (empty = none).
@@ -355,9 +469,7 @@ export function StatementThreadsLayer({
monacoModule.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges;
// Exactly one background per line: passive, current, or creation.
// Higher-priority states replace the base instead of layering over it.
- const lineClasses = new Map<number, string>(
- commentedLines.map((line) => [line, "bb-thread-line--passive"])
- );
+ const lineClasses = new Map<number, string>(commentedLines);
// A pending selection replaces the reading highlight; open composers
// keep theirs beside it, and win where they overlap.
const pendingSelection = canCreate ? selection : undefined;
@@ -669,18 +781,28 @@ export function StatementThreadsLayer({
return (
<>
- {visitableThreads.length > 0 && !findWidgetVisible && (
- <MonacoOverlayWidget editor={editor}>
- <StatementThreadWalker
- announcement={walkerAnnouncement}
- count={visitableThreads.length}
- position={currentVisitableIndex + 1}
- onNext={() => walk(1)}
- onPrevious={() => walk(-1)}
- remainder={unplacedUnresolved}
- />
- </MonacoOverlayWidget>
- )}
+ {(planMatches ? planMatches.length : visitableThreads.length) > 0 &&
+ !findWidgetVisible && (
+ <MonacoOverlayWidget editor={editor}>
+ <StatementThreadWalker
+ announcement={walkerAnnouncement}
+ count={planMatches?.length ?? visitableThreads.length}
+ filterLabel={
+ walkerFilter
+ ? t("plan.review.thread.walker.filter", {
+ reviewer: reviewerName(t, walkerFilter.runType),
+ state: findingGroupLabel(t, walkerFilter.group),
+ })
+ : undefined
+ }
+ onClearFilter={() => setWalkerFilter(undefined)}
+ position={planPosition ?? currentVisitableIndex + 1}
+ onNext={() => walk(1)}
+ onPrevious={() => walk(-1)}
+ remainder={unplacedUnresolved}
+ />
+ </MonacoOverlayWidget>
+ )}
{[...openLines]
.sort((a, b) => a - b)
.map((line) => {
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx
index 5aceda04ca..1d0cb21c07 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStack.tsx
@@ -1,8 +1,7 @@
-import { ChevronDown, CircleCheck, MessageSquare } from "lucide-react";
+import { ChevronDown, MessageSquare } from "lucide-react";
import { type ReactNode, type Ref, type SetStateAction, useState } from "react";
import { useTranslation } from "react-i18next";
import { HumanizeTs } from "@/components/HumanizeTs";
-import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getTimeForPbTimestampProtoEs } from "@/types";
@@ -11,6 +10,7 @@ import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { CommentThreadCard } from "./CommentThreadCard";
import { ReviewPriorityBadge, useCommentAuthor } from "./ReviewResult";
+import { ThreadStateBadge } from "./ThreadStateBadge";
import {
compareByCreateTime,
type EditorThread,
@@ -213,12 +213,7 @@ function CollapsedThreadRow({
className="hidden shrink-0 text-xs text-control-light @xl:inline"
tsMs={getTimeForPbTimestampProtoEs(comment.createTime)}
/>
- {resolved && (
- <Badge className="shrink-0 gap-x-1 px-2 text-xs" variant="success">
- <CircleCheck className="size-3" />
- {t("plan.review.thread.resolved")}
- </Badge>
- )}
+ {resolved && <ThreadStateBadge resolved />}
<ChevronDown className="size-4 shrink-0 text-control-light" />
</Button>
);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/ThreadStateBadge.tsx b/frontend/src/routes/project/plan-detail/components/threads/ThreadStateBadge.tsx
new file mode 100644
index 0000000000..9fd640ea30
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/threads/ThreadStateBadge.tsx
@@ -0,0 +1,25 @@
+import { CircleCheck } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Badge } from "@/components/ui/badge";
+
+// An open thread needs someone, so it carries the colored badge; a resolved
+// one is quiet gray text.
+export function ThreadStateBadge({ resolved }: { resolved: boolean }) {
+ const { t } = useTranslation();
+ if (resolved) {
+ return (
+ <span
+ className="inline-flex shrink-0 items-center gap-x-1 text-xs text-control-light"
+ data-testid="thread-state"
+ >
+ <CircleCheck className="size-3" />
+ {t("plan.review.thread.resolved")}
+ </span>
+ );
+ }
+ return (
+ <Badge className="shrink-0" data-testid="thread-state" variant="attention">
+ {t("plan.review.thread.open")}
+ </Badge>
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css
index cd5fcce607..25525416ec 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css
+++ b/frontend/src/routes/project/plan-detail/components/threads/statementThreads.css
@@ -6,6 +6,15 @@
background: rgb(var(--color-control-bg) / 0.65);
}
+/* Open findings: P0 says the SQL is wrong, the rest need a person's call. */
+.monaco-editor .bb-thread-line--blocking {
+ background: rgb(var(--color-error) / 0.08);
+}
+
+.monaco-editor .bb-thread-line--attention {
+ background: rgb(var(--color-warning) / 0.1);
+}
+
.monaco-editor .bb-thread-line {
background: rgb(var(--color-accent) / 0.12);
}
diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
index c807cb7a76..f10ad864f0 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.test.ts
@@ -3,6 +3,7 @@ import { TimestampSchema } from "@bufbuild/protobuf/wkt";
import { describe, expect, test } from "vitest";
import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
+ type IssueComment,
IssueComment_ReviewMetadataSchema,
IssueComment_ThreadState,
IssueCommentSchema,
@@ -25,6 +26,8 @@ import {
formatLineRange,
groupMarkersByLine,
groupThreads,
+ isShownInEditor,
+ needsActivityCard,
resolveAnchorState,
selectEditorThreads,
sheetSha256OfName,
@@ -204,6 +207,125 @@ describe("resolveAnchorState", () => {
});
});
+describe("isShownInEditor", () => {
+ const noPlacement = () => undefined;
+ const noPreview = () => undefined;
+
+ test("shows a thread placed CURRENT on its spec's sheet", () => {
+ expect(
+ isShownInEditor(
+ root("here", { anchor: anchor(3, 4) }),
+ plan().specs,
+ noPlacement,
+ noPreview
+ )
+ ).toBe(true);
+ });
+
+ test("hides a thread past the loaded head of an oversized statement", () => {
+ expect(
+ isShownInEditor(
+ root("far", { anchor: anchor(30, 31) }),
+ plan().specs,
+ noPlacement,
+ () => 20
+ )
+ ).toBe(false);
+ expect(
+ isShownInEditor(
+ root("near", { anchor: anchor(19, 20) }),
+ plan().specs,
+ noPlacement,
+ () => 20
+ )
+ ).toBe(true);
+ });
+
+ test("hides a thread with no anchor, an outdated placement, or an unplaced revision", () => {
+ expect(
+ isShownInEditor(root("whole"), plan().specs, noPlacement, noPreview)
+ ).toBe(false);
+ expect(
+ isShownInEditor(
+ root("outdated", { anchor: anchor(3, 3) }),
+ plan().specs,
+ () => OUTDATED,
+ noPreview
+ )
+ ).toBe(false);
+ expect(
+ isShownInEditor(
+ root("pending", { anchor: anchor(3, 3, OTHER_SHA) }),
+ plan().specs,
+ noPlacement,
+ noPreview
+ )
+ ).toBe(false);
+ });
+
+ test("follows a computed placement to its current line", () => {
+ expect(
+ isShownInEditor(
+ root("moved", { anchor: anchor(3, 3, OTHER_SHA) }),
+ plan().specs,
+ () => current(25, 25),
+ () => 20
+ )
+ ).toBe(false);
+ });
+});
+
+describe("needsActivityCard", () => {
+ const finding = (
+ id: string,
+ opts: { resolved?: boolean; superseded?: boolean } = {}
+ ) =>
+ create(IssueCommentSchema, {
+ ...root(id, { resolved: opts.resolved }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: ReviewRun_Type.RULE,
+ superseded: opts.superseded ?? false,
+ }),
+ });
+ const threadOf = (rootComment: IssueComment, replies: IssueComment[] = []) =>
+ groupThreads([rootComment, ...replies])[0];
+
+ test("a finding the editor shows needs no card, unless someone replied", () => {
+ expect(needsActivityCard(threadOf(finding("shown")), true)).toBe(false);
+ expect(
+ needsActivityCard(
+ threadOf(finding("talked"), [reply("r", "talked", 2)]),
+ true
+ )
+ ).toBe(true);
+ });
+
+ test("a finding the editor cannot show keeps its card", () => {
+ expect(needsActivityCard(threadOf(finding("hidden")), false)).toBe(true);
+ });
+
+ test("a resolved superseded result is history, a reopened one is not", () => {
+ expect(
+ needsActivityCard(
+ threadOf(finding("old", { resolved: true, superseded: true })),
+ false
+ )
+ ).toBe(false);
+ expect(
+ needsActivityCard(
+ threadOf(finding("reopened", { superseded: true })),
+ false
+ )
+ ).toBe(true);
+ expect(
+ needsActivityCard(
+ threadOf(finding("reopened-shown", { superseded: true })),
+ true
+ )
+ ).toBe(false);
+ });
+});
+
describe("buildWholeLineAnchor", () => {
test("orders the lines and uses zero columns", () => {
const built = buildWholeLineAnchor({
diff --git a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
index f591c2b913..13bc7ccd62 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/threadModel.ts
@@ -228,6 +228,46 @@ export function selectEditorThreads(
return placed.sort(compareEditorThreads);
}
+// Whether the statement editor shows a thread: anchored, placed CURRENT on
+// its spec's current sheet, and inside the part of an oversized statement
+// the editor loaded. Anything else can only be read in its Activity card.
+export function isShownInEditor(
+ root: IssueComment,
+ specs: readonly Plan_Spec[],
+ placementFor: (
+ commentName: string,
+ specId: string,
+ sheetSha256: string | undefined
+ ) => Placement | undefined,
+ previewEndLineFor: (specId: string) => number | undefined
+): boolean {
+ const anchor = root.statementAnchor;
+ if (!anchor) return false;
+ const spec = specs.find((candidate) => candidate.id === anchor.spec);
+ const sheetSha256 = targetSha256OfSpec(spec);
+ const placement =
+ placementFor(root.name, anchor.spec, sheetSha256) ??
+ trivialPlacement(anchor, sheetSha256);
+ if (placement?.state !== "CURRENT") return false;
+ const previewEndLine = previewEndLineFor(anchor.spec);
+ return (
+ previewEndLine === undefined || placement.range.endLine <= previewEndLine
+ );
+}
+
+// Under SQL Review V2, Activity records each run as one line, so a finding
+// keeps its own card only where nothing else shows it: people replied to it,
+// or the editor cannot show it. A result a later run superseded is history
+// unless someone reopened it, since an open thread holds the rollout.
+export function needsActivityCard(
+ thread: CommentThread,
+ shownInEditor: boolean
+): boolean {
+ if (thread.replies.length > 0) return true;
+ if (thread.root.reviewMetadata?.superseded && thread.resolved) return false;
+ return !shownInEditor;
+}
+
export const isEditorThreadVisible = (
entry: EditorThread,
previewEndLine: number | undefined
diff --git a/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts b/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts
index f304c6d20f..489025db0d 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/useThreadActions.ts
@@ -8,6 +8,7 @@ import {
type StatementAnchor,
} from "@/types/proto-es/v1/issue_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
// Resolve and Reopen go through UpdateIssueComment, which the server gates
@@ -19,12 +20,14 @@ export function canSettleThread(project: Project | undefined): boolean {
);
}
+// A draft takes comments only where its Review section shows them: under
+// SQL Review V2, which reviews drafts too.
export function canReplyToThread(
project: Project | undefined,
issue: Issue
): boolean {
return Boolean(
- !issue.draft &&
+ (!issue.draft || sqlReviewV2Enabled()) &&
project &&
hasProjectPermissionV2(project, "bb.issueComments.create")
);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
index fa1ce47b06..36482eecfd 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
+++ b/frontend/src/routes/project/plan-detail/components/threads/useUnresolvedThreadCounts.ts
@@ -39,18 +39,14 @@ export function useIssueThreadsLoaded(issueName: string | undefined) {
);
}
-// Unresolved threads the statement editor shows for each of `specs`, so a
-// change tab and its editor walker agree.
-export function usePlacedUnresolvedThreadCounts(
- issueName: string | undefined,
- specs: Plan_Spec[],
+// The last complete line the statement editor loads for each spec whose
+// sheet is too large to load whole; specs loaded whole have no entry.
+export function usePreviewEndLines(
+ specs: readonly Plan_Spec[],
projectName: string
): ReadonlyMap<string, number> {
- const threads = useIssueThreads(issueName);
const sheetsByName = useAppStore((s) => s.sheetsByName);
- const placements = usePlanDetailStore((s) => s.placements);
- const placementTargets = usePlanDetailStore((s) => s.placementTargets);
- const previewEndLines = useMemo(() => {
+ return useMemo(() => {
const lines = new Map<string, number>();
for (const spec of specs) {
const sha = targetSha256OfSpec(spec);
@@ -67,6 +63,19 @@ export function usePlacedUnresolvedThreadCounts(
}
return lines;
}, [projectName, sheetsByName, specs]);
+}
+
+// Unresolved threads the statement editor shows for each of `specs`, so a
+// change tab and its editor walker agree.
+export function usePlacedUnresolvedThreadCounts(
+ issueName: string | undefined,
+ specs: Plan_Spec[],
+ projectName: string
+): ReadonlyMap<string, number> {
+ const threads = useIssueThreads(issueName);
+ const placements = usePlanDetailStore((s) => s.placements);
+ const placementTargets = usePlanDetailStore((s) => s.placementTargets);
+ const previewEndLines = usePreviewEndLines(specs, projectName);
return useMemo(
() =>
countPlacedUnresolvedBySpec(
diff --git a/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.test.ts b/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.test.ts
new file mode 100644
index 0000000000..4433c28c27
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.test.ts
@@ -0,0 +1,234 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { IssueStatus } from "@/types/proto-es/v1/common_pb";
+import {
+ DatabaseGroupSchema,
+ DatabaseGroupView,
+} from "@/types/proto-es/v1/database_group_service_pb";
+import {
+ IssueSchema,
+ type ReviewRun,
+ ReviewRun_Status,
+ ReviewRunSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ type Plan_Spec,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_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: {
+ dbGroupsByName: {} as Record<string, unknown>,
+ dbGroupViewByName: {} as Record<string, unknown>,
+ },
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/api", () => ({
+ issueServiceClientConnect: { runReview: mocks.runReview },
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: (selector: (state: unknown) => unknown) =>
+ selector({ serverInfo: mocks.serverInfo, ...mocks.groups }),
+}));
+
+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 { useAIReviewRun } from "./useAIReviewRun";
+
+const ISSUE = "projects/p/issues/1";
+const GROUP = "projects/p/databaseGroups/g";
+
+const spec = (targets: string[]): Plan_Spec["config"] => ({
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, { targets }),
+});
+
+const run = (status: ReviewRun_Status) =>
+ create(ReviewRunSchema, { name: `${ISSUE}/reviewRuns/ai`, status });
+
+const openPage = (
+ aiReviewRun: ReviewRun | null | undefined,
+ overrides: Record<string, unknown> = {}
+) => {
+ mocks.page = {
+ aiReviewRun,
+ isEditing: false,
+ issue: create(IssueSchema, { name: ISSUE, status: IssueStatus.OPEN }),
+ patchState: vi.fn(),
+ plan: create(PlanSchema, {
+ name: "projects/p/plans/1",
+ issue: ISSUE,
+ specs: [{ id: "0", config: spec(["instances/i/databases/d"]) }],
+ }),
+ 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>;
+ };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.dev = true;
+ mocks.permissions = new Set(["bb.reviewRuns.get", "bb.reviewRuns.run"]);
+ mocks.serverInfo = { aiEnabled: true, aiSqlReviewEnabled: true };
+ mocks.groups = { dbGroupsByName: {}, dbGroupViewByName: {} };
+});
+
+describe("useAIReviewRun", () => {
+ test("starts a run on a slot that never ran", () => {
+ openPage(null);
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(true);
+ expect(result.current.canStart).toBe(true);
+ });
+
+ test("sends RunReview for the issue's AI slot and adopts the started run", async () => {
+ const page = openPage(null);
+ const started = run(ReviewRun_Status.AVAILABLE);
+ mocks.runReview.mockResolvedValueOnce(started);
+ const { result } = renderHook(() => useAIReviewRun());
+ await act(async () => {
+ await result.current.runReview();
+ });
+ expect(mocks.runReview).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ name: `${ISSUE}/reviewRuns/ai` }),
+ expect.anything()
+ );
+ expect(page.patchState).toHaveBeenCalledExactlyOnceWith({
+ aiReviewRun: started,
+ });
+ expect(page.refreshState).toHaveBeenCalledOnce();
+ });
+
+ test("reports the server message when RunReview fails and changes nothing else", async () => {
+ const page = openPage(null);
+ mocks.runReview.mockRejectedValueOnce(
+ new ConnectError("AI review is off", Code.FailedPrecondition)
+ );
+ const { result } = renderHook(() => useAIReviewRun());
+ await act(async () => {
+ await result.current.runReview();
+ });
+ expect(mocks.pushNotification).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ style: "CRITICAL",
+ title: "plan.ai-review.failed-to-run",
+ description: "AI review is off",
+ })
+ );
+ expect(page.patchState).not.toHaveBeenCalled();
+ expect(result.current.canStart).toBe(true);
+ });
+
+ test.each<[string, ReviewRun | null | undefined, Record<string, unknown>]>([
+ ["a run is queued", run(ReviewRun_Status.AVAILABLE), {}],
+ ["a run is running", run(ReviewRun_Status.RUNNING), {}],
+ ["the slot has not been read", undefined, {}],
+ ["the page has unsaved edits", null, { isEditing: true }],
+ ])("cannot start while %s", (_, aiReviewRun, overrides) => {
+ openPage(aiReviewRun, overrides);
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(true);
+ expect(result.current.canStart).toBe(false);
+ });
+
+ test("shows but cannot run without the run permission", () => {
+ mocks.permissions = new Set(["bb.reviewRuns.get"]);
+ openPage(null);
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(true);
+ expect(result.current.allowRun).toBe(false);
+ });
+
+ test("shows for a draft issue", () => {
+ openPage(null, {
+ issue: create(IssueSchema, {
+ name: ISSUE,
+ status: IssueStatus.OPEN,
+ draft: true,
+ }),
+ });
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(true);
+ });
+
+ test("hides while the plan's only group matches no databases", () => {
+ openPage(null, {
+ plan: create(PlanSchema, {
+ name: "projects/p/plans/1",
+ issue: ISSUE,
+ specs: [{ id: "0", config: spec([GROUP]) }],
+ }),
+ });
+ mocks.groups = {
+ dbGroupsByName: {
+ [GROUP]: create(DatabaseGroupSchema, {
+ name: GROUP,
+ matchedDatabases: [],
+ }),
+ },
+ dbGroupViewByName: { [GROUP]: DatabaseGroupView.FULL },
+ };
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(false);
+ });
+
+ test.each<[string, () => void]>([
+ ["outside dev builds", () => (mocks.dev = false)],
+ [
+ "with AI review off",
+ () => (mocks.serverInfo = { aiEnabled: true, aiSqlReviewEnabled: false }),
+ ],
+ [
+ "once a rollout exists",
+ () =>
+ openPage(null, {
+ rollout: create(RolloutSchema, {
+ name: "projects/p/plans/1/rollout",
+ }),
+ }),
+ ],
+ ])("hides %s", (_, arrange) => {
+ openPage(null);
+ arrange();
+ const { result } = renderHook(() => useAIReviewRun());
+ expect(result.current.shown).toBe(false);
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.ts b/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.ts
new file mode 100644
index 0000000000..61afaafefc
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useAIReviewRun.ts
@@ -0,0 +1,89 @@
+import { create } from "@bufbuild/protobuf";
+import { ConnectError, createContextValues } from "@connectrpc/connect";
+import { useCallback, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect } from "@/api";
+import { skipErrorNotificationContextKey } from "@/api/context-key";
+import { pushNotification } from "@/stores";
+import { useAppStore } from "@/stores/app";
+import { IssueStatus } from "@/types/proto-es/v1/common_pb";
+import { 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: whether the page shows it, and starting a run.
+// RunReview replaces whatever execution the slot holds and the backend has no
+// same-version no-op, so a run cannot start while one is queued or running,
+// nor 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. A run reviews the saved plan, so unsaved SQL would
+// get findings about a statement the user has already changed.
+export 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 run = page.aiReviewRun;
+ const canStart =
+ allowRun &&
+ !starting &&
+ !page.isEditing &&
+ run !== undefined &&
+ !isAIReviewRunActive(run);
+
+ const runReview = useCallback(async () => {
+ if (!issue) return;
+ setStarting(true);
+ try {
+ const started = await issueServiceClientConnect.runReview(
+ create(RunReviewRequestSchema, { name: aiReviewRunName(issue.name) }),
+ {
+ contextValues: createContextValues().set(
+ skipErrorNotificationContextKey,
+ true
+ ),
+ }
+ );
+ patchState({ aiReviewRun: started });
+ 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]);
+
+ const editing = page.isEditing;
+ return useMemo(
+ () => ({ allowRun, canStart, editing, run, runReview, shown, starting }),
+ [allowRun, canStart, editing, run, runReview, shown, starting]
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/hooks/useEffectiveStandardRules.ts b/frontend/src/routes/project/plan-detail/hooks/useEffectiveStandardRules.ts
new file mode 100644
index 0000000000..3e6d23544b
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useEffectiveStandardRules.ts
@@ -0,0 +1,63 @@
+import { useEffect } from "react";
+import {
+ effectiveWorkspaceRules,
+ reviewRulesOfPolicy,
+} from "@/components/sql-review/standardRules";
+import { useWorkspaceResourceName } from "@/hooks/useAppState";
+import { useAppStore } from "@/stores/app";
+import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
+import type { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+
+export type EffectiveStandardRules = {
+ rules: ReviewRuleType[];
+ source: "project" | "workspace";
+};
+
+// The standard rules the rule review applies to a project: its own enforced
+// policy, else the workspace's. Undefined until known, and when the reader
+// cannot see the workspace rules a project without its own follows.
+export function useEffectiveStandardRules(
+ projectName: string
+): EffectiveStandardRules | undefined {
+ const workspace = useWorkspaceResourceName();
+ const canReadWorkspace = hasWorkspacePermissionV2("bb.policies.get");
+ const projectPolicy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ );
+ const workspacePolicy = useAppStore((state) =>
+ state.getPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ );
+ useEffect(() => {
+ const store = useAppStore.getState();
+ void store
+ .fetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ .catch(() => undefined);
+ if (workspace && canReadWorkspace) {
+ void store
+ .fetchPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ })
+ .catch(() => undefined);
+ }
+ }, [canReadWorkspace, projectName, workspace]);
+
+ const projectRules = reviewRulesOfPolicy(projectPolicy);
+ if (projectRules) return { rules: projectRules, source: "project" };
+ const workspaceRules = canReadWorkspace
+ ? effectiveWorkspaceRules(workspacePolicy)
+ : undefined;
+ return workspaceRules
+ ? { rules: workspaceRules, source: "workspace" }
+ : undefined;
+}
diff --git a/frontend/src/routes/project/plan-detail/hooks/useFocusThread.test.ts b/frontend/src/routes/project/plan-detail/hooks/useFocusThread.test.ts
new file mode 100644
index 0000000000..cccc3b93f5
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useFocusThread.test.ts
@@ -0,0 +1,87 @@
+import { create } from "@bufbuild/protobuf";
+import { renderHook } from "@testing-library/react";
+import { beforeEach, expect, test, vi } from "vitest";
+import {
+ IssueCommentSchema,
+ StatementAnchorSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ Plan_SpecSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ focusPlanPhase: vi.fn(),
+ push: vi.fn(),
+ requestActivityFocus: vi.fn(),
+ requestThreadFocus: vi.fn(),
+}));
+
+vi.mock("@/app/router", () => ({ router: { push: mocks.push } }));
+
+vi.mock("../shell/focusPhase", () => ({
+ focusPlanPhase: mocks.focusPlanPhase,
+}));
+
+vi.mock("../shared/stores/usePlanDetailStore", () => ({
+ usePlanDetailStoreApi: () => ({
+ getState: () => ({
+ requestActivityFocus: mocks.requestActivityFocus,
+ requestThreadFocus: mocks.requestThreadFocus,
+ selectedSpecId: "spec-1",
+ }),
+ }),
+}));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => ({
+ expandPhase: vi.fn(),
+ plan: create(PlanSchema, {
+ specs: [
+ create(Plan_SpecSchema, { id: "spec-1" }),
+ create(Plan_SpecSchema, { id: "spec-2" }),
+ ],
+ }),
+ planId: "1",
+ projectId: "p",
+ }),
+}));
+
+import { useFocusThread } from "./useFocusThread";
+
+const thread = (spec?: string) =>
+ create(IssueCommentSchema, {
+ name: "projects/p/issues/1/issueComments/7",
+ statementAnchor: spec ? create(StatementAnchorSchema, { spec }) : undefined,
+ });
+
+beforeEach(() => vi.clearAllMocks());
+
+test("opens a thread on another change in that change's editor", () => {
+ const { result } = renderHook(() => useFocusThread());
+ result.current.focusInStatement(thread("spec-2"), 4);
+ expect(mocks.requestThreadFocus).toHaveBeenCalledWith({
+ commentName: "projects/p/issues/1/issueComments/7",
+ specId: "spec-2",
+ lineNumber: 4,
+ });
+ expect(mocks.push).toHaveBeenCalledOnce();
+ expect(mocks.requestActivityFocus).not.toHaveBeenCalled();
+});
+
+test.each([
+ ["without an anchor", undefined],
+ ["anchored to a change the plan no longer has", "spec-gone"],
+])("sends a thread %s to its Activity card", (_, spec) => {
+ const { result } = renderHook(() => useFocusThread());
+ result.current.focusInStatement(thread(spec));
+ expect(mocks.focusPlanPhase).toHaveBeenCalledWith(
+ "review",
+ expect.any(Function)
+ );
+ expect(mocks.requestActivityFocus).toHaveBeenCalledWith(
+ "projects/p/issues/1/issueComments/7"
+ );
+ expect(mocks.requestThreadFocus).not.toHaveBeenCalled();
+ expect(mocks.push).not.toHaveBeenCalled();
+});
diff --git a/frontend/src/routes/project/plan-detail/hooks/useFocusThread.ts b/frontend/src/routes/project/plan-detail/hooks/useFocusThread.ts
new file mode 100644
index 0000000000..8f5592059e
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useFocusThread.ts
@@ -0,0 +1,53 @@
+import { useCallback } from "react";
+import { router } from "@/app/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";
+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { usePlanDetailStoreApi } from "../shared/stores/usePlanDetailStore";
+import { focusPlanPhase } from "../shell/focusPhase";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+
+// Opens the Changes phase on a thread's spec and asks the statement editor to
+// reveal it; the editor picks the request up once it shows that spec. A
+// thread without an anchor, or anchored to a change the plan no longer has,
+// has only its Activity card.
+export function useFocusThread() {
+ const page = usePlanDetailContext();
+ const storeApi = usePlanDetailStoreApi();
+ const { expandPhase, plan, planId, projectId } = page;
+
+ const focusInActivity = useCallback(
+ (root: IssueComment) => {
+ focusPlanPhase("review", expandPhase);
+ storeApi.getState().requestActivityFocus(root.name);
+ },
+ [expandPhase, storeApi]
+ );
+
+ const focusInStatement = useCallback(
+ (root: IssueComment, lineNumber?: number) => {
+ const specId = root.statementAnchor?.spec;
+ if (!specId || !plan.specs.some((spec) => spec.id === specId)) {
+ focusInActivity(root);
+ return;
+ }
+ storeApi.getState().requestThreadFocus({
+ commentName: root.name,
+ specId,
+ lineNumber: lineNumber ?? root.statementAnchor?.startPosition?.line,
+ });
+ focusPlanPhase("changes", expandPhase);
+ if (storeApi.getState().selectedSpecId !== specId) {
+ void router.push(
+ {
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: { planId, projectId, specId },
+ },
+ { preventScrollReset: true }
+ );
+ }
+ },
+ [expandPhase, focusInActivity, plan.specs, planId, projectId, storeApi]
+ );
+
+ return { focusInActivity, focusInStatement };
+}
diff --git a/frontend/src/routes/project/plan-detail/hooks/usePlanReviewState.ts b/frontend/src/routes/project/plan-detail/hooks/usePlanReviewState.ts
new file mode 100644
index 0000000000..6cd7ad5c0c
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/usePlanReviewState.ts
@@ -0,0 +1,111 @@
+import { useMemo } from "react";
+import { useAppStore } from "@/stores/app";
+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import { deriveSteps } from "../components/review/ReviewApprovalFlow";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import {
+ hasReviewableSQL,
+ loadedMatchedDatabaseCount,
+} from "../utils/aiReviewRun";
+import {
+ type AutomatedReviewRow,
+ aiReviewRow,
+ computePlanGates,
+ countFindings,
+ countOpenDiscussions,
+ type PlanGate,
+ planCheckRow,
+ planCheckRunRow,
+ resolvedByPeople,
+ ruleReviewApplies,
+ ruleReviewRow,
+} from "../utils/planGates";
+import { useAIReviewRun } from "./useAIReviewRun";
+import { useSqlReviewV2 } from "./useSqlReviewV2";
+
+const NO_COMMENTS: IssueComment[] = [];
+
+export type PlanReviewState = {
+ rows: AutomatedReviewRow[];
+ gates: PlanGate[];
+ openDiscussions: number;
+ ai: ReturnType<typeof useAIReviewRun>;
+};
+
+// The automated reviewers' rows and the rollout's gates under SQL Review V2;
+// undefined where it is off or before the plan has an issue.
+export function usePlanReviewState(): PlanReviewState | undefined {
+ const page = usePlanDetailContext();
+ const sqlReview = useSqlReviewV2();
+ const ai = useAIReviewRun();
+ const issue = page.issue;
+ const comments = useAppStore((state) =>
+ issue ? state.getIssueComments(issue.name) : NO_COMMENTS
+ );
+ const ruleReview = sqlReview?.ruleReview;
+ const dbGroupsByName = useAppStore((state) => state.dbGroupsByName);
+ const dbGroupViewByName = useAppStore((state) => state.dbGroupViewByName);
+ const reviewsSQL = useMemo(
+ () =>
+ hasReviewableSQL(
+ page.plan,
+ loadedMatchedDatabaseCount({ dbGroupsByName, dbGroupViewByName })
+ ),
+ [dbGroupViewByName, dbGroupsByName, page.plan]
+ );
+ const currentApprovalRole = useMemo(
+ () =>
+ issue
+ ? deriveSteps(issue).find((step) => step.status === "current")?.role
+ : undefined,
+ [issue]
+ );
+
+ return useMemo(() => {
+ if (!sqlReview || !issue) return undefined;
+ const rows: AutomatedReviewRow[] = [];
+ if (ruleReview && ruleReviewApplies(ruleReview.run, reviewsSQL)) {
+ rows.push(
+ ruleReviewRow({
+ run: ruleReview.run,
+ stale: ruleReview.stale,
+ loadFailed: ruleReview.loadFailed,
+ findings: countFindings(comments, "rule"),
+ })
+ );
+ }
+ const aiFindings = countFindings(comments, "ai");
+ if (ai.shown || aiFindings.open + resolvedByPeople(aiFindings) > 0) {
+ rows.push(
+ aiReviewRow({ run: ai.run, runFetched: ai.shown, findings: aiFindings })
+ );
+ }
+ for (const reviewer of ["policy", "ghost", "report"] as const) {
+ const row = planCheckRow(reviewer, page.planCheckRuns);
+ if (row) rows.push(row);
+ }
+ const runRow = planCheckRunRow(page.planCheckRuns);
+ if (runRow) rows.push(runRow);
+ const openDiscussions = countOpenDiscussions(comments);
+ return {
+ rows,
+ gates: computePlanGates({
+ issue,
+ currentApprovalRole,
+ rows,
+ openDiscussions,
+ }),
+ openDiscussions,
+ ai,
+ };
+ }, [
+ ai,
+ comments,
+ currentApprovalRole,
+ issue,
+ page.planCheckRuns,
+ reviewsSQL,
+ ruleReview,
+ sqlReview,
+ ]);
+}
diff --git a/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.test.ts b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.test.ts
new file mode 100644
index 0000000000..b27a35c6a5
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.test.ts
@@ -0,0 +1,112 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, expect, test, vi } from "vitest";
+import { IssueStatus } from "@/types/proto-es/v1/common_pb";
+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";
+import { RolloutSchema } from "@/types/proto-es/v1/rollout_service_pb";
+
+const mocks = vi.hoisted(() => ({
+ page: {} as Record<string, unknown>,
+ permitted: true,
+ pushNotification: vi.fn(),
+ reload: vi.fn(async () => undefined),
+ runReview: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/api", () => ({
+ issueServiceClientConnect: { runReview: mocks.runReview },
+}));
+
+vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
+
+vi.mock("@/utils/iam/permission", () => ({
+ hasProjectPermissionV2: () => mocks.permitted,
+}));
+
+vi.mock("../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => mocks.page,
+}));
+
+vi.mock("./useSqlReviewV2", () => ({
+ useSqlReviewV2: () => ({ ruleReview: { reload: mocks.reload } }),
+}));
+
+import { useRuleReviewRerun } from "./useRuleReviewRerun";
+
+const ISSUE = "projects/p/issues/1";
+
+const openPage = (overrides: Record<string, unknown> = {}) => {
+ mocks.page = {
+ issue: create(IssueSchema, { name: ISSUE, status: IssueStatus.OPEN }),
+ isEditing: false,
+ project: {},
+ readonly: false,
+ rollout: undefined,
+ ...overrides,
+ };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.permitted = true;
+ openPage();
+});
+
+test("starts the issue's rule review and reads it again", async () => {
+ mocks.runReview.mockResolvedValueOnce({});
+ const { result } = renderHook(() => useRuleReviewRerun());
+ expect(result.current.allowed).toBe(true);
+ await act(async () => {
+ await result.current.run();
+ });
+ expect(mocks.runReview).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ name: `${ISSUE}/reviewRuns/rule` }),
+ expect.anything()
+ );
+ expect(mocks.reload).toHaveBeenCalledOnce();
+});
+
+test("reports the server message when the run cannot start", async () => {
+ mocks.runReview.mockRejectedValueOnce(
+ new ConnectError("plan has a rollout", Code.FailedPrecondition)
+ );
+ const { result } = renderHook(() => useRuleReviewRerun());
+ await act(async () => {
+ await result.current.run();
+ });
+ expect(mocks.pushNotification).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ title: "plan.automated-review.failed-to-rerun",
+ description: "plan has a rollout",
+ })
+ );
+ expect(mocks.reload).not.toHaveBeenCalled();
+});
+
+test.each<[string, () => void]>([
+ ["once a rollout exists", () => openPage({ rollout: create(RolloutSchema) })],
+ [
+ "on a closed issue",
+ () =>
+ openPage({
+ issue: create(IssueSchema, { name: ISSUE, status: IssueStatus.DONE }),
+ }),
+ ],
+ ["without the run permission", () => (mocks.permitted = false)],
+])("is not offered %s", (_, arrange) => {
+ arrange();
+ const { result } = renderHook(() => useRuleReviewRerun());
+ expect(result.current.allowed).toBe(false);
+});
+
+test("waits for unsaved edits, since a run reviews the saved plan", () => {
+ openPage({ isEditing: true });
+ const { result } = renderHook(() => useRuleReviewRerun());
+ expect(result.current.disabled).toBe(true);
+});
diff --git a/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.ts b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.ts
new file mode 100644
index 0000000000..605dc96426
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/useRuleReviewRerun.ts
@@ -0,0 +1,64 @@
+import { create } from "@bufbuild/protobuf";
+import { ConnectError, createContextValues } from "@connectrpc/connect";
+import { useCallback, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect } from "@/api";
+import { skipErrorNotificationContextKey } from "@/api/context-key";
+import { pushNotification } from "@/stores";
+import { IssueStatus } from "@/types/proto-es/v1/common_pb";
+import { RunReviewRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
+import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { useSqlReviewV2 } from "./useSqlReviewV2";
+
+// Starts the standard rule review again on the saved SQL. The SQL is not the
+// only input: rule settings and the synced schema change what the rules
+// find, so a reviewer with a result can still need another run. RunReview
+// accepts it only for an open issue whose SQL no rollout has frozen.
+export function useRuleReviewRerun() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const ruleReview = useSqlReviewV2()?.ruleReview;
+ const [starting, setStarting] = useState(false);
+ const { issue } = page;
+ const allowed =
+ issue?.status === IssueStatus.OPEN &&
+ !page.rollout &&
+ !page.readonly &&
+ hasProjectPermissionV2(page.project, "bb.reviewRuns.run");
+
+ const run = useCallback(async () => {
+ if (!issue) return;
+ setStarting(true);
+ try {
+ await issueServiceClientConnect.runReview(
+ create(RunReviewRequestSchema, {
+ name: `${issue.name}/reviewRuns/rule`,
+ }),
+ {
+ contextValues: createContextValues().set(
+ skipErrorNotificationContextKey,
+ true
+ ),
+ }
+ );
+ await ruleReview?.reload();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("plan.automated-review.failed-to-rerun"),
+ description: ConnectError.from(error).rawMessage,
+ });
+ } finally {
+ setStarting(false);
+ }
+ }, [issue, ruleReview, t]);
+
+ return {
+ allowed,
+ // A run reviews the saved plan, not the edits on screen.
+ disabled: starting || page.isEditing,
+ run,
+ };
+}
diff --git a/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts b/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts
index 309cb7e2fb..32abb8ccaf 100644
--- a/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts
+++ b/frontend/src/routes/project/plan-detail/shared/stores/threadFocusSlice.ts
@@ -20,4 +20,28 @@ export const createThreadFocusSlice: PlanDetailSliceCreator<
? { threadFocus: undefined }
: state
),
+ walkerFilter: undefined,
+ setWalkerFilter: (walkerFilter) => set({ walkerFilter }),
+ reviewRowRequest: undefined,
+ requestReviewRow: (reviewer) =>
+ set((state) => ({
+ reviewRowRequest: {
+ reviewer,
+ nonce: (state.reviewRowRequest?.nonce ?? 0) + 1,
+ },
+ })),
+ activityFocus: undefined,
+ requestActivityFocus: (commentName) =>
+ set((state) => ({
+ activityFocus: {
+ commentName,
+ nonce: (state.activityFocus?.nonce ?? 0) + 1,
+ },
+ })),
+ clearActivityFocus: (nonce) =>
+ set((state) =>
+ state.activityFocus && state.activityFocus.nonce === nonce
+ ? { activityFocus: undefined }
+ : state
+ ),
});
diff --git a/frontend/src/routes/project/plan-detail/shared/stores/types.ts b/frontend/src/routes/project/plan-detail/shared/stores/types.ts
index d9130e9ae2..7e3140b28f 100644
--- a/frontend/src/routes/project/plan-detail/shared/stores/types.ts
+++ b/frontend/src/routes/project/plan-detail/shared/stores/types.ts
@@ -1,5 +1,9 @@
import type { StateCreator } from "zustand";
-import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
+import type {
+ Issue,
+ IssueComment,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
import type {
Plan,
Plan_Spec,
@@ -7,6 +11,7 @@ import type {
} from "@/types/proto-es/v1/plan_service_pb";
import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
import type { Placement } from "../../components/threads/placement/place";
+import type { AutomatedReviewer, FindingGroup } from "../../utils/planGates";
export type PlanDetailPhase = "changes" | "review" | "deploy";
@@ -77,10 +82,27 @@ export interface ThreadFocusRequest {
nonce: number;
}
+// Narrows the statement editor's walker to one group of one reviewer's
+// findings, as a click on a finding count asks for.
+export interface WalkerFilter {
+ runType: ReviewRun_Type;
+ group: FindingGroup;
+}
+
export type ThreadFocusSlice = {
threadFocus: ThreadFocusRequest | undefined;
requestThreadFocus: (request: Omit<ThreadFocusRequest, "nonce">) => void;
clearThreadFocus: (nonce: number) => void;
+ walkerFilter: WalkerFilter | undefined;
+ setWalkerFilter: (filter: WalkerFilter | undefined) => void;
+ // An automated review row to expand and scroll to, as Activity's "Show"
+ // asks for.
+ reviewRowRequest: { reviewer: AutomatedReviewer; nonce: number } | undefined;
+ requestReviewRow: (reviewer: AutomatedReviewer) => void;
+ // A thread's Activity card to scroll to; the timeline unfolds to show it.
+ activityFocus: { commentName: string; nonce: number } | undefined;
+ requestActivityFocus: (commentName: string) => void;
+ clearActivityFocus: (nonce: number) => void;
};
// Measurements of one placement run, kept so the decision to move the rule
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.tsx
index adab999427..8f62de19b3 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
@@ -34,6 +34,7 @@ import { UserSchema } from "@/types/proto-es/v1/user_service_pb";
import type { PlanDetailPageSnapshot, PlanDetailPhase } from "./types";
const mocks = vi.hoisted(() => ({
+ sqlReviewV2: false,
fetchPlanSnapshot: vi.fn(),
getIssueRoute: vi.fn(() => ({ name: "issue-detail" })),
routerPush: vi.fn(),
@@ -41,6 +42,10 @@ const mocks = vi.hoisted(() => ({
setDocumentTitle: vi.fn(),
}));
+vi.mock("@/utils/featureGates", () => ({
+ sqlReviewV2Enabled: () => mocks.sqlReviewV2,
+}));
+
vi.mock("react-i18next", () => ({
initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
@@ -121,6 +126,7 @@ const buildSnapshotPatch = ({
describe("usePlanDetailPage", () => {
beforeEach(() => {
+ mocks.sqlReviewV2 = false;
vi.clearAllMocks();
clearPagedDataCache();
vi.spyOn(Math, "random").mockReturnValue(0.5);
@@ -370,6 +376,31 @@ describe("usePlanDetailPage", () => {
expect(mocks.routerReplace).not.toHaveBeenCalled();
});
+ test("under SQL Review V2 keeps Changes and Review open until the rollout exists", async () => {
+ mocks.sqlReviewV2 = true;
+ mocks.fetchPlanSnapshot.mockResolvedValue(
+ buildSnapshotPatch({
+ issue: {
+ name: "projects/foo/issues/1",
+ approvalStatus: ApprovalStatus.APPROVED,
+ draft: false,
+ status: IssueStatus.OPEN,
+ } as PlanDetailPageSnapshot["issue"],
+ planId: "plan-1",
+ })
+ );
+
+ const { result } = renderHook(
+ () => usePlanDetailPage({ projectId: "foo", planId: "plan-1" }),
+ { wrapper }
+ );
+
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ expect(result.current.activePhases).toEqual(
+ new Set(["changes", "review", "deploy"])
+ );
+ });
+
test("expands every phase for an explicit review route", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
index a5a575bf05..c61760455a 100644
--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
@@ -44,6 +44,7 @@ import { unknownPlan } from "@/types/v1/issue/plan";
import { unknownProject } from "@/types/v1/project";
import { unknownUser } from "@/types/v1/user";
import { setDocumentTitle } from "@/utils";
+import { sqlReviewV2Enabled } from "@/utils/featureGates";
import { isTaskActivelyTransitioning } from "@/utils/v1/issue/rollout";
import type { PlanDetailPhase } from "../../shared/stores/types";
import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";
@@ -168,7 +169,9 @@ type PhaseSelection = {
// The phase to focus by default: an explicit URL selection wins — a stage/task
// selection already resolves to an explicit deploy phase in useRouteSelection —
-// otherwise the furthest-progressed phase the plan has reached.
+// otherwise the furthest-progressed phase the plan has reached. Under SQL
+// Review V2 that is Deploy only once the rollout exists: findings and threads
+// also hold the rollout, and the page cannot see every gate.
const getCurrentPhase = (
snapshot: PlanDetailPageSnapshot,
selection: PhaseSelection
@@ -177,7 +180,11 @@ const getCurrentPhase = (
if (isPlanDetailPhase(routePhase)) {
return routePhase;
}
- if (snapshot.rollout || isRolloutExpected(snapshot)) {
+ const hasRollout = !!snapshot.rollout && !snapshot.issue?.draft;
+ if (
+ hasRollout ||
+ (!sqlReviewV2Enabled() && !snapshot.rollout && isRolloutExpected(snapshot))
+ ) {
return PLAN_DETAIL_PHASE_DEPLOY;
}
if (snapshot.issue) {
diff --git a/frontend/src/routes/project/plan-detail/utils/findingIndex.test.ts b/frontend/src/routes/project/plan-detail/utils/findingIndex.test.ts
new file mode 100644
index 0000000000..c121bf3738
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/findingIndex.test.ts
@@ -0,0 +1,86 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { expect, test } from "vitest";
+import { PositionSchema } from "@/types/proto-es/v1/common_pb";
+import {
+ IssueComment_ReviewMetadata_Priority,
+ IssueComment_ReviewMetadataSchema,
+ IssueComment_ThreadState,
+ IssueCommentSchema,
+ ReviewRun_Type,
+ StatementAnchorSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { Plan_SpecSchema } from "@/types/proto-es/v1/plan_service_pb";
+import { countByName, findingsInOrder } from "./findingIndex";
+
+const specs = [
+ create(Plan_SpecSchema, { id: "spec-1" }),
+ create(Plan_SpecSchema, { id: "spec-2" }),
+];
+
+const finding = (
+ name: string,
+ options: {
+ spec?: string;
+ line?: number;
+ priority?: IssueComment_ReviewMetadata_Priority;
+ resolved?: boolean;
+ runType?: ReviewRun_Type;
+ } = {}
+) =>
+ create(IssueCommentSchema, {
+ name,
+ threadState: options.resolved
+ ? IssueComment_ThreadState.RESOLVED
+ : IssueComment_ThreadState.OPEN,
+ statementAnchor:
+ options.line === undefined
+ ? undefined
+ : create(StatementAnchorSchema, {
+ spec: options.spec ?? "spec-1",
+ startPosition: create(PositionSchema, { line: options.line }),
+ }),
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType: options.runType ?? ReviewRun_Type.RULE,
+ priority: options.priority ?? IssueComment_ReviewMetadata_Priority.P1,
+ }),
+ });
+
+test("lists one group of a reviewer's findings in change and line order", () => {
+ const comments = [
+ finding("other-change", { spec: "spec-2", line: 1 }),
+ finding("whole-change"),
+ finding("line-7", { line: 7 }),
+ finding("line-2", { line: 2 }),
+ finding("p0", {
+ line: 1,
+ priority: IssueComment_ReviewMetadata_Priority.P0,
+ }),
+ finding("resolved", { line: 3, resolved: true }),
+ finding("ai", { line: 1, runType: ReviewRun_Type.AI }),
+ ];
+ expect(
+ findingsInOrder(comments, ReviewRun_Type.RULE, specs, "p1").map(
+ (comment) => comment.name
+ )
+ ).toEqual(["line-2", "line-7", "other-change", "whole-change"]);
+ expect(
+ findingsInOrder(comments, ReviewRun_Type.RULE, specs, "open").map(
+ (comment) => comment.name
+ )
+ ).toEqual(["p0", "line-2", "line-7", "other-change", "whole-change"]);
+ expect(
+ findingsInOrder(comments, ReviewRun_Type.RULE, specs, "resolved").map(
+ (comment) => comment.name
+ )
+ ).toEqual(["resolved"]);
+});
+
+test("counts findings by name, most frequent first", () => {
+ const comments = ["b", "a", "b", "c", "a", "b"].map((name) => finding(name));
+ expect(countByName(comments, (comment) => comment.name)).toEqual([
+ ["b", 3],
+ ["a", 2],
+ ["c", 1],
+ ]);
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/findingIndex.ts b/frontend/src/routes/project/plan-detail/utils/findingIndex.ts
new file mode 100644
index 0000000000..ffe42e8ff5
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/findingIndex.ts
@@ -0,0 +1,50 @@
+import type {
+ IssueComment,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { type FindingGroup, inFindingGroup } from "./planGates";
+
+// A reviewer's findings in one group, in change and line order: where a click
+// on a count lands first, and the order the walker steps in. A finding
+// without an anchor sorts last.
+export function findingsInOrder(
+ comments: readonly IssueComment[],
+ runType: ReviewRun_Type,
+ specs: readonly Plan_Spec[],
+ group: FindingGroup
+): IssueComment[] {
+ const specIndex = (comment: IssueComment) => {
+ const index = specs.findIndex(
+ (spec) => spec.id === comment.statementAnchor?.spec
+ );
+ return index === -1 ? Number.MAX_SAFE_INTEGER : index;
+ };
+ const line = (comment: IssueComment) =>
+ comment.statementAnchor?.startPosition?.line || Number.MAX_SAFE_INTEGER;
+ return comments
+ .filter(
+ (comment) =>
+ comment.reviewMetadata?.runType === runType &&
+ inFindingGroup(comment, group)
+ )
+ .sort(
+ (a, b) =>
+ specIndex(a) - specIndex(b) ||
+ line(a) - line(b) ||
+ a.name.localeCompare(b.name)
+ );
+}
+
+// How many findings share each name, most frequent first.
+export function countByName(
+ findings: readonly IssueComment[],
+ nameOf: (comment: IssueComment) => string
+): [string, number][] {
+ const counts = new Map<string, number>();
+ for (const comment of findings) {
+ const name = nameOf(comment);
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+ return [...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));
+}
diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts
index fddc9051cf..c055cf1107 100644
--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts
+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts
@@ -13,8 +13,10 @@ import {
buildChangesSummary,
buildDeploySummary,
buildReviewSummary,
+ buildReviewSummaryV2,
isRolloutExpected,
} from "./phaseSummary";
+import { emptyFindings, ruleReviewRow } from "./planGates";
const templates: Record<string, string> = {
"common.and": "and",
@@ -28,6 +30,14 @@ const templates: Record<string, string> = {
"plan.summary.n-passed": "{{n}} passed",
"plan.summary.n-unresolved-threads": "{{count}} unresolved threads",
"plan.summary.n-warning": "{{n}} warning",
+ "plan.summary.approved-by": "Approved by {{names}}",
+ "plan.summary.no-approval-required": "No approval required",
+ "plan.findings.n-resolved": "{{count}} resolved",
+ "plan.findings.n-overridden": "{{count}} P0 resolved without a change",
+ "plan.findings.separator": ", ",
+ "plan.automated-review.summary-part": "{{reviewer}}: {{status}}",
+ "plan.deploy-waiting.open-discussions": "{{count}} open discussions",
+ "sql-review.standard-rules.self": "Standard rules",
};
const t = (key: string, options?: Record<string, unknown>) => {
@@ -329,3 +339,56 @@ describe("isRolloutExpected", () => {
expect(isRolloutExpected({ issue: approvedIssue, plan })).toBe(true);
});
});
+
+describe("SQL Review V2 summaries", () => {
+ const resolvedRule = ruleReviewRow({
+ run: null,
+ stale: false,
+ loadFailed: false,
+ findings: { ...emptyFindings(), resolved: 2, overridden: 1 },
+ });
+
+ test("names the approvers and each reviewer's conclusion", () => {
+ const issue = {
+ draft: false,
+ approvalStatus: ApprovalStatus.APPROVED,
+ approvalTemplate: { flow: { roles: ["roles/a", "roles/b"] } },
+ approvers: [
+ { principal: "users/[email protected]" },
+ { principal: "users/[email protected]" },
+ ],
+ } as unknown as Issue;
+ expect(
+ buildReviewSummaryV2(
+ issue,
+ t,
+ [{ ...resolvedRule, conclusion: "resolved" }],
+ 0
+ )
+ ).toBe(
+ "Approved by alex, dana · Standard rules: 2 resolved, 1 P0 resolved without a change"
+ );
+ });
+
+ test("says no approval is required and counts open discussions", () => {
+ const issue = {
+ draft: false,
+ approvalStatus: ApprovalStatus.SKIPPED,
+ approvers: [],
+ } as unknown as Issue;
+ expect(buildReviewSummaryV2(issue, t, [], 2)).toBe(
+ "No approval required · 2 open discussions"
+ );
+ });
+
+ test("leaves the checks out of the Changes summary on request", () => {
+ const plan = {
+ planCheckRunStatusCount: { SUCCESS: 2 },
+ specs: [],
+ } as unknown as Plan;
+ expect(buildChangesSummary(plan, t)).toContain("2 passed");
+ expect(
+ buildChangesSummary(plan, t, { includeChecks: false })
+ ).not.toContain("passed");
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts
index b9fdc432fb..e189f6ad62 100644
--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts
+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts
@@ -11,6 +11,8 @@ import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import type { AutomatedReviewRow } from "./planGates";
+import { reviewSummaryPart } from "./reviewLabels";
export type { PlanCheckSummary } from "@/lib/plan/check";
@@ -22,7 +24,7 @@ const isDatabaseGroupName = (name: string): boolean =>
// Mirrors the eligibility gates that can permanently prevent RolloutCreator
// from materializing a rollout. Transient approval and check gates are handled
// separately below.
-const supportsAutomaticRollout = (plan: Plan): boolean =>
+export const supportsAutomaticRollout = (plan: Plan): boolean =>
plan.state === State.ACTIVE &&
plan.specs.length > 0 &&
plan.specs.every((spec) => spec.config?.case === "changeDatabaseConfig");
@@ -71,7 +73,13 @@ const targetsForSpec = (spec: Plan["specs"][number]): string[] => {
const extractPrincipalEmail = (principal: string): string =>
principal.replace(/^users\//, "");
-export const buildChangesSummary = (plan: Plan, t: T): string => {
+// Under SQL Review V2 the checks are reviewers in the Review section, so the
+// Changes summary leaves them out.
+export const buildChangesSummary = (
+ plan: Plan,
+ t: T,
+ { includeChecks = true }: { includeChecks?: boolean } = {}
+): string => {
const parts: string[] = [];
parts.push(t("plan.summary.n-changes", { n: plan.specs.length }));
@@ -93,7 +101,7 @@ export const buildChangesSummary = (plan: Plan, t: T): string => {
}
const checks = getPlanCheckSummary(plan);
- if (checks.total > 0) {
+ if (includeChecks && checks.total > 0) {
const checkParts: string[] = [];
if (checks.success > 0) {
checkParts.push(t("plan.summary.n-passed", { n: checks.success }));
@@ -147,6 +155,50 @@ export const buildReviewSummary = (
return parts.join(" · ");
};
+// The Review summary under SQL Review V2: the approval outcome, then each
+// reviewer's conclusion, so a reader can tell people resolved the findings.
+export const buildReviewSummaryV2 = (
+ issue: Issue | undefined,
+ t: T,
+ rows: readonly AutomatedReviewRow[],
+ openDiscussions: number
+): string => {
+ if (!issue) return "";
+ const parts: string[] = [];
+ const roles = issue.approvalTemplate?.flow?.roles ?? [];
+ if (!issue.draft) {
+ if (
+ issue.approvalStatus === ApprovalStatus.SKIPPED ||
+ (issue.approvalTemplate && roles.length === 0)
+ ) {
+ parts.push(t("plan.summary.no-approval-required"));
+ } else if (issue.approvalStatus === ApprovalStatus.APPROVED) {
+ const names = issue.approvers.map(
+ (approver) => extractPrincipalEmail(approver.principal).split("@")[0]
+ );
+ parts.push(t("plan.summary.approved-by", { names: names.join(", ") }));
+ } else if (issue.approvalStatus === ApprovalStatus.REJECTED) {
+ parts.push(t("plan.lifecycle.gate-review-rejected"));
+ } else if (roles.length > 0) {
+ parts.push(
+ t("plan.summary.n-of-m-approved", {
+ m: roles.length,
+ n: issue.approvers.length,
+ })
+ );
+ }
+ }
+ for (const row of rows) {
+ parts.push(reviewSummaryPart(t, row));
+ }
+ if (openDiscussions > 0) {
+ parts.push(
+ t("plan.deploy-waiting.open-discussions", { count: openDiscussions })
+ );
+ }
+ return parts.join(" · ");
+};
+
export const buildDeploySummary = (
rollout: Rollout | undefined,
t: T
diff --git a/frontend/src/routes/project/plan-detail/utils/planGates.test.ts b/frontend/src/routes/project/plan-detail/utils/planGates.test.ts
new file mode 100644
index 0000000000..b551db6e38
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/planGates.test.ts
@@ -0,0 +1,406 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import {
+ IssueComment_ReviewMetadata_Priority,
+ IssueComment_ReviewMetadataSchema,
+ IssueComment_ThreadState,
+ IssueCommentSchema,
+ IssueSchema,
+ ReviewRun_Status,
+ ReviewRun_Type,
+ ReviewRunSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ PlanCheckRun_Result_Type,
+ PlanCheckRun_ResultSchema,
+ PlanCheckRun_Status,
+ PlanCheckRunSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+import {
+ aiReviewRow,
+ computePlanGates,
+ countFindings,
+ countOpenDiscussions,
+ emptyFindings,
+ findingSetOf,
+ inFindingGroup,
+ planCheckRow,
+ planCheckRunRow,
+ type ReviewerFindings,
+ resolvedByPeople,
+ rowNeedsAttention,
+ ruleReviewApplies,
+ ruleReviewRow,
+} from "./planGates";
+
+const finding = (
+ runType: ReviewRun_Type,
+ threadState: IssueComment_ThreadState,
+ options: {
+ priority?: IssueComment_ReviewMetadata_Priority;
+ superseded?: boolean;
+ } = {}
+) =>
+ create(IssueCommentSchema, {
+ name: `c${Math.random()}`,
+ threadState,
+ reviewMetadata: create(IssueComment_ReviewMetadataSchema, {
+ runType,
+ priority: options.priority ?? IssueComment_ReviewMetadata_Priority.P1,
+ superseded: options.superseded ?? false,
+ }),
+ });
+
+const discussion = (threadState: IssueComment_ThreadState) =>
+ create(IssueCommentSchema, { name: `d${Math.random()}`, threadState });
+
+const run = (status: ReviewRun_Status, extra: { outdated?: boolean } = {}) =>
+ create(ReviewRunSchema, { status, ...extra });
+
+const NO_FINDINGS = emptyFindings();
+const findings = (extra: Partial<ReviewerFindings>): ReviewerFindings => ({
+ ...emptyFindings(),
+ ...extra,
+});
+const { P0, P1, P2 } = IssueComment_ReviewMetadata_Priority;
+const { OPEN, RESOLVED } = IssueComment_ThreadState;
+
+describe("findingSetOf", () => {
+ test.each([
+ [OPEN, P0, false, "p0"],
+ [OPEN, P1, false, "p1"],
+ [OPEN, P2, false, "p2"],
+ [OPEN, P1, true, "p1"],
+ [RESOLVED, P0, false, "overridden"],
+ [RESOLVED, P1, false, "resolved"],
+ [RESOLVED, P2, false, "resolved"],
+ [RESOLVED, P0, true, "earlier"],
+ ] as const)(
+ "a %s %s finding (superseded %s) is %s",
+ (state, priority, superseded, set) => {
+ expect(
+ findingSetOf(
+ finding(ReviewRun_Type.RULE, state, { priority, superseded })
+ )
+ ).toBe(set);
+ }
+ );
+
+ test("a discussion is no finding", () => {
+ expect(findingSetOf(discussion(OPEN))).toBeUndefined();
+ });
+});
+
+describe("inFindingGroup", () => {
+ test("open covers every open finding, whatever its priority", () => {
+ for (const priority of [P0, P1, P2]) {
+ expect(
+ inFindingGroup(finding(ReviewRun_Type.RULE, OPEN, { priority }), "open")
+ ).toBe(true);
+ }
+ expect(
+ inFindingGroup(finding(ReviewRun_Type.RULE, RESOLVED, {}), "open")
+ ).toBe(false);
+ });
+});
+
+describe("countFindings", () => {
+ test("splits open findings by priority and sets resolved P0s apart", () => {
+ const comments = [
+ finding(ReviewRun_Type.RULE, OPEN, { priority: P0 }),
+ finding(ReviewRun_Type.RULE, OPEN, { superseded: true }),
+ finding(ReviewRun_Type.RULE, RESOLVED, { priority: P0 }),
+ finding(ReviewRun_Type.RULE, RESOLVED, {}),
+ finding(ReviewRun_Type.RULE, RESOLVED, { priority: P2 }),
+ finding(ReviewRun_Type.RULE, RESOLVED, { superseded: true }),
+ finding(ReviewRun_Type.AI, OPEN, { priority: P2 }),
+ discussion(OPEN),
+ ];
+ const rule = countFindings(comments, "rule");
+ expect(rule).toEqual({
+ open: 2,
+ p0: 1,
+ p1: 1,
+ p2: 0,
+ overridden: 1,
+ resolved: 2,
+ earlier: 1,
+ });
+ expect(resolvedByPeople(rule)).toBe(3);
+ expect(countFindings(comments, "ai")).toMatchObject({ open: 1, p2: 1 });
+ expect(countOpenDiscussions(comments)).toBe(1);
+ });
+});
+
+describe("rowNeedsAttention", () => {
+ test("a P0 resolved without a change needs attention though it holds nothing", () => {
+ const row = ruleReviewRow({
+ run: run(ReviewRun_Status.DONE),
+ stale: false,
+ loadFailed: false,
+ findings: findings({ overridden: 1 }),
+ });
+ expect(row.conclusion).toBe("resolved");
+ expect(row.holdsRollout).toBe(false);
+ expect(rowNeedsAttention(row)).toBe(true);
+ });
+});
+
+describe("ruleReviewApplies", () => {
+ test.each([
+ ["a missing run on a plan with SQL", null, true, true],
+ ["a missing run on a plan with nothing to review", null, false, false],
+ [
+ "a run on a plan with nothing left to review",
+ run(ReviewRun_Status.DONE),
+ false,
+ true,
+ ],
+ ["a run not loaded yet", undefined, false, true],
+ ] as const)("%s", (_, reviewRun, reviewsSQL, applies) => {
+ expect(ruleReviewApplies(reviewRun, reviewsSQL)).toBe(applies);
+ });
+});
+
+describe("ruleReviewRow", () => {
+ test.each([
+ [run(ReviewRun_Status.DONE), NO_FINDINGS, "passed", false],
+ [run(ReviewRun_Status.DONE), findings({ resolved: 3 }), "resolved", false],
+ [
+ run(ReviewRun_Status.DONE),
+ findings({ open: 2, p1: 2, resolved: 1 }),
+ "open",
+ true,
+ ],
+ [run(ReviewRun_Status.RUNNING), NO_FINDINGS, "running", true],
+ [run(ReviewRun_Status.AVAILABLE), NO_FINDINGS, "running", true],
+ [run(ReviewRun_Status.FAILED), NO_FINDINGS, "failed", true],
+ [
+ run(ReviewRun_Status.DONE, { outdated: true }),
+ NO_FINDINGS,
+ "outdated",
+ true,
+ ],
+ [null, NO_FINDINGS, "not-run", true],
+ [undefined, NO_FINDINGS, "loading", true],
+ ] as const)("run %# concludes %s", (input, findings, conclusion, holds) => {
+ const row = ruleReviewRow({
+ run: input,
+ stale: false,
+ loadFailed: false,
+ findings,
+ });
+ expect(row.conclusion).toBe(conclusion);
+ expect(row.holdsRollout).toBe(holds);
+ });
+
+ test("a stale completion is not a result yet", () => {
+ const row = ruleReviewRow({
+ run: run(ReviewRun_Status.DONE),
+ stale: true,
+ loadFailed: false,
+ findings: NO_FINDINGS,
+ });
+ expect(row.conclusion).toBe("running");
+ });
+
+ test("a load failure is a failure", () => {
+ const row = ruleReviewRow({
+ run: undefined,
+ stale: false,
+ loadFailed: true,
+ findings: NO_FINDINGS,
+ });
+ expect(row.conclusion).toBe("failed");
+ });
+});
+
+describe("aiReviewRow", () => {
+ test("holds the rollout only through open findings", () => {
+ expect(
+ aiReviewRow({
+ run: run(ReviewRun_Status.RUNNING),
+ runFetched: true,
+ findings: NO_FINDINGS,
+ }).holdsRollout
+ ).toBe(false);
+ expect(
+ aiReviewRow({ run: null, runFetched: true, findings: NO_FINDINGS })
+ .conclusion
+ ).toBe("not-run");
+ const open = aiReviewRow({
+ run: run(ReviewRun_Status.DONE),
+ runFetched: true,
+ findings: findings({ open: 1, p1: 1 }),
+ });
+ expect(open.conclusion).toBe("open");
+ expect(open.holdsRollout).toBe(true);
+ });
+
+ test("concludes from the findings when the page does not read the run", () => {
+ const row = aiReviewRow({
+ run: undefined,
+ runFetched: false,
+ findings: findings({ resolved: 2, overridden: 1 }),
+ });
+ expect(row.conclusion).toBe("resolved");
+ expect(rowNeedsAttention(row)).toBe(true);
+ });
+});
+
+describe("planCheckRow", () => {
+ const checkRun = (
+ status: PlanCheckRun_Status,
+ results: [PlanCheckRun_Result_Type, Advice_Level, string][]
+ ) =>
+ create(PlanCheckRunSchema, {
+ status,
+ results: results.map(([type, level, target]) =>
+ create(PlanCheckRun_ResultSchema, { type, status: level, target })
+ ),
+ });
+
+ test("is absent without a result of its type", () => {
+ const runs = [
+ checkRun(PlanCheckRun_Status.DONE, [
+ [
+ PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT,
+ Advice_Level.SUCCESS,
+ "db1",
+ ],
+ ]),
+ ];
+ expect(planCheckRow("policy", runs)).toBeUndefined();
+ expect(planCheckRow("ghost", runs)).toBeUndefined();
+ });
+
+ test("errors are open findings, warnings pass", () => {
+ const runs = [
+ checkRun(PlanCheckRun_Status.DONE, [
+ [PlanCheckRun_Result_Type.STATEMENT_ADVISE, Advice_Level.ERROR, "db1"],
+ [
+ PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ Advice_Level.WARNING,
+ "db2",
+ ],
+ [PlanCheckRun_Result_Type.GHOST_SYNC, Advice_Level.SUCCESS, "db1"],
+ ]),
+ ];
+ const policy = planCheckRow("policy", runs);
+ expect(policy?.conclusion).toBe("open");
+ expect(policy?.findings.open).toBe(1);
+ expect(policy?.warnings).toBe(1);
+ expect(policy?.targets).toBe(2);
+ expect(planCheckRow("ghost", runs)?.conclusion).toBe("passed");
+ });
+});
+
+describe("statement report and run rows", () => {
+ test("a report that fails holds the rollout; one that passes has no row", () => {
+ const report = (level: Advice_Level) =>
+ create(PlanCheckRunSchema, {
+ status: PlanCheckRun_Status.DONE,
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ type: PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT,
+ status: level,
+ target: "db1",
+ }),
+ ],
+ });
+ const failing = planCheckRow("report", [report(Advice_Level.ERROR)]);
+ expect(failing?.conclusion).toBe("open");
+ expect(failing?.holdsRollout).toBe(true);
+ expect(failing?.findings.p0).toBe(1);
+ expect(
+ planCheckRow("report", [report(Advice_Level.SUCCESS)])
+ ).toBeUndefined();
+ expect(
+ planCheckRow("report", [report(Advice_Level.WARNING)])?.holdsRollout
+ ).toBe(false);
+ });
+
+ test.each([
+ [PlanCheckRun_Status.FAILED, "failed"],
+ [PlanCheckRun_Status.CANCELED, "failed"],
+ [PlanCheckRun_Status.RUNNING, "running"],
+ [PlanCheckRun_Status.STATUS_UNSPECIFIED, "running"],
+ ] as const)(
+ "a run %s without results holds the rollout as %s",
+ (status, conclusion) => {
+ const row = planCheckRunRow([
+ create(PlanCheckRunSchema, { status, error: "cannot derive targets" }),
+ ]);
+ expect(row?.conclusion).toBe(conclusion);
+ expect(row?.holdsRollout).toBe(true);
+ expect(row?.error).toBe("cannot derive targets");
+ }
+ );
+
+ test("a finished run has no run row", () => {
+ expect(
+ planCheckRunRow([
+ create(PlanCheckRunSchema, { status: PlanCheckRun_Status.DONE }),
+ ])
+ ).toBeUndefined();
+ });
+});
+
+describe("computePlanGates", () => {
+ const issue = (extra: Parameters<typeof create<typeof IssueSchema>>[1]) =>
+ create(IssueSchema, { status: IssueStatus.OPEN, ...extra });
+ const openRule = ruleReviewRow({
+ run: run(ReviewRun_Status.DONE),
+ stale: false,
+ loadFailed: false,
+ findings: findings({ open: 2, p1: 2 }),
+ });
+ const pendingAI = aiReviewRow({
+ run: run(ReviewRun_Status.RUNNING),
+ runFetched: true,
+ findings: NO_FINDINGS,
+ });
+
+ test("a draft waits on submission and its open findings", () => {
+ const gates = computePlanGates({
+ issue: issue({ draft: true }),
+ rows: [openRule, pendingAI],
+ openDiscussions: 0,
+ });
+ expect(gates.map((gate) => gate.kind)).toEqual(["submit", "review"]);
+ });
+
+ test("lists approval, held reviewers, and discussion in order", () => {
+ const gates = computePlanGates({
+ issue: issue({ approvalStatus: ApprovalStatus.PENDING }),
+ currentApprovalRole: "roles/workspaceDBA",
+ rows: [openRule, pendingAI],
+ openDiscussions: 1,
+ });
+ expect(gates).toEqual([
+ { kind: "approval", rejected: false, role: "roles/workspaceDBA" },
+ { kind: "review", row: openRule },
+ { kind: "discussion", open: 1 },
+ ]);
+ });
+
+ test("is empty once every gate passes, or when the issue is closed", () => {
+ expect(
+ computePlanGates({
+ issue: issue({ approvalStatus: ApprovalStatus.SKIPPED }),
+ rows: [pendingAI],
+ openDiscussions: 0,
+ })
+ ).toEqual([]);
+ expect(
+ computePlanGates({
+ issue: issue({ status: IssueStatus.DONE }),
+ rows: [openRule],
+ openDiscussions: 3,
+ })
+ ).toEqual([]);
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/planGates.ts b/frontend/src/routes/project/plan-detail/utils/planGates.ts
new file mode 100644
index 0000000000..00b4c0d3eb
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/planGates.ts
@@ -0,0 +1,379 @@
+// The automated reviewers' conclusions and the gates the automatic rollout
+// waits on, computed once for the Review section, the Deploy waiting list, the
+// header, and the collapsed summaries. Mirrors the server's rollout creator:
+// approval passed, plan checks passed, the rule review done for the current
+// SQL, and no open thread.
+import type { Timestamp } from "@bufbuild/protobuf/wkt";
+import { isThreadRoot } from "@/stores/app/issueComment";
+import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
+import {
+ type Issue,
+ type IssueComment,
+ IssueComment_ReviewMetadata_Priority,
+ IssueComment_ThreadState,
+ type ReviewRun,
+ ReviewRun_Status,
+ ReviewRun_Type,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ type PlanCheckRun,
+ PlanCheckRun_Result_Type,
+ PlanCheckRun_Status,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+
+export type AutomatedReviewer =
+ | "rule"
+ | "ai"
+ | "policy"
+ | "ghost"
+ | "report"
+ | "checks";
+
+export type PlanCheckReviewer = "policy" | "ghost" | "report";
+
+// One conclusion per reviewer. "passed" is a run with no findings;
+// "resolved" a run whose findings people have all resolved.
+export type ReviewConclusion =
+ | "loading"
+ | "not-run"
+ | "running"
+ | "outdated"
+ | "failed"
+ | "open"
+ | "resolved"
+ | "passed";
+
+// A finding's priority as its reviewer gave it: P0 says the SQL is wrong and
+// must change, P1 that a person must accept a real risk, P2 is advice.
+export type FindingPriority = "p0" | "p1" | "p2";
+
+// Where a finding stands: open findings by priority, and the latest run's
+// resolved findings, where a P0 resolved without a change stands apart. A
+// run supersedes and resolves everything its reviewer posted before, so a
+// resolved finding of the latest run was resolved by a person on the
+// current SQL.
+export type FindingSet =
+ | FindingPriority
+ | "overridden"
+ | "resolved"
+ | "earlier";
+
+// What a count or the walker covers: one set, or every open finding.
+export type FindingGroup = FindingSet | "open";
+
+// The number of a reviewer's findings in each set.
+export interface ReviewerFindings extends Record<FindingSet, number> {
+ open: number;
+}
+
+export interface AutomatedReviewRow {
+ reviewer: AutomatedReviewer;
+ conclusion: ReviewConclusion;
+ findings: ReviewerFindings;
+ holdsRollout: boolean;
+ // A failed run's error, or a load failure.
+ error?: string;
+ // When the run the conclusion comes from finished.
+ time?: Timestamp;
+ // Plan check rows: databases the check ran on, and warnings that pass.
+ targets?: number;
+ warnings?: number;
+}
+
+export type PlanGate =
+ | { kind: "submit" }
+ | { kind: "approval"; rejected: boolean; role?: string }
+ | { kind: "review"; row: AutomatedReviewRow }
+ | { kind: "discussion"; open: number };
+
+export const findingPriority = (
+ priority: IssueComment_ReviewMetadata_Priority
+): FindingPriority =>
+ priority === IssueComment_ReviewMetadata_Priority.P0
+ ? "p0"
+ : priority === IssueComment_ReviewMetadata_Priority.P2
+ ? "p2"
+ : "p1";
+
+// The set a reviewer's finding belongs to; undefined for anything else.
+export function findingSetOf(comment: IssueComment): FindingSet | undefined {
+ const review = comment.reviewMetadata;
+ if (!review || !isThreadRoot(comment)) return undefined;
+ const priority = findingPriority(review.priority);
+ if (comment.threadState === IssueComment_ThreadState.OPEN) return priority;
+ if (review.superseded) return "earlier";
+ return priority === "p0" ? "overridden" : "resolved";
+}
+
+export function inFindingGroup(
+ comment: IssueComment,
+ group: FindingGroup
+): boolean {
+ const set = findingSetOf(comment);
+ return group === "open"
+ ? set === "p0" || set === "p1" || set === "p2"
+ : set === group;
+}
+
+// An AI finding names its rule in its text; its first line is the title.
+export const findingTitle = (comment: IssueComment): string =>
+ comment.comment
+ .split("\n", 1)[0]
+ .replace(/^#+\s*/, "")
+ .trim();
+
+export const emptyFindings = (): ReviewerFindings => ({
+ open: 0,
+ p0: 0,
+ p1: 0,
+ p2: 0,
+ overridden: 0,
+ resolved: 0,
+ earlier: 0,
+});
+
+// The latest run's findings people resolved, whatever their priority: what a
+// rerun reopens.
+export const resolvedByPeople = (findings: ReviewerFindings): number =>
+ findings.resolved + findings.overridden;
+
+const runTypeOf: Record<"rule" | "ai", ReviewRun_Type> = {
+ rule: ReviewRun_Type.RULE,
+ ai: ReviewRun_Type.AI,
+};
+
+// Open findings count whatever run posted them, since any open thread holds
+// the rollout; resolved ones count for the latest run only.
+export function countFindings(
+ comments: readonly IssueComment[],
+ reviewer: "rule" | "ai"
+): ReviewerFindings {
+ const runType = runTypeOf[reviewer];
+ const counts = emptyFindings();
+ for (const comment of comments) {
+ if (comment.reviewMetadata?.runType !== runType) continue;
+ const set = findingSetOf(comment);
+ if (!set) continue;
+ counts[set]++;
+ if (set === "p0" || set === "p1" || set === "p2") counts.open++;
+ }
+ return counts;
+}
+
+// Open threads people started, as opposed to findings a reviewer posted.
+export function countOpenDiscussions(comments: readonly IssueComment[]) {
+ return comments.filter(
+ (comment) =>
+ isThreadRoot(comment) &&
+ !comment.reviewMetadata &&
+ comment.threadState === IssueComment_ThreadState.OPEN
+ ).length;
+}
+
+const findingsConclusion = (findings: ReviewerFindings): ReviewConclusion =>
+ findings.open > 0
+ ? "open"
+ : resolvedByPeople(findings) > 0
+ ? "resolved"
+ : "passed";
+
+const runConclusion = (
+ run: ReviewRun,
+ findings: ReviewerFindings
+): ReviewConclusion => {
+ if (run.outdated) return "outdated";
+ switch (run.status) {
+ case ReviewRun_Status.AVAILABLE:
+ case ReviewRun_Status.RUNNING:
+ return "running";
+ case ReviewRun_Status.FAILED:
+ return "failed";
+ case ReviewRun_Status.DONE:
+ return findingsConclusion(findings);
+ default:
+ return "loading";
+ }
+};
+
+// Every state but a finished current run holds the rollout: the server starts
+// a missing or outdated run before it creates the rollout, and waits for it.
+export function ruleReviewRow(input: {
+ run: ReviewRun | null | undefined;
+ stale: boolean;
+ loadFailed: boolean;
+ findings: ReviewerFindings;
+}): AutomatedReviewRow {
+ const { findings, run } = input;
+ let conclusion: ReviewConclusion;
+ if (input.loadFailed) {
+ conclusion = "failed";
+ } else if (run === undefined) {
+ conclusion = "loading";
+ } else if (run === null) {
+ conclusion = "not-run";
+ } else {
+ conclusion = runConclusion(run, findings);
+ // A completion the page has not re-read since the SQL changed, or whose
+ // findings are still being listed, is not a result yet.
+ if (input.stale && conclusion !== "outdated" && conclusion !== "failed") {
+ conclusion = "running";
+ }
+ }
+ return {
+ reviewer: "rule",
+ conclusion,
+ findings,
+ holdsRollout: conclusion !== "passed" && conclusion !== "resolved",
+ error: input.loadFailed ? undefined : (run?.error ?? undefined),
+ time: run?.endTime,
+ };
+}
+
+// A plan with no SQL to review never gets a rule review run, and the server
+// holds nothing for one; a run that exists still counts, since the server
+// restarts a stale run whatever the plan holds.
+export const ruleReviewApplies = (
+ run: ReviewRun | null | undefined,
+ reviewsSQL: boolean
+): boolean => run !== null || reviewsSQL;
+
+// The AI review holds the rollout only through the findings it posts. The
+// page reads its run only while a review can still start, as before a
+// rollout; otherwise the findings alone conclude.
+export function aiReviewRow(input: {
+ run: ReviewRun | null | undefined;
+ runFetched: boolean;
+ findings: ReviewerFindings;
+}): AutomatedReviewRow {
+ const { findings } = input;
+ const run = input.runFetched ? input.run : null;
+ const conclusion =
+ run === undefined
+ ? "loading"
+ : run === null
+ ? findings.open + resolvedByPeople(findings) > 0
+ ? findingsConclusion(findings)
+ : "not-run"
+ : runConclusion(run, findings);
+ return {
+ reviewer: "ai",
+ conclusion,
+ findings,
+ holdsRollout: findings.open > 0,
+ error: run?.error || undefined,
+ time: run?.endTime,
+ };
+}
+
+const PLAN_CHECK_TYPE: Record<PlanCheckReviewer, PlanCheckRun_Result_Type> = {
+ policy: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ ghost: PlanCheckRun_Result_Type.GHOST_SYNC,
+ report: PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT,
+};
+
+// A plan check type's row, from its results: the V1 SQL review on engines the
+// standard rules do not cover, the gh-ost dry run, or the statement report.
+// The server creates no rollout while any result is an ERROR. A report that
+// passes describes the statement rather than judging it, so it has no row.
+// Undefined without a result to show.
+export function planCheckRow(
+ reviewer: PlanCheckReviewer,
+ runs: readonly PlanCheckRun[]
+): AutomatedReviewRow | undefined {
+ const type = PLAN_CHECK_TYPE[reviewer];
+ const results = runs.flatMap((run) =>
+ run.results.filter((result) => result.type === type)
+ );
+ const errors = results.filter(
+ (result) => result.status === Advice_Level.ERROR
+ ).length;
+ const warnings = results.filter(
+ (result) => result.status === Advice_Level.WARNING
+ ).length;
+ if (results.length === 0) return undefined;
+ if (reviewer === "report" && errors === 0 && warnings === 0) return undefined;
+ const conclusion: ReviewConclusion = errors > 0 ? "open" : "passed";
+ return {
+ reviewer,
+ conclusion,
+ findings: { ...emptyFindings(), open: errors, p0: errors },
+ holdsRollout: errors > 0,
+ time: runs[0]?.createTime,
+ targets: new Set(results.map((result) => result.target)).size,
+ warnings,
+ };
+}
+
+// The plan check run while it has no results to show: queued, running, or
+// stopped before producing any, as when its targets cannot be derived. The
+// server creates the rollout only once the current run is DONE.
+export function planCheckRunRow(
+ runs: readonly PlanCheckRun[]
+): AutomatedReviewRow | undefined {
+ const run = runs.find(
+ (candidate) =>
+ candidate.status !== PlanCheckRun_Status.DONE &&
+ candidate.results.length === 0
+ );
+ if (!run) return undefined;
+ const stopped =
+ run.status === PlanCheckRun_Status.FAILED ||
+ run.status === PlanCheckRun_Status.CANCELED;
+ return {
+ reviewer: "checks",
+ conclusion: stopped ? "failed" : "running",
+ findings: emptyFindings(),
+ holdsRollout: true,
+ error: run.error || undefined,
+ time: run.createTime,
+ };
+}
+
+// A P0 resolved without a change does not hold the rollout, but an approver
+// should look at it.
+export const rowNeedsAttention = (row: AutomatedReviewRow): boolean =>
+ row.conclusion === "open" ||
+ row.conclusion === "failed" ||
+ row.conclusion === "outdated" ||
+ row.conclusion === "not-run" ||
+ row.findings.overridden > 0;
+
+const approvalPassed = (
+ issue: Pick<Issue, "approvalStatus" | "approvalTemplate">
+) =>
+ issue.approvalStatus === ApprovalStatus.APPROVED ||
+ issue.approvalStatus === ApprovalStatus.SKIPPED ||
+ issue.approvalTemplate?.flow?.roles.length === 0;
+
+// What the automatic rollout still waits on, in the order a reader acts on
+// it. Empty once every gate passes.
+export function computePlanGates(input: {
+ issue: Pick<
+ Issue,
+ "draft" | "status" | "approvalStatus" | "approvalTemplate"
+ >;
+ currentApprovalRole?: string;
+ rows: readonly AutomatedReviewRow[];
+ openDiscussions: number;
+}): PlanGate[] {
+ const { issue } = input;
+ if (issue.status !== IssueStatus.OPEN) return [];
+ const gates: PlanGate[] = [];
+ if (issue.draft) {
+ gates.push({ kind: "submit" });
+ } else if (!approvalPassed(issue)) {
+ gates.push({
+ kind: "approval",
+ rejected: issue.approvalStatus === ApprovalStatus.REJECTED,
+ role: input.currentApprovalRole,
+ });
+ }
+ for (const row of input.rows) {
+ if (row.holdsRollout) gates.push({ kind: "review", row });
+ }
+ if (input.openDiscussions > 0) {
+ gates.push({ kind: "discussion", open: input.openDiscussions });
+ }
+ return gates;
+}
diff --git a/frontend/src/routes/project/plan-detail/utils/reviewLabels.ts b/frontend/src/routes/project/plan-detail/utils/reviewLabels.ts
new file mode 100644
index 0000000000..a5ca00eb0d
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/reviewLabels.ts
@@ -0,0 +1,122 @@
+import type {
+ AutomatedReviewer,
+ AutomatedReviewRow,
+ FindingGroup,
+ FindingPriority,
+} from "./planGates";
+
+type T = (key: string, options?: Record<string, unknown>) => string;
+
+export const reviewerLabel = (t: T, reviewer: AutomatedReviewer): string => {
+ switch (reviewer) {
+ case "rule":
+ return t("sql-review.standard-rules.self");
+ case "ai":
+ return t("sql-review.ai-review.self");
+ case "policy":
+ return t("plan.automated-review.policy");
+ case "ghost":
+ return t("plan.automated-review.ghost");
+ case "report":
+ return t("plan.automated-review.report");
+ case "checks":
+ return t("plan.automated-review.checks");
+ }
+};
+
+export const findingGroupLabel = (t: T, group: FindingGroup): string => {
+ switch (group) {
+ case "p0":
+ case "p1":
+ case "p2":
+ return group.toUpperCase();
+ case "open":
+ return t("plan.findings.set.open");
+ case "overridden":
+ return t("plan.findings.set.overridden");
+ case "resolved":
+ return t("plan.findings.set.resolved");
+ case "earlier":
+ return t("plan.findings.set.earlier");
+ }
+};
+
+export const isPlanCheckRow = (row: AutomatedReviewRow): boolean =>
+ row.reviewer !== "rule" && row.reviewer !== "ai";
+
+const PRIORITIES: readonly FindingPriority[] = ["p0", "p1", "p2"];
+
+// A reviewer's open findings, P0 first: "1 P0, 2 P1". A plan check reports
+// errors rather than priorities.
+export const openFindingsLabel = (t: T, row: AutomatedReviewRow): string =>
+ isPlanCheckRow(row)
+ ? t("plan.automated-review.n-errors", { count: row.findings.open })
+ : PRIORITIES.filter((priority) => row.findings[priority] > 0)
+ .map((priority) =>
+ t("plan.findings.n-priority", {
+ count: row.findings[priority],
+ priority: priority.toUpperCase(),
+ })
+ )
+ .join(t("plan.findings.separator"));
+
+// A held reviewer as a line of what the rollout waits on.
+export const reviewGateLabel = (t: T, row: AutomatedReviewRow): string => {
+ const reviewer = reviewerLabel(t, row.reviewer);
+ switch (row.conclusion) {
+ case "open":
+ return t("plan.deploy-waiting.reviewer-findings", {
+ reviewer,
+ findings: openFindingsLabel(t, row),
+ });
+ case "failed":
+ return t("plan.deploy-waiting.reviewer-failed", { reviewer });
+ case "outdated":
+ return t("plan.deploy-waiting.reviewer-outdated", { reviewer });
+ case "not-run":
+ return t("plan.deploy-waiting.reviewer-not-run", { reviewer });
+ default:
+ return t("plan.deploy-waiting.reviewer-running", { reviewer });
+ }
+};
+
+// A reviewer's conclusion in a collapsed summary, saying what people decided
+// about its findings: "Standard rules: 2 resolved, 1 P0 resolved without a
+// change".
+export const reviewSummaryPart = (t: T, row: AutomatedReviewRow): string => {
+ const reviewer = reviewerLabel(t, row.reviewer);
+ const { findings } = row;
+ let status: string;
+ switch (row.conclusion) {
+ case "open":
+ status = openFindingsLabel(t, row);
+ break;
+ case "resolved":
+ status = [
+ findings.resolved > 0
+ ? t("plan.findings.n-resolved", { count: findings.resolved })
+ : "",
+ findings.overridden > 0
+ ? t("plan.findings.n-overridden", { count: findings.overridden })
+ : "",
+ ]
+ .filter(Boolean)
+ .join(t("plan.findings.separator"));
+ break;
+ case "passed":
+ status = t("plan.automated-review.passed");
+ break;
+ case "failed":
+ status = t("plan.automated-review.failed");
+ break;
+ case "outdated":
+ status = t("plan.automated-review.out-of-date");
+ break;
+ case "not-run":
+ status = t("plan.automated-review.not-run");
+ break;
+ default:
+ status = t("plan.automated-review.running");
+ }
+ return t("plan.automated-review.summary-part", { reviewer, status });
+};
diff --git a/frontend/src/routes/project/plan-detail/utils/reviewScope.test.ts b/frontend/src/routes/project/plan-detail/utils/reviewScope.test.ts
new file mode 100644
index 0000000000..4a43ff261a
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/reviewScope.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { reviewScope } from "./reviewScope";
+
+const db = (name: string) => `instances/i/databases/${name}`;
+const GROUP = "projects/p/databaseGroups/g";
+const engines: Record<string, Engine> = {
+ [db("pg1")]: Engine.POSTGRES,
+ [db("pg2")]: Engine.POSTGRES,
+ [db("bq")]: Engine.BIGQUERY,
+};
+
+const plan = (...specs: string[][]) =>
+ create(PlanSchema, {
+ specs: specs.map((targets, index) => ({
+ id: `spec-${index}`,
+ config: {
+ case: "changeDatabaseConfig" as const,
+ value: create(Plan_ChangeDatabaseConfigSchema, { targets }),
+ },
+ })),
+ });
+
+const scope = (
+ reviewer: "rule" | "ai",
+ input: ReturnType<typeof plan>,
+ sampleSize = 0,
+ matched: Record<string, string[]> = {}
+) =>
+ reviewScope(input, {
+ reviewer,
+ sampleSize,
+ matchedDatabases: (group) => matched[group],
+ engineOf: (database) => engines[database],
+ });
+
+describe("reviewScope", () => {
+ test("the rule review covers its engines and leaves the rest to the review policy", () => {
+ expect(scope("rule", plan([db("pg1"), db("bq")]))).toEqual({
+ databases: [db("pg1")],
+ engines: [Engine.POSTGRES],
+ total: 1,
+ });
+ });
+
+ test("the AI review takes the first targets of each spec when it samples", () => {
+ const result = scope("ai", plan([db("pg1"), db("pg2"), db("bq")]), 1);
+ expect(result.databases).toEqual([db("pg1")]);
+ expect(result.total).toBe(3);
+ });
+
+ test("a group counts its matched databases once loaded, and dedupes across specs", () => {
+ const input = plan([GROUP], [db("pg1")]);
+ expect(scope("rule", input).databases).toEqual([db("pg1")]);
+ expect(
+ scope("rule", input, 0, { [GROUP]: [db("pg1"), db("pg2")] }).databases
+ ).toEqual([db("pg1"), db("pg2")]);
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/reviewScope.ts b/frontend/src/routes/project/plan-detail/utils/reviewScope.ts
new file mode 100644
index 0000000000..742c09baee
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/reviewScope.ts
@@ -0,0 +1,78 @@
+import { isValidDatabaseGroupName } from "@/types/dbGroup";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+
+// Engines the standard rule review covers. Mirrors reviewFuncs in
+// backend/runner/reviewrun/review_funcs.go; a target on any other engine is
+// reviewed by the plan checks' review policy instead.
+const RULE_REVIEW_ENGINES: ReadonlySet<Engine> = new Set([
+ Engine.POSTGRES,
+ Engine.MYSQL,
+ Engine.OCEANBASE,
+ Engine.MARIADB,
+ Engine.TIDB,
+ Engine.MSSQL,
+ Engine.ORACLE,
+ Engine.SNOWFLAKE,
+]);
+
+export interface ReviewScope {
+ // The databases the reviewer reviews, in plan order.
+ databases: string[];
+ engines: Engine[];
+ // The databases it could have reviewed; more than `databases` when the AI
+ // review samples.
+ total: number;
+}
+
+// What a reviewer reviews. The rule review takes every target on an engine
+// it covers. The AI review takes the first `sampleSize` targets of each
+// spec, or every target when the size is zero. A group's targets are its
+// matched databases once loaded.
+export function reviewScope(
+ plan: Pick<Plan, "specs">,
+ options: {
+ reviewer: "rule" | "ai";
+ sampleSize: number;
+ matchedDatabases: (group: string) => string[] | undefined;
+ engineOf: (database: string) => Engine | undefined;
+ }
+): ReviewScope {
+ const reviewed = new Set<string>();
+ const candidates = new Set<string>();
+ for (const spec of plan.specs) {
+ if (
+ spec.config.case !== "changeDatabaseConfig" ||
+ spec.config.value.release
+ ) {
+ continue;
+ }
+ const targets = spec.config.value.targets.flatMap((target) =>
+ isValidDatabaseGroupName(target)
+ ? (options.matchedDatabases(target) ?? [])
+ : [target]
+ );
+ const eligible =
+ options.reviewer === "rule"
+ ? targets.filter((database) => {
+ const engine = options.engineOf(database);
+ return engine === undefined || RULE_REVIEW_ENGINES.has(engine);
+ })
+ : targets;
+ for (const database of eligible) candidates.add(database);
+ const sampled =
+ options.reviewer === "ai" && options.sampleSize > 0
+ ? eligible.slice(0, options.sampleSize)
+ : eligible;
+ for (const database of sampled) reviewed.add(database);
+ }
+ const databases = [...reviewed];
+ const engines = [
+ ...new Set(
+ databases
+ .map((database) => options.engineOf(database))
+ .filter((engine): engine is Engine => engine !== undefined)
+ ),
+ ];
+ return { databases, engines, total: candidates.size };
+}
diff --git a/frontend/src/routes/project/plan-detail/utils/statementSummary.test.ts b/frontend/src/routes/project/plan-detail/utils/statementSummary.test.ts
new file mode 100644
index 0000000000..ffc14525b5
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/statementSummary.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment node
+import { create } from "@bufbuild/protobuf";
+import { expect, test } from "vitest";
+import { StatementType } from "@/types/proto-es/v1/common_pb";
+import {
+ PlanCheckRun_Result_SqlSummaryReportSchema,
+ PlanCheckRun_Result_Type,
+ PlanCheckRun_ResultSchema,
+ PlanCheckRunSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { statementSummary } from "./statementSummary";
+
+const report = (types: StatementType[], affectedRows: bigint) =>
+ create(PlanCheckRun_ResultSchema, {
+ type: PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT,
+ report: {
+ case: "sqlSummaryReport",
+ value: create(PlanCheckRun_Result_SqlSummaryReportSchema, {
+ statementTypes: types,
+ affectedRows,
+ }),
+ },
+ });
+
+test("summarizes the statement kinds and the most rows a target affects", () => {
+ const types = [
+ StatementType.DELETE,
+ StatementType.ALTER_TABLE,
+ StatementType.UPDATE,
+ StatementType.ALTER_TABLE,
+ ];
+ const summary = statementSummary([
+ create(PlanCheckRunSchema, {
+ results: [report(types, 600n), report(types, 900n)],
+ }),
+ ]);
+ expect(summary).toEqual({
+ types: ["DELETE", "ALTER TABLE", "UPDATE"],
+ affectedRows: 900n,
+ });
+});
+
+test("is undefined without a summary report", () => {
+ expect(
+ statementSummary([
+ create(PlanCheckRunSchema, {
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ ],
+ }),
+ ])
+ ).toBeUndefined();
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/statementSummary.ts b/frontend/src/routes/project/plan-detail/utils/statementSummary.ts
new file mode 100644
index 0000000000..b97e7bc8ed
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/statementSummary.ts
@@ -0,0 +1,44 @@
+import { StatementType } from "@/types/proto-es/v1/common_pb";
+import {
+ type PlanCheckRun,
+ PlanCheckRun_Result_Type,
+} from "@/types/proto-es/v1/plan_service_pb";
+
+export interface StatementSummary {
+ // Distinct statement kinds in order of first appearance: "ALTER TABLE".
+ // Some engines' reports list each kind once, so their number is not a
+ // statement count.
+ types: string[];
+ // The most rows any target expects the change to affect.
+ affectedRows: bigint;
+}
+
+// What the statement summary report says about a spec's SQL. The report
+// describes the statement rather than judging it, so it belongs beside the
+// statement, not among the reviewers. Undefined until a report exists.
+export function statementSummary(
+ runs: readonly PlanCheckRun[]
+): StatementSummary | undefined {
+ const reports = runs.flatMap((run) =>
+ run.results.flatMap((result) =>
+ result.type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT &&
+ result.report.case === "sqlSummaryReport"
+ ? [result.report.value]
+ : []
+ )
+ );
+ if (reports.length === 0) return undefined;
+ const first = reports[0];
+ const types = [
+ ...new Set(
+ first.statementTypes.map((type) =>
+ (StatementType[type] ?? "").replaceAll("_", " ")
+ )
+ ),
+ ].filter(Boolean);
+ const affectedRows = reports.reduce(
+ (max, report) => (report.affectedRows > max ? report.affectedRows : max),
+ 0n
+ );
+ return { types, affectedRows };
+}