Skip to content

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

refactor(react): unify plan-check display surfaces (BYT-9486) (#20305)

boojacka591093cbd34
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index c1d4fff924..0044f65f33 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2708,12 +2708,10 @@
"description": "Estimated by statistical information.",
"self": "Affected rows"
},
- "ghost-sync": "gh-ost sync",
"sql-review": {
"description": "Analyze the SQL statement for potential issues and provide recommendations. Includes built-in rules and your custom rules.",
"self": "SQL review"
- },
- "summary-report": "Summary report"
+ }
},
"checking": "Checking...",
"created": "Created",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a81ece52c4..c5d643d3a1 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2708,12 +2708,10 @@
"description": "Estimado por información estadística.",
"self": "Filas afectadas"
},
- "ghost-sync": "Sincronización gh-ost",
"sql-review": {
"description": "Analice la sentencia SQL para detectar posibles problemas y proporcione recomendaciones. Incluye reglas integradas y sus reglas personalizadas.",
"self": "Revisión de SQL"
- },
- "summary-report": "Informe resumido"
+ }
},
"checking": "Comprobando...",
"created": "Creado",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index c3c70e1b05..701a241efe 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2708,12 +2708,10 @@
"description": "統計情報から推定。",
"self": "影響を受ける行"
},
- "ghost-sync": "gh-ost同期",
"sql-review": {
"description": "SQL文を分析し、潜在的な問題点を特定し、推奨事項を提示します。組み込みルールとカスタムルールが含まれます。",
"self": "SQL レビュー"
- },
- "summary-report": "概略報告"
+ }
},
"checking": "検査中…",
"created": "内蔵",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 7559709a63..00fb94de24 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2708,12 +2708,10 @@
"description": "Ước tính theo thông tin thống kê.",
"self": "Số dòng bị ảnh hưởng"
},
- "ghost-sync": "Đồng bộ gh-ost",
"sql-review": {
"description": "Phân tích câu lệnh SQL để tìm ra các vấn đề tiềm ẩn và đưa ra khuyến nghị. Bao gồm các quy tắc tích hợp sẵn và quy tắc tùy chỉnh của bạn.",
"self": "Đánh giá SQL"
- },
- "summary-report": "Báo cáo tổng hợp"
+ }
},
"checking": "Đang kiểm tra...",
"created": "Đã tạo",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 0b44b9e37f..dad873aeb3 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2708,12 +2708,10 @@
"description": "根据统计信息估算。",
"self": "影响行数"
},
- "ghost-sync": "gh-ost 同步",
"sql-review": {
"description": "分析 SQL 语句中的潜在问题并提供建议。包括内置规则以及您的自定义规则。",
"self": "SQL 审核"
- },
- "summary-report": "概要报告"
+ }
},
"checking": "检查中…",
"created": "创建于",
diff --git a/frontend/src/react/components/plan-check/PlanCheckSection.tsx b/frontend/src/react/components/plan-check/PlanCheckSection.tsx
new file mode 100644
index 0000000000..41aa470e0e
--- /dev/null
+++ b/frontend/src/react/components/plan-check/PlanCheckSection.tsx
@@ -0,0 +1,544 @@
+import {
+ AlertCircle,
+ CheckCircle,
+ CircleQuestionMark,
+ FileCode,
+ Loader2,
+ Play,
+ SearchCode,
+ Shield,
+ XCircle,
+} from "lucide-react";
+import { type ReactNode, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import {
+ getFilteredResultGroups,
+ getPlanCheckSummary,
+ type PlanCheckSummary,
+} from "@/react/pages/project/plan-detail/utils/planCheck";
+import {
+ getDateForPbTimestampProtoEs,
+ getRuleLocalization,
+ ruleTemplateMapV2,
+ ruleTypeToString,
+} from "@/types";
+import {
+ type PlanCheckRun,
+ type PlanCheckRun_Result,
+ PlanCheckRun_Result_Type,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { SQLReviewRule_Type } from "@/types/proto-es/v1/review_config_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+import { extractDatabaseResourceName } from "@/utils/v1/database";
+
+const PAGE_SIZE = 10;
+
+interface PlanCheckSectionProps {
+ planCheckRuns: PlanCheckRun[];
+ // When provided, the section uses this summary instead of computing one
+ // from planCheckRuns. Issue-detail uses this to fall back to
+ // plan.planCheckRunStatusCount when planCheckRuns are not yet loaded.
+ summaryOverride?: PlanCheckSummary;
+ canRun: boolean;
+ isRunning: boolean;
+ runDisabled?: boolean;
+ onRun: () => void | Promise<void>;
+ // Called when the drawer opens; should refresh runs and return the latest.
+ // Return value replaces what the drawer renders.
+ onRefreshOnOpen?: () => Promise<PlanCheckRun[]>;
+ // Optional trailing element rendered after status counts (e.g. affected rows).
+ trailingSummary?: ReactNode;
+ // If true, FAILED check runs without results render as a synthetic error
+ // group. Used by plan-detail regular checks.
+ includeRunFailure?: boolean;
+ // Section heading style; defaults to uppercase.
+ headingClassName?: string;
+}
+
+export function PlanCheckSection({
+ planCheckRuns,
+ summaryOverride,
+ canRun,
+ isRunning,
+ runDisabled,
+ onRun,
+ onRefreshOnOpen,
+ trailingSummary,
+ includeRunFailure = false,
+ headingClassName = "textlabel uppercase",
+}: PlanCheckSectionProps) {
+ const { t } = useTranslation();
+ const [drawerOpen, setDrawerOpen] = useState(false);
+
+ const summary = useMemo(
+ () => summaryOverride ?? getPlanCheckSummary(planCheckRuns),
+ [summaryOverride, planCheckRuns]
+ );
+ const hasAnyChecks = summary.total > 0;
+
+ return (
+ <div className="flex flex-col gap-y-1">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className={headingClassName}>{t("plan.checks.self")}</h3>
+ {canRun && (
+ <Button
+ disabled={isRunning || runDisabled}
+ onClick={() => void onRun()}
+ size="xs"
+ variant="outline"
+ >
+ <Play className="h-3.5 w-3.5" />
+ {t("plan.run")}
+ </Button>
+ )}
+ </div>
+
+ {hasAnyChecks ? (
+ <div className="flex min-w-0 flex-wrap items-center gap-3">
+ <button
+ aria-label={t("plan.navigator.checks")}
+ className="cursor-pointer text-left"
+ onClick={() => setDrawerOpen(true)}
+ type="button"
+ >
+ <PlanCheckSummaryRow summary={summary} />
+ </button>
+ {trailingSummary}
+ </div>
+ ) : (
+ <span className="text-sm text-control-placeholder">
+ {t("plan.overview.no-checks")}
+ </span>
+ )}
+
+ <PlanCheckResultsDrawer
+ includeRunFailure={includeRunFailure}
+ onOpenChange={setDrawerOpen}
+ onRefreshOnOpen={onRefreshOnOpen}
+ open={drawerOpen}
+ planCheckRuns={planCheckRuns}
+ />
+ </div>
+ );
+}
+
+type StatusEntry = {
+ count: number;
+ icon: typeof XCircle;
+ label: string;
+ status: Advice_Level;
+ textClass: string;
+};
+
+function getStatusEntries(
+ summary: PlanCheckSummary,
+ t: ReturnType<typeof useTranslation>["t"]
+): StatusEntry[] {
+ return [
+ {
+ count: summary.error,
+ icon: XCircle,
+ label: t("common.error"),
+ status: Advice_Level.ERROR,
+ textClass: "text-error",
+ },
+ {
+ count: summary.warning,
+ icon: AlertCircle,
+ label: t("common.warning"),
+ status: Advice_Level.WARNING,
+ textClass: "text-warning",
+ },
+ {
+ count: summary.success,
+ icon: CheckCircle,
+ label: t("common.success"),
+ status: Advice_Level.SUCCESS,
+ textClass: "text-success",
+ },
+ ].filter((entry) => entry.count > 0);
+}
+
+function PlanCheckSummaryRow({ summary }: { summary: PlanCheckSummary }) {
+ const { t } = useTranslation();
+ const entries = getStatusEntries(summary, t);
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-3 text-sm">
+ {summary.running > 0 && (
+ <span className="flex items-center gap-1 text-control">
+ <Loader2 className="size-4 animate-spin" />
+ <span>{t("common.running")}</span>
+ <span>{summary.running}</span>
+ </span>
+ )}
+ {entries.map(({ count, icon: Icon, label, status, textClass }) => (
+ <span className={cn("flex items-center gap-1", textClass)} key={status}>
+ <Icon className="size-4" />
+ <span>{label}</span>
+ <span>{count}</span>
+ </span>
+ ))}
+ </div>
+ );
+}
+
+function PlanCheckFilterPills({
+ onSelect,
+ selectedStatus,
+ summary,
+}: {
+ onSelect: (status: Advice_Level | undefined) => void;
+ selectedStatus?: Advice_Level;
+ summary: PlanCheckSummary;
+}) {
+ const { t } = useTranslation();
+ const entries = getStatusEntries(summary, t);
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-2 text-sm">
+ {summary.running > 0 && (
+ <div className="flex items-center gap-1 px-2 py-1 text-control">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ <span>{t("common.running")}</span>
+ </div>
+ )}
+ {entries.map(({ count, icon: Icon, label, status, textClass }) => {
+ const isSelected = selectedStatus === status;
+ return (
+ <button
+ className={cn(
+ "flex cursor-pointer items-center gap-1 rounded-lg px-2 py-1 transition-colors",
+ textClass,
+ isSelected ? "bg-gray-100" : "hover:bg-gray-100"
+ )}
+ key={status}
+ onClick={() => onSelect(isSelected ? undefined : status)}
+ type="button"
+ >
+ <Icon className="h-5 w-5" />
+ <span>{label}</span>
+ <span>{count}</span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+interface PlanCheckResultsDrawerProps {
+ open: boolean;
+ onOpenChange: (next: boolean) => void;
+ planCheckRuns: PlanCheckRun[];
+ onRefreshOnOpen?: () => Promise<PlanCheckRun[]>;
+ includeRunFailure?: boolean;
+}
+
+export function PlanCheckResultsDrawer({
+ open,
+ onOpenChange,
+ planCheckRuns,
+ onRefreshOnOpen,
+ includeRunFailure = false,
+}: PlanCheckResultsDrawerProps) {
+ const { t } = useTranslation();
+ const [selectedStatus, setSelectedStatus] = useState<
+ Advice_Level | undefined
+ >(undefined);
+ const [displayCount, setDisplayCount] = useState(PAGE_SIZE);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ setSelectedStatus(undefined);
+ setDisplayCount(PAGE_SIZE);
+ if (!onRefreshOnOpen) return;
+ let canceled = false;
+ const refresh = async () => {
+ try {
+ setIsRefreshing(true);
+ await onRefreshOnOpen();
+ } finally {
+ if (!canceled) setIsRefreshing(false);
+ }
+ };
+ void refresh();
+ return () => {
+ canceled = true;
+ };
+ }, [open, onRefreshOnOpen]);
+
+ useEffect(() => {
+ setDisplayCount(PAGE_SIZE);
+ }, [selectedStatus]);
+
+ const summary = useMemo(
+ () => getPlanCheckSummary(planCheckRuns),
+ [planCheckRuns]
+ );
+ const filteredResultGroups = useMemo(
+ () =>
+ getFilteredResultGroups({
+ includeRunFailure,
+ planCheckRuns,
+ runFailureContent: t("common.failed"),
+ runFailureTitle: t("common.failed"),
+ selectedStatus,
+ }),
+ [includeRunFailure, planCheckRuns, selectedStatus, t]
+ );
+ const displayedResultGroups = filteredResultGroups.slice(0, displayCount);
+ const remainingCount = Math.max(
+ filteredResultGroups.length - displayCount,
+ 0
+ );
+
+ return (
+ <Sheet onOpenChange={onOpenChange} open={open}>
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>{t("plan.navigator.checks")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ {summary.total > 0 && (
+ <PlanCheckFilterPills
+ onSelect={setSelectedStatus}
+ selectedStatus={selectedStatus}
+ summary={summary}
+ />
+ )}
+ {isRefreshing && filteredResultGroups.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-control-light">
+ <Loader2 className="mb-4 h-12 w-12 animate-spin opacity-50" />
+ </div>
+ ) : filteredResultGroups.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-control-light">
+ <CheckCircle className="mb-4 h-12 w-12 opacity-50" />
+ <div className="text-lg">
+ {selectedStatus !== undefined
+ ? t("plan.checks.no-results-match-filters")
+ : t("plan.checks.no-check-results")}
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="divide-y">
+ {displayedResultGroups.map((group) => {
+ const description = getCheckTypeDescription(group.type, t);
+ return (
+ <div className="px-2 py-4" key={group.key}>
+ <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
+ <div className="flex items-center gap-3">
+ <CheckTypeIcon type={group.type} />
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">
+ {getCheckTypeLabel(group.type, t)}
+ </span>
+ {description && (
+ <Tooltip content={description}>
+ <CircleQuestionMark className="h-4 w-4 text-control-light" />
+ </Tooltip>
+ )}
+ {group.createTime && (
+ <span className="text-xs text-control-light">
+ {getDateForPbTimestampProtoEs(
+ group.createTime
+ )?.toLocaleString() ?? ""}
+ </span>
+ )}
+ </div>
+ </div>
+ {group.target && (
+ <div className="min-w-0 max-w-[50%] truncate text-sm text-control-light">
+ {formatCheckTarget(group.target)}
+ </div>
+ )}
+ </div>
+ <div className="flex flex-col gap-y-2 pl-8">
+ {group.results.map((result, index) => (
+ <PlanCheckResultCard
+ key={`${group.key}-${index}`}
+ result={result}
+ />
+ ))}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ {remainingCount > 0 && (
+ <div className="flex justify-center py-4">
+ <button
+ className="cursor-pointer text-sm text-accent hover:underline"
+ onClick={() =>
+ setDisplayCount((count) => count + PAGE_SIZE)
+ }
+ type="button"
+ >
+ {t("common.load-more")} ({remainingCount})
+ </button>
+ </div>
+ )}
+ </>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+export function PlanCheckResultCard({
+ result,
+}: {
+ result: PlanCheckRun_Result;
+}) {
+ const { t } = useTranslation();
+ const position =
+ result.report?.case === "sqlReviewReport"
+ ? result.report.value.startPosition
+ : undefined;
+ const affectedRows =
+ result.report?.case === "sqlSummaryReport"
+ ? result.report.value.affectedRows
+ : undefined;
+ const displayTitle = useMemo(
+ () => resolveResultTitle(result.title, result.code, result.report?.case),
+ [result.title, result.code, result.report?.case]
+ );
+
+ return (
+ <div className="flex items-start gap-3 rounded-lg border border-control-border bg-control-bg px-3 py-2">
+ <div className="mt-0.5 shrink-0">{statusIcon(result.status)}</div>
+ <div className="flex min-w-0 flex-1 flex-col gap-y-1">
+ <div className="text-sm font-medium text-main">{displayTitle}</div>
+ {result.content && (
+ <div className="text-sm text-control">{result.content}</div>
+ )}
+ {position && (position.line > 0 || position.column > 0) && (
+ <div className="mt-1 text-sm text-control-light">
+ {position.line > 0 ? `${t("common.line")} ${position.line}` : ""}
+ {position.line > 0 && position.column > 0 ? ", " : ""}
+ {position.column > 0
+ ? `${t("common.column")} ${position.column}`
+ : ""}
+ </div>
+ )}
+ {affectedRows !== undefined && (
+ <div className="mt-1 flex items-center gap-1 text-sm">
+ <span className="inline-flex items-center rounded-full bg-white px-2 py-0.5 text-xs text-control">
+ {t("task.check-type.affected-rows.self")}
+ </span>
+ <span>{String(affectedRows)}</span>
+ <span className="text-control opacity-80">
+ ({t("task.check-type.affected-rows.description")})
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function CheckTypeIcon({
+ className,
+ type,
+}: {
+ className?: string;
+ type: PlanCheckRun_Result_Type;
+}) {
+ const Icon =
+ type === PlanCheckRun_Result_Type.STATEMENT_ADVISE
+ ? SearchCode
+ : type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT
+ ? FileCode
+ : type === PlanCheckRun_Result_Type.GHOST_SYNC
+ ? Shield
+ : FileCode;
+ return <Icon className={cn("h-5 w-5 text-control-light", className)} />;
+}
+
+function getCheckTypeLabel(
+ type: PlanCheckRun_Result_Type,
+ t: ReturnType<typeof useTranslation>["t"]
+) {
+ if (type === PlanCheckRun_Result_Type.STATEMENT_ADVISE) {
+ return t("task.check-type.sql-review.self");
+ }
+ if (type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT) {
+ return t("task.check-type.affected-rows.self");
+ }
+ if (type === PlanCheckRun_Result_Type.GHOST_SYNC) {
+ return t("task.online-migration.self");
+ }
+ return t("plan.navigator.checks");
+}
+
+function getCheckTypeDescription(
+ type: PlanCheckRun_Result_Type,
+ t: ReturnType<typeof useTranslation>["t"]
+) {
+ if (type === PlanCheckRun_Result_Type.STATEMENT_ADVISE) {
+ return t("task.check-type.sql-review.description");
+ }
+ if (type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT) {
+ return t("task.check-type.affected-rows.description");
+ }
+ return "";
+}
+
+function statusIcon(status: Advice_Level) {
+ if (status === Advice_Level.ERROR) {
+ return <XCircle className="h-4 w-4 text-error" />;
+ }
+ if (status === Advice_Level.WARNING) {
+ return <AlertCircle className="h-4 w-4 text-warning" />;
+ }
+ return <CheckCircle className="h-4 w-4 text-success" />;
+}
+
+function formatCheckTarget(target: string): string {
+ if (!target) return "";
+ try {
+ return extractDatabaseResourceName(target).databaseName;
+ } catch {
+ return target;
+ }
+}
+
+// Resolves SQL-review rule codes to their localized rule titles. Non-SQL-review
+// results pass through unchanged. Mirrors what was previously duplicated inside
+// IssueDetailChecks so all surfaces get localized titles.
+function resolveResultTitle(
+ title: string,
+ code: number,
+ reportCase: PlanCheckRun_Result["report"]["case"]
+): string {
+ const withCode = (message: string) =>
+ code !== 0 ? `${message} #${code}` : message;
+ if (title === "OK" || title === "Syntax error") return withCode(title);
+ if (reportCase !== "sqlReviewReport") return title;
+ if (!code) return title;
+ const typeKey = title as keyof typeof SQLReviewRule_Type;
+ const typeEnum = SQLReviewRule_Type[typeKey];
+ if (typeEnum !== undefined) {
+ for (const mapByType of ruleTemplateMapV2.values()) {
+ const rule = mapByType.get(typeEnum);
+ if (rule) {
+ return withCode(
+ getRuleLocalization(ruleTypeToString(rule.type), rule.engine).title
+ );
+ }
+ }
+ } else if (title.startsWith("builtin.")) {
+ return withCode(getRuleLocalization(title).title);
+ }
+ return withCode(title);
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index d45c62d442..8f675602e1 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -3782,10 +3782,8 @@
"task.affected-rows": "Affected rows",
"task.check-type.affected-rows.description": "Estimated by statistical information.",
"task.check-type.affected-rows.self": "Affected rows",
- "task.check-type.ghost-sync": "gh-ost sync",
"task.check-type.sql-review.description": "Analyze the SQL statement for potential issues and provide recommendations. Includes built-in rules and your custom rules.",
"task.check-type.sql-review.self": "SQL review",
- "task.check-type.summary-report": "Summary report",
"task.executed-by": "Executed by",
"task.no-cancelable-tasks": "No cancelable tasks",
"task.no-runnable-tasks": "No runnable tasks",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 2a29728dff..79401edf1c 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -3770,10 +3770,8 @@
"task.affected-rows": "Filas afectadas",
"task.check-type.affected-rows.description": "Estimado por información estadística.",
"task.check-type.affected-rows.self": "Filas afectadas",
- "task.check-type.ghost-sync": "gh-ost sync",
"task.check-type.sql-review.description": "Analyze the SQL statement for potential issues and provide recommendations. Includes built-in rules and your custom rules.",
"task.check-type.sql-review.self": "SQL review",
- "task.check-type.summary-report": "Summary report",
"task.executed-by": "Ejecutado por",
"task.no-cancelable-tasks": "No hay tareas cancelables",
"task.no-runnable-tasks": "No hay tareas ejecutables",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 36edf7761e..e79981ce40 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -3770,10 +3770,8 @@
"task.affected-rows": "影響を受けた行数",
"task.check-type.affected-rows.description": "統計情報に基づく推定です。",
"task.check-type.affected-rows.self": "影響行数",
- "task.check-type.ghost-sync": "gh-ost sync",
"task.check-type.sql-review.description": "Analyze the SQL statement for potential issues and provide recommendations. Includes built-in rules and your custom rules.",
"task.check-type.sql-review.self": "SQL review",
- "task.check-type.summary-report": "Summary report",
"task.executed-by": "実行者",
"task.no-cancelable-tasks": "キャンセル可能なタスクはありません",
"task.no-runnable-tasks": "実行可能なタスクはありません",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 107ca9f2de..278f3e10fe 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -3770,10 +3770,8 @@
"task.affected-rows": "Hàng bị ảnh hưởng",
"task.check-type.affected-rows.description": "Ước tính theo thông tin thống kê.",
"task.check-type.affected-rows.self": "Số dòng bị ảnh hưởng",
- "task.check-type.ghost-sync": "gh-ost sync",
"task.check-type.sql-review.description": "Analyze the SQL statement for potential issues and provide recommendations. Includes built-in rules and your custom rules.",
"task.check-type.sql-review.self": "SQL review",
- "task.check-type.summary-report": "Summary report",
"task.executed-by": "Người thực thi",
"task.no-cancelable-tasks": "Không có tác vụ nào có thể hủy",
"task.no-runnable-tasks": "Không có tác vụ nào có thể chạy được",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 80e7ffd899..711927f581 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -3770,10 +3770,8 @@
"task.affected-rows": "影响行数",
"task.check-type.affected-rows.description": "根据统计信息估算。",
"task.check-type.affected-rows.self": "影响行数",
- "task.check-type.ghost-sync": "gh-ost 同步",
"task.check-type.sql-review.description": "分析 SQL 语句中的潜在问题并提供建议,包括内置规则和自定义规则。",
"task.check-type.sql-review.self": "SQL 审核",
- "task.check-type.summary-report": "摘要报告",
"task.executed-by": "执行人",
"task.no-cancelable-tasks": "没有可取消的任务",
"task.no-runnable-tasks": "没有可运行的任务",
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
index ecc7a0591c..9f936f27f9 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
@@ -1,133 +1,74 @@
import { create } from "@bufbuild/protobuf";
-import type { Timestamp as TimestampPb } from "@bufbuild/protobuf/wkt";
-import {
- AlertCircle,
- CheckCircle,
- CircleQuestionMark,
- FileCode,
- Loader2,
- Play,
- SearchCode,
- Shield,
- XCircle,
-} from "lucide-react";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { planServiceClientConnect } from "@/connect";
-import { Button } from "@/react/components/ui/button";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/react/components/ui/sheet";
-import { Tooltip } from "@/react/components/ui/tooltip";
+import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
import { useVueState } from "@/react/hooks/useVueState";
-import { cn } from "@/react/lib/utils";
import { pushNotification, useCurrentUserV1, useProjectV1Store } from "@/store";
import { extractUserEmail, projectNamePrefix } from "@/store/modules/v1/common";
-import {
- getDateForPbTimestampProtoEs,
- getRuleLocalization,
- ruleTemplateMapV2,
- ruleTypeToString,
-} from "@/types";
import {
GetPlanCheckRunRequestSchema,
GetPlanRequestSchema,
type PlanCheckRun,
- type PlanCheckRun_Result,
- PlanCheckRun_Result_Type,
- PlanCheckRun_ResultSchema,
- PlanCheckRun_Status,
RunPlanChecksRequestSchema,
} from "@/types/proto-es/v1/plan_service_pb";
-import { SQLReviewRule_Type } from "@/types/proto-es/v1/review_config_service_pb";
-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
import { hasProjectPermissionV2 } from "@/utils";
-import { extractDatabaseResourceName } from "@/utils/v1/database";
+import { getPlanCheckSummaryWithFallback } from "../../plan-detail/utils/planCheck";
import { useIssueDetailContext } from "../context/IssueDetailContext";
-interface ResultGroup {
- key: string;
- type: PlanCheckRun_Result_Type;
- target: string;
- createTime?: TimestampPb;
- results: PlanCheckRun_Result[];
-}
-
-const PAGE_SIZE = 10;
-
export function IssueDetailChecks() {
const { t } = useTranslation();
const page = useIssueDetailContext();
const projectStore = useProjectV1Store();
const currentUser = useVueState(() => useCurrentUserV1().value);
const [isRunningChecks, setIsRunningChecks] = useState(false);
- const [selectedResultStatus, setSelectedResultStatus] = useState<
- Advice_Level | undefined
- >();
const projectName = `${projectNamePrefix}${page.projectId}`;
const project = useVueState(() => projectStore.getProjectByName(projectName));
- const summary = useMemo(() => getPlanCheckSummary(page), [page]);
- const hasAnyChecks = summary.total > 0;
+
+ const summary = useMemo(
+ () =>
+ getPlanCheckSummaryWithFallback(
+ page.planCheckRuns,
+ page.plan?.planCheckRunStatusCount
+ ),
+ [page.planCheckRuns, page.plan?.planCheckRunStatusCount]
+ );
+
const allowRunChecks = useMemo(() => {
- if (!page.plan) {
- return false;
- }
- // Once a rollout exists, the plan is frozen — re-running checks produces
- // the same result and is misleading for the user.
- if (page.plan.hasRollout) {
- return false;
- }
- if (extractUserEmail(page.plan.creator) === currentUser.email) {
- return true;
- }
+ if (!page.plan) return false;
+ // Once a rollout exists the plan is frozen — re-running checks would only
+ // produce the same results and misleads the user.
+ if (page.plan.hasRollout) return false;
+ if (extractUserEmail(page.plan.creator) === currentUser.email) return true;
return hasProjectPermissionV2(project, "bb.planCheckRuns.run");
}, [currentUser.email, page.plan, project]);
- const refreshChecks = useCallback(async () => {
+ const refreshChecks = useCallback(async (): Promise<PlanCheckRun[]> => {
const planName = page.plan?.name;
- if (!planName) {
- return [];
- }
- const nextPlan = await planServiceClientConnect.getPlan(
- create(GetPlanRequestSchema, {
- name: planName,
- })
- );
-
- let nextPlanCheckRuns: PlanCheckRun[] = [];
- try {
- const response = await planServiceClientConnect.getPlanCheckRun(
- create(GetPlanCheckRunRequestSchema, {
- name: `${planName}/planCheckRun`,
- })
- );
- nextPlanCheckRuns = [response];
- } catch {
- nextPlanCheckRuns = [];
- }
-
- page.patchState({
- plan: nextPlan,
- planCheckRuns: nextPlanCheckRuns,
- });
+ if (!planName) return [];
+ const [nextPlan, runOrNull] = await Promise.all([
+ planServiceClientConnect.getPlan(
+ create(GetPlanRequestSchema, { name: planName })
+ ),
+ planServiceClientConnect
+ .getPlanCheckRun(
+ create(GetPlanCheckRunRequestSchema, {
+ name: `${planName}/planCheckRun`,
+ })
+ )
+ .catch(() => null),
+ ]);
+ const nextPlanCheckRuns = runOrNull ? [runOrNull] : [];
+ page.patchState({ plan: nextPlan, planCheckRuns: nextPlanCheckRuns });
return nextPlanCheckRuns;
}, [page.plan?.name, page.patchState]);
const runChecks = useCallback(async () => {
- if (!page.plan?.name) {
- return;
- }
-
+ if (!page.plan?.name) return;
try {
setIsRunningChecks(true);
await planServiceClientConnect.runPlanChecks(
- create(RunPlanChecksRequestSchema, {
- name: page.plan.name,
- })
+ create(RunPlanChecksRequestSchema, { name: page.plan.name })
);
await refreshChecks();
pushNotification({
@@ -147,713 +88,18 @@ export function IssueDetailChecks() {
}
}, [page.plan?.name, refreshChecks, t]);
- if (!page.plan) {
- return null;
- }
+ if (!page.plan) return null;
return (
- <div className="flex flex-col gap-y-1">
- <div className="flex items-center justify-between">
- <h3 className="textlabel">{t("plan.navigator.checks")}</h3>
- {allowRunChecks && (
- <Button
- disabled={isRunningChecks}
- onClick={() => {
- void runChecks();
- }}
- size="xs"
- variant="outline"
- >
- <Play className="h-3.5 w-3.5" />
- {t("plan.run")}
- </Button>
- )}
- </div>
- <div className="flex items-center gap-2">
- {hasAnyChecks && (
- <IssueDetailChecksStatusCount
- selectedStatus={selectedResultStatus}
- summary={summary}
- onSelectStatus={setSelectedResultStatus}
- />
- )}
- {!hasAnyChecks && (
- <span className="text-sm text-control-placeholder">
- {t("plan.overview.no-checks")}
- </span>
- )}
- </div>
-
- <IssueDetailChecksDialog
- onClose={() => setSelectedResultStatus(undefined)}
- open={selectedResultStatus !== undefined}
- planCheckRuns={page.planCheckRuns}
- refreshChecks={refreshChecks}
- status={selectedResultStatus}
- />
- </div>
+ <PlanCheckSection
+ canRun={allowRunChecks}
+ headingClassName="textlabel"
+ includeRunFailure
+ isRunning={isRunningChecks}
+ onRefreshOnOpen={refreshChecks}
+ onRun={runChecks}
+ planCheckRuns={page.planCheckRuns}
+ summaryOverride={summary}
+ />
);
}
-
-function IssueDetailChecksStatusCount({
- onSelectStatus,
- selectedStatus,
- summary,
-}: {
- onSelectStatus: (status: Advice_Level | undefined) => void;
- selectedStatus?: Advice_Level;
- summary: PlanCheckSummary;
-}) {
- const { t } = useTranslation();
-
- return (
- <div className="flex items-center gap-3">
- {summary.running > 0 && (
- <div className="flex items-center gap-1 text-control">
- <Loader2 className="h-5 w-5 animate-spin" />
- <span>{t("task.status.running")}</span>
- </div>
- )}
- {summary.error > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-error",
- selectedStatus === Advice_Level.ERROR
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : selectedStatus !== undefined
- ? "px-2 py-1"
- : ""
- )}
- onClick={() =>
- onSelectStatus(
- selectedStatus === Advice_Level.ERROR
- ? undefined
- : Advice_Level.ERROR
- )
- }
- type="button"
- >
- <XCircle className="h-5 w-5" />
- <span>{summary.error}</span>
- </button>
- )}
- {summary.warning > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-warning",
- selectedStatus === Advice_Level.WARNING
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : selectedStatus !== undefined
- ? "px-2 py-1"
- : ""
- )}
- onClick={() =>
- onSelectStatus(
- selectedStatus === Advice_Level.WARNING
- ? undefined
- : Advice_Level.WARNING
- )
- }
- type="button"
- >
- <AlertCircle className="h-5 w-5" />
- <span>{summary.warning}</span>
- </button>
- )}
- {summary.success > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-success",
- selectedStatus === Advice_Level.SUCCESS
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : selectedStatus !== undefined
- ? "px-2 py-1"
- : ""
- )}
- onClick={() =>
- onSelectStatus(
- selectedStatus === Advice_Level.SUCCESS
- ? undefined
- : Advice_Level.SUCCESS
- )
- }
- type="button"
- >
- <CheckCircle className="h-5 w-5" />
- <span>{summary.success}</span>
- </button>
- )}
- </div>
- );
-}
-
-function IssueDetailChecksDialog({
- onClose,
- open,
- planCheckRuns,
- refreshChecks,
- status,
-}: {
- onClose: () => void;
- open: boolean;
- planCheckRuns: PlanCheckRun[];
- refreshChecks: () => Promise<PlanCheckRun[]>;
- status?: Advice_Level;
-}) {
- const { t } = useTranslation();
- const [isLoading, setIsLoading] = useState(false);
- const [resolvedPlanCheckRuns, setResolvedPlanCheckRuns] =
- useState<PlanCheckRun[]>(planCheckRuns);
-
- useEffect(() => {
- setResolvedPlanCheckRuns(planCheckRuns);
- }, [planCheckRuns]);
-
- useEffect(() => {
- if (!open) {
- return;
- }
-
- let canceled = false;
-
- const load = async () => {
- try {
- setIsLoading(true);
- const runs = await refreshChecks();
- if (!canceled) {
- setResolvedPlanCheckRuns(runs);
- }
- } finally {
- if (!canceled) {
- setIsLoading(false);
- }
- }
- };
-
- void load();
-
- return () => {
- canceled = true;
- };
- }, [open, refreshChecks]);
-
- return (
- <Sheet onOpenChange={(nextOpen) => !nextOpen && onClose()} open={open}>
- <SheetContent
- className="w-[calc(100vw-2rem)] max-w-[calc(100vw-2rem)] sm:max-w-[40rem]"
- width="standard"
- >
- <SheetHeader>
- <SheetTitle>{t("plan.navigator.checks")}</SheetTitle>
- </SheetHeader>
- <SheetBody className="py-4">
- <IssueDetailChecksView
- defaultStatus={status}
- isLoading={isLoading}
- planCheckRuns={resolvedPlanCheckRuns}
- />
- </SheetBody>
- </SheetContent>
- </Sheet>
- );
-}
-
-function IssueDetailChecksView({
- defaultStatus,
- isLoading = false,
- planCheckRuns,
-}: {
- defaultStatus?: Advice_Level;
- isLoading?: boolean;
- planCheckRuns: PlanCheckRun[];
-}) {
- const { t } = useTranslation();
- const [selectedStatus, setSelectedStatus] = useState<
- Advice_Level | undefined
- >(defaultStatus);
- const [displayCount, setDisplayCount] = useState(PAGE_SIZE);
-
- useEffect(() => {
- setSelectedStatus(defaultStatus);
- }, [defaultStatus]);
-
- const summary = useMemo(
- () => computePlanCheckStatusSummary(planCheckRuns),
- [planCheckRuns]
- );
- const hasAnyStatus = summary.total > 0;
- const hasFilters = selectedStatus !== undefined;
- const filteredResultGroups = useMemo(
- () => buildFilteredResultGroups(planCheckRuns, selectedStatus),
- [planCheckRuns, selectedStatus]
- );
- const displayedResultGroups = filteredResultGroups.slice(0, displayCount);
- const hasMore = filteredResultGroups.length > displayCount;
- const remainingCount = filteredResultGroups.length - displayCount;
-
- useEffect(() => {
- setDisplayCount(PAGE_SIZE);
- }, [selectedStatus]);
-
- return (
- <div className="flex flex-1 flex-col">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-4">
- {hasAnyStatus && (
- <div className="flex items-center gap-3">
- {summary.error > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-error",
- selectedStatus === Advice_Level.ERROR
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : "px-2 py-1"
- )}
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.ERROR
- ? undefined
- : Advice_Level.ERROR
- )
- }
- type="button"
- >
- <XCircle className="h-5 w-5" />
- <span>{t("common.error")}</span>
- <span>{summary.error}</span>
- </button>
- )}
- {summary.warning > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-warning",
- selectedStatus === Advice_Level.WARNING
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : "px-2 py-1"
- )}
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.WARNING
- ? undefined
- : Advice_Level.WARNING
- )
- }
- type="button"
- >
- <AlertCircle className="h-5 w-5" />
- <span>{t("common.warning")}</span>
- <span>{summary.warning}</span>
- </button>
- )}
- {summary.success > 0 && (
- <button
- className={cn(
- "flex items-center gap-1 text-success",
- selectedStatus === Advice_Level.SUCCESS
- ? "rounded-lg bg-gray-100 px-2 py-1"
- : "px-2 py-1"
- )}
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.SUCCESS
- ? undefined
- : Advice_Level.SUCCESS
- )
- }
- type="button"
- >
- <CheckCircle className="h-5 w-5" />
- <span>{t("common.success")}</span>
- <span>{summary.success}</span>
- </button>
- )}
- </div>
- )}
- </div>
- </div>
-
- <div className="flex-1 overflow-y-auto">
- {isLoading ? (
- <div className="flex flex-col items-center justify-center py-12">
- <Loader2 className="h-5 w-5 animate-spin text-control-light" />
- </div>
- ) : filteredResultGroups.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12">
- <CheckCircle className="mb-4 h-12 w-12 text-control-light opacity-50" />
- <div className="text-lg text-control-light">
- {hasFilters
- ? t("plan.checks.no-results-match-filters")
- : t("plan.checks.no-check-results")}
- </div>
- </div>
- ) : (
- <div>
- <div className="divide-y">
- {displayedResultGroups.map((group) => (
- <div key={group.key} className="px-2 py-4">
- <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
- <div className="flex shrink-0 items-center gap-3">
- <CheckTypeIcon
- className="h-5 w-5 text-control-light"
- type={group.type}
- />
- <div className="flex flex-row items-center gap-2">
- <span className="text-sm font-medium">
- {getCheckTypeLabel(group.type, t)}
- </span>
- {getCheckTypeDescription(group.type, t) && (
- <Tooltip
- content={getCheckTypeDescription(group.type, t)}
- >
- <CircleQuestionMark className="h-4 w-4 text-control-light" />
- </Tooltip>
- )}
- {group.createTime && (
- <span className="text-sm text-control-light">
- {formatTimestamp(group.createTime)}
- </span>
- )}
- </div>
- </div>
- {group.target && (
- <div className="min-w-0 max-w-[50%] truncate text-sm text-control-light">
- {formatCheckTarget(group.target)}
- </div>
- )}
- </div>
-
- <div className="flex flex-col gap-y-2 pl-8">
- {group.results.map((result, index) => (
- <IssueDetailCheckResultCard
- key={`${group.key}-${index}`}
- affectedRows={
- result.report?.case === "sqlSummaryReport"
- ? result.report.value.affectedRows
- : undefined
- }
- code={result.code}
- content={result.content}
- position={
- result.report?.case === "sqlReviewReport" &&
- result.report.value.startPosition
- ? result.report.value.startPosition
- : undefined
- }
- reportType={result.report?.case}
- status={getCheckResultStatus(result.status)}
- title={result.title}
- />
- ))}
- </div>
- </div>
- ))}
- </div>
-
- {hasMore && (
- <div className="flex justify-center py-4">
- <button
- className="text-sm text-accent hover:underline"
- onClick={() =>
- setDisplayCount((current) => current + PAGE_SIZE)
- }
- type="button"
- >
- {t("common.load-more")} ({remainingCount})
- </button>
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
-
-function IssueDetailCheckResultCard({
- affectedRows,
- code,
- content,
- position,
- reportType,
- status,
- title,
-}: {
- affectedRows?: bigint;
- code?: number;
- content?: string;
- position?: { line: number; column: number };
- reportType?: "sqlReviewReport" | "sqlSummaryReport";
- status: "SUCCESS" | "WARNING" | "ERROR";
- title: string;
-}) {
- const { t } = useTranslation();
- const displayTitle = useMemo(
- () => getCheckResultTitle(title, code, reportType),
- [code, reportType, title]
- );
-
- return (
- <div className="flex items-start gap-3 rounded-lg border bg-gray-50 px-3 py-2">
- {status === "ERROR" ? (
- <XCircle className="h-5 w-5 shrink-0 text-error" />
- ) : status === "WARNING" ? (
- <AlertCircle className="h-5 w-5 shrink-0 text-warning" />
- ) : (
- <CheckCircle className="h-5 w-5 shrink-0 text-success" />
- )}
-
- <div className="flex min-w-0 flex-1 flex-col gap-y-1">
- <div className="text-sm font-medium text-main">{displayTitle}</div>
- {content && <div className="text-sm text-control">{content}</div>}
- {position && (position.line > 0 || position.column > 0) && (
- <div className="mt-1 text-sm text-control-light">
- {position.line > 0 && (
- <span>
- {t("common.line")} {position.line}
- </span>
- )}
- {position.line > 0 && position.column > 0 && <span>, </span>}
- {position.column > 0 && (
- <span>
- {t("common.column")} {position.column}
- </span>
- )}
- </div>
- )}
- {affectedRows !== undefined && (
- <div className="mt-1 flex items-center gap-1 text-sm">
- <span className="inline-flex items-center rounded-full bg-white px-2 py-0.5 text-xs text-control">
- {t("task.check-type.affected-rows.self")}
- </span>
- <span>{String(affectedRows)}</span>
- <span className="text-control opacity-80">
- ({t("task.check-type.affected-rows.description")})
- </span>
- </div>
- )}
- </div>
- </div>
- );
-}
-
-interface PlanCheckSummary {
- running: number;
- success: number;
- warning: number;
- error: number;
- total: number;
-}
-
-function getPlanCheckSummary(
- page: ReturnType<typeof useIssueDetailContext>
-): PlanCheckSummary {
- if (page.planCheckRuns.length > 0) {
- return computePlanCheckStatusSummary(page.planCheckRuns);
- }
-
- const statusCount = page.plan?.planCheckRunStatusCount || {};
- const running =
- statusCount[PlanCheckRun_Status[PlanCheckRun_Status.RUNNING]] || 0;
- const success = statusCount[Advice_Level[Advice_Level.SUCCESS]] || 0;
- const warning = statusCount[Advice_Level[Advice_Level.WARNING]] || 0;
- const error =
- (statusCount[Advice_Level[Advice_Level.ERROR]] || 0) +
- (statusCount[PlanCheckRun_Status[PlanCheckRun_Status.FAILED]] || 0);
- const total = running + success + warning + error;
- return { running, success, warning, error, total };
-}
-
-function computePlanCheckStatusSummary(runs: PlanCheckRun[]): PlanCheckSummary {
- let running = 0;
- let success = 0;
- let warning = 0;
- let error = 0;
-
- for (const checkRun of runs) {
- if (checkRun.status === PlanCheckRun_Status.RUNNING) {
- running++;
- }
- if (checkRun.status === PlanCheckRun_Status.FAILED) {
- error++;
- }
- for (const result of checkRun.results) {
- if (result.status === Advice_Level.ERROR) {
- error++;
- } else if (result.status === Advice_Level.WARNING) {
- warning++;
- } else if (result.status === Advice_Level.SUCCESS) {
- success++;
- }
- }
- }
-
- return {
- error,
- running,
- success,
- total: running + success + warning + error,
- warning,
- };
-}
-
-function buildFilteredResultGroups(
- planCheckRuns: PlanCheckRun[],
- selectedStatus?: Advice_Level
-) {
- const groups: ResultGroup[] = [];
- const groupMap = new Map<string, ResultGroup>();
-
- for (const checkRun of planCheckRuns) {
- if (
- checkRun.status === PlanCheckRun_Status.FAILED &&
- (selectedStatus === undefined || selectedStatus === Advice_Level.ERROR)
- ) {
- groups.push({
- createTime: checkRun.createTime,
- key: `failed-${checkRun.name}`,
- results: [
- create(PlanCheckRun_ResultSchema, {
- code: 0,
- content: checkRun.error || "Plan check run failed",
- status: Advice_Level.ERROR,
- title: "Check Failed",
- }),
- ],
- target: "",
- type: PlanCheckRun_Result_Type.TYPE_UNSPECIFIED,
- });
- }
-
- for (const result of checkRun.results) {
- if (selectedStatus !== undefined && result.status !== selectedStatus) {
- continue;
- }
-
- const key = `${result.type}-${result.target}`;
- const group = groupMap.get(key) ?? {
- createTime: checkRun.createTime,
- key,
- results: [],
- target: result.target,
- type: result.type,
- };
- group.results.push(result);
- if (!groupMap.has(key)) {
- groupMap.set(key, group);
- groups.push(group);
- }
- }
- }
-
- return groups;
-}
-
-function CheckTypeIcon({
- className,
- type,
-}: {
- className?: string;
- type: PlanCheckRun_Result_Type;
-}) {
- const Icon =
- type === PlanCheckRun_Result_Type.STATEMENT_ADVISE
- ? SearchCode
- : type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT
- ? FileCode
- : type === PlanCheckRun_Result_Type.GHOST_SYNC
- ? Shield
- : FileCode;
- return <Icon className={className} />;
-}
-
-function getCheckTypeLabel(
- type: PlanCheckRun_Result_Type,
- t: ReturnType<typeof useTranslation>["t"]
-) {
- if (type === PlanCheckRun_Result_Type.STATEMENT_ADVISE) {
- return t("task.check-type.sql-review.self");
- }
- if (type === PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT) {
- return t("task.check-type.summary-report");
- }
- if (type === PlanCheckRun_Result_Type.GHOST_SYNC) {
- return t("task.check-type.ghost-sync");
- }
- return String(type);
-}
-
-function getCheckTypeDescription(
- type: PlanCheckRun_Result_Type,
- t: ReturnType<typeof useTranslation>["t"]
-) {
- if (type === PlanCheckRun_Result_Type.STATEMENT_ADVISE) {
- return t("task.check-type.sql-review.description");
- }
- return undefined;
-}
-
-function getCheckResultStatus(
- status: Advice_Level
-): "SUCCESS" | "WARNING" | "ERROR" {
- if (status === Advice_Level.ERROR) {
- return "ERROR";
- }
- if (status === Advice_Level.WARNING) {
- return "WARNING";
- }
- return "SUCCESS";
-}
-
-function getCheckResultTitle(
- title: string,
- code?: number,
- reportType?: "sqlReviewReport" | "sqlSummaryReport"
-) {
- const messageWithCode = (message: string) => {
- if (code !== undefined && code !== 0) {
- return `${message} #${code}`;
- }
- return message;
- };
-
- if (title === "OK" || title === "Syntax error") {
- return messageWithCode(title);
- }
-
- if (reportType === "sqlReviewReport") {
- if (!code) {
- return title;
- }
- const typeKey = title as keyof typeof SQLReviewRule_Type;
- const typeEnum = SQLReviewRule_Type[typeKey];
- if (typeEnum !== undefined) {
- for (const mapByType of ruleTemplateMapV2.values()) {
- const rule = mapByType.get(typeEnum);
- if (rule) {
- return messageWithCode(
- getRuleLocalization(ruleTypeToString(rule.type), rule.engine).title
- );
- }
- }
- } else if (title.startsWith("builtin.")) {
- return messageWithCode(getRuleLocalization(title).title);
- }
- }
-
- return messageWithCode(title);
-}
-
-function formatTimestamp(timestamp: TimestampPb) {
- return getDateForPbTimestampProtoEs(timestamp)?.toLocaleString() ?? "";
-}
-
-function formatCheckTarget(target: string) {
- if (!target) {
- return "";
- }
- try {
- return extractDatabaseResourceName(target).databaseName;
- } catch {
- return target;
- }
-}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
index 3b469a0c69..6b8c3cab1e 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
@@ -374,6 +374,7 @@ function buildPageState(): PlanDetailPageState {
isEditing: false,
isInitializing: false,
isRefreshing: false,
+ isRunningChecks: false,
lastRefreshTime: 0,
mobileSidebarOpen: false,
pageKey: "foo/create/spec-1",
@@ -415,6 +416,7 @@ function buildPageState(): PlanDetailPageState {
routePhase: "changes",
selectedTaskName: undefined,
setEditing: vi.fn(),
+ setIsRunningChecks: vi.fn(),
setMobileSidebarOpen: vi.fn(),
sidebarMode: "DESKTOP",
taskRuns: [],
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx
index 359a671c8b..cd4acbcfc0 100644
Binary files a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx and b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx differ
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
index e42daf24a6..02c6278362 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
@@ -1,48 +1,22 @@
import { create } from "@bufbuild/protobuf";
-import {
- AlertCircle,
- CheckCircle,
- CircleQuestionMark,
- FileCode,
- Play,
- SearchCode,
- XCircle,
-} from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
+import { CircleQuestionMark } from "lucide-react";
+import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { releaseServiceClientConnect } from "@/connect";
-import { Badge } from "@/react/components/ui/badge";
-import { Button } from "@/react/components/ui/button";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/react/components/ui/sheet";
+import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
import { Tooltip } from "@/react/components/ui/tooltip";
import { pushNotification } from "@/store";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
-import {
- type PlanCheckRun,
- type PlanCheckRun_Result,
- PlanCheckRun_Result_Type,
-} from "@/types/proto-es/v1/plan_service_pb";
import {
CheckReleaseRequestSchema,
type CheckReleaseResponse_CheckResult,
Release_Type,
} from "@/types/proto-es/v1/release_service_pb";
-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
import { extractProjectResourceName } from "@/utils";
import { getSheetStatement } from "@/utils/v1/sheet";
import { usePlanDetailContext } from "../context/PlanDetailContext";
import { getLocalSheetByName } from "../utils/localSheet";
-import {
- getFilteredResultGroups,
- getPlanCheckSummary,
- transformReleaseCheckResultsToPlanCheckRuns,
-} from "../utils/planCheck";
+import { transformReleaseCheckResultsToPlanCheckRuns } from "../utils/planCheck";
export function PlanDetailDraftChecks({
checkResults,
@@ -58,9 +32,6 @@ export function PlanDetailDraftChecks({
const { t } = useTranslation();
const page = usePlanDetailContext();
const [isRunningChecks, setIsRunningChecks] = useState(false);
- const [selectedResultStatus, setSelectedResultStatus] = useState<
- Advice_Level | undefined
- >();
const statement = useMemo(() => {
if (selectedSpec.config.case !== "changeDatabaseConfig") return "";
@@ -72,10 +43,6 @@ export function PlanDetailDraftChecks({
() => transformReleaseCheckResultsToPlanCheckRuns(checkResults ?? []),
[checkResults]
);
- const summary = useMemo(
- () => getPlanCheckSummary(formattedCheckRuns),
- [formattedCheckRuns]
- );
const affectedRows = useMemo(() => {
return (checkResults ?? []).reduce(
(acc, result) => acc + result.affectedRows,
@@ -120,295 +87,25 @@ export function PlanDetailDraftChecks({
}
};
- return (
- <div className="flex flex-col gap-y-1">
- <div className="flex items-center justify-between gap-2">
- <h3 className="textlabel uppercase">{t("plan.checks.self")}</h3>
- <Button
- disabled={statement.length === 0 || isRunningChecks}
- onClick={() => void runChecks()}
- size="xs"
- variant="outline"
- >
- <Play className="h-3.5 w-3.5" />
- {t("plan.run")}
- </Button>
- </div>
-
- <div className="flex min-w-0 flex-wrap items-center gap-3 text-sm">
- {summary.error > 0 && (
- <button
- className="flex items-center gap-1 text-error hover:opacity-80"
- onClick={() => setSelectedResultStatus(Advice_Level.ERROR)}
- type="button"
- >
- <XCircle className="h-4 w-4 text-error" />
- <span>{t("common.error")}</span>
- <span className="font-medium">{summary.error}</span>
- </button>
- )}
- {summary.warning > 0 && (
- <button
- className="flex items-center gap-1 text-warning hover:opacity-80"
- onClick={() => setSelectedResultStatus(Advice_Level.WARNING)}
- type="button"
- >
- <AlertCircle className="h-4 w-4 text-warning" />
- <span>{t("common.warning")}</span>
- <span className="font-medium">{summary.warning}</span>
- </button>
- )}
- {!checkResults ? null : summary.error === 0 && summary.warning === 0 ? (
- <span className="flex items-center gap-1 text-success">
- <CheckCircle className="h-4 w-4 text-success" />
- <span>{t("common.success")}</span>
- </span>
- ) : null}
- {checkResults && affectedRows > 0 && (
- <Tooltip content={t("task.check-type.affected-rows.description")}>
- <span className="flex items-center gap-1 text-sm text-control-light">
- <span>{t("task.check-type.affected-rows.self")}</span>
- <span>{String(affectedRows)}</span>
- <CircleQuestionMark className="h-3.5 w-3.5 opacity-80" />
- </span>
- </Tooltip>
- )}
- </div>
-
- <DraftChecksDialog
- onClose={() => setSelectedResultStatus(undefined)}
- open={selectedResultStatus !== undefined}
- planCheckRuns={formattedCheckRuns}
- status={selectedResultStatus}
- />
- </div>
- );
-}
-
-function DraftChecksDialog({
- onClose,
- open,
- planCheckRuns,
- status,
-}: {
- onClose: () => void;
- open: boolean;
- planCheckRuns: PlanCheckRun[];
- status?: Advice_Level;
-}) {
- const { t } = useTranslation();
- const [selectedStatus, setSelectedStatus] = useState<
- Advice_Level | undefined
- >(status);
- const summary = useMemo(
- () => getPlanCheckSummary(planCheckRuns),
- [planCheckRuns]
- );
-
- useEffect(() => {
- if (!open) return;
- setSelectedStatus(status);
- }, [open, status]);
-
- const filteredResultGroups = useMemo(
- () => getFilteredResultGroups({ planCheckRuns, selectedStatus }),
- [planCheckRuns, selectedStatus]
- );
-
- return (
- <Sheet
- onOpenChange={(nextOpen) => {
- if (!nextOpen) onClose();
- }}
- open={open}
- >
- <SheetContent width="wide">
- <SheetHeader>
- <SheetTitle>{t("plan.navigator.checks")}</SheetTitle>
- </SheetHeader>
- <SheetBody className="gap-y-4">
- {summary.total > 0 && (
- <div className="flex min-w-0 flex-wrap items-center gap-3 text-sm">
- {summary.error > 0 && (
- <button
- className={
- selectedStatus === Advice_Level.ERROR
- ? "flex items-center gap-1 rounded-lg bg-gray-100 px-2 py-1 text-error"
- : "flex items-center gap-1 text-error"
- }
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.ERROR
- ? undefined
- : Advice_Level.ERROR
- )
- }
- type="button"
- >
- <XCircle className="h-5 w-5" />
- <span>{t("common.error")}</span>
- <span>{summary.error}</span>
- </button>
- )}
- {summary.warning > 0 && (
- <button
- className={
- selectedStatus === Advice_Level.WARNING
- ? "flex items-center gap-1 rounded-lg bg-gray-100 px-2 py-1 text-warning"
- : "flex items-center gap-1 text-warning"
- }
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.WARNING
- ? undefined
- : Advice_Level.WARNING
- )
- }
- type="button"
- >
- <AlertCircle className="h-5 w-5" />
- <span>{t("common.warning")}</span>
- <span>{summary.warning}</span>
- </button>
- )}
- {summary.success > 0 && (
- <button
- className={
- selectedStatus === Advice_Level.SUCCESS
- ? "flex items-center gap-1 rounded-lg bg-gray-100 px-2 py-1 text-success"
- : "flex items-center gap-1 text-success"
- }
- onClick={() =>
- setSelectedStatus((current) =>
- current === Advice_Level.SUCCESS
- ? undefined
- : Advice_Level.SUCCESS
- )
- }
- type="button"
- >
- <CheckCircle className="h-5 w-5" />
- <span>{t("common.success")}</span>
- <span>{summary.success}</span>
- </button>
- )}
- </div>
- )}
- {filteredResultGroups.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-12 text-control-light">
- <CheckCircle className="mb-4 h-12 w-12 opacity-50" />
- <div className="text-lg">{t("plan.checks.no-check-results")}</div>
- </div>
- ) : (
- <div className="divide-y">
- {filteredResultGroups.map((group) => (
- <div key={group.key} className="px-2 py-4">
- <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
- <div className="flex items-center gap-3">
- {group.type ===
- PlanCheckRun_Result_Type.STATEMENT_ADVISE ? (
- <SearchCode className="h-5 w-5 text-control-light" />
- ) : (
- <FileCode className="h-5 w-5 text-control-light" />
- )}
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium">
- {group.type ===
- PlanCheckRun_Result_Type.STATEMENT_ADVISE
- ? t("task.check-type.sql-review.self")
- : t("task.check-type.affected-rows.self")}
- </span>
- {group.type ===
- PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT && (
- <Tooltip
- content={t(
- "task.check-type.affected-rows.description"
- )}
- >
- <CircleQuestionMark className="h-4 w-4 text-control-light" />
- </Tooltip>
- )}
- {group.createTime && (
- <span className="text-xs text-control-light">
- {group.createTime.seconds
- ? new Date(
- Number(group.createTime.seconds) * 1000
- ).toLocaleString()
- : ""}
- </span>
- )}
- </div>
- </div>
- <div className="min-w-0 max-w-[50%] text-sm text-control-light">
- <span className="truncate">{group.target}</span>
- </div>
- </div>
- <div className="flex flex-col gap-y-2 pl-8">
- {group.results.map((result, index) => (
- <DraftCheckResultCard
- key={`${group.key}-${index}`}
- result={result}
- />
- ))}
- </div>
- </div>
- ))}
- </div>
- )}
- </SheetBody>
- </SheetContent>
- </Sheet>
- );
-}
-
-function DraftCheckResultCard({ result }: { result: PlanCheckRun_Result }) {
- const { t } = useTranslation();
- const position =
- result.report?.case === "sqlReviewReport"
- ? result.report.value.startPosition
- : undefined;
- const affectedRows =
- result.report?.case === "sqlSummaryReport"
- ? result.report.value.affectedRows
- : undefined;
+ const trailingSummary =
+ checkResults && affectedRows > 0n ? (
+ <Tooltip content={t("task.check-type.affected-rows.description")}>
+ <span className="flex items-center gap-1 text-sm text-control-light">
+ <span>{t("task.check-type.affected-rows.self")}</span>
+ <span>{String(affectedRows)}</span>
+ <CircleQuestionMark className="h-3.5 w-3.5 opacity-80" />
+ </span>
+ </Tooltip>
+ ) : null;
return (
- <div className="flex items-start gap-3 rounded-lg border border-control-border bg-control-bg px-3 py-2">
- <div className="mt-0.5 shrink-0">
- {result.status === Advice_Level.ERROR ? (
- <XCircle className="h-5 w-5 text-error" />
- ) : result.status === Advice_Level.WARNING ? (
- <AlertCircle className="h-5 w-5 text-warning" />
- ) : (
- <CheckCircle className="h-5 w-5 text-success" />
- )}
- </div>
- <div className="flex min-w-0 flex-1 flex-col gap-y-1">
- <div className="text-sm font-medium text-main">{result.title}</div>
- {result.content && (
- <div className="text-sm text-control">{result.content}</div>
- )}
- {position && (position.line > 0 || position.column > 0) && (
- <div className="mt-1 text-sm text-control-light">
- {position.line > 0 ? `${t("common.line")} ${position.line}` : ""}
- {position.line > 0 && position.column > 0 ? ", " : ""}
- {position.column > 0
- ? `${t("common.column")} ${position.column}`
- : ""}
- </div>
- )}
- {affectedRows !== undefined && (
- <div className="mt-1 flex items-center gap-1 text-sm">
- <Badge className="px-2 py-0 text-xs font-medium" variant="default">
- {t("task.check-type.affected-rows.self")}
- </Badge>
- <span>{String(affectedRows)}</span>
- <span className="text-control opacity-80">
- ({t("task.check-type.affected-rows.description")})
- </span>
- </div>
- )}
- </div>
- </div>
+ <PlanCheckSection
+ canRun
+ isRunning={isRunningChecks}
+ onRun={runChecks}
+ planCheckRuns={formattedCheckRuns}
+ runDisabled={statement.length === 0}
+ trailingSummary={trailingSummary}
+ />
);
}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
index d393138848..4fce78fc35 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
@@ -1,14 +1,9 @@
import { create } from "@bufbuild/protobuf";
-import {
- AlertCircle,
- CheckCircle,
- Loader2,
- RefreshCw,
- XCircle,
-} from "lucide-react";
+import { RefreshCw } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect } from "@/connect";
+import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
import { Button } from "@/react/components/ui/button";
import { Checkbox } from "@/react/components/ui/checkbox";
import {
@@ -37,6 +32,8 @@ import {
humanizeTs,
} from "@/utils";
import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanCheckActions } from "../hooks/usePlanCheckActions";
+import { getPlanCheckSummaryWithFallback } from "../utils/planCheck";
import { getPlanDetailSidebarStatusInfo } from "../utils/sidebarStatus";
import { PlanDetailSidebarApprovalFlow } from "./PlanDetailApprovalFlow";
@@ -72,14 +69,16 @@ export function PlanDetailMetadataSidebar() {
t,
});
}, [page.isCreating, page.issue, page.plan.state, page.rollout, t]);
- const planCheckSummary = useMemo(() => {
- const counts = page.plan.planCheckRunStatusCount || {};
- const running = counts.RUNNING || 0;
- const success = counts.SUCCESS || 0;
- const warning = counts.WARNING || 0;
- const error = (counts.ERROR || 0) + (counts.FAILED || 0);
- return { error, running, success, warning };
- }, [page.plan.planCheckRunStatusCount]);
+ const planCheckSummary = useMemo(
+ () =>
+ getPlanCheckSummaryWithFallback(
+ page.planCheckRuns,
+ page.plan.planCheckRunStatusCount
+ ),
+ [page.plan.planCheckRunStatusCount, page.planCheckRuns]
+ );
+ const { allowRunChecks, isRunningChecks, refreshChecks, runChecks } =
+ usePlanCheckActions();
const allowChangeLabels = useMemo(() => {
if (!project || !page.issue || page.issue.status !== IssueStatus.OPEN) {
return false;
@@ -122,43 +121,17 @@ export function PlanDetailMetadataSidebar() {
</div>
</div>
- {(planCheckSummary.running > 0 ||
- planCheckSummary.success > 0 ||
- planCheckSummary.warning > 0 ||
- planCheckSummary.error > 0) && (
- <div>
- <h4 className="mb-1 textinfolabel">{t("plan.navigator.checks")}</h4>
- <div className="flex flex-wrap items-center gap-3">
- {planCheckSummary.running > 0 && (
- <span className="flex items-center gap-1 text-control">
- <Loader2 className="size-4 animate-spin" />
- <span>{t("common.running")}</span>
- <span>{planCheckSummary.running}</span>
- </span>
- )}
- {planCheckSummary.error > 0 && (
- <span className="flex items-center gap-1 text-error">
- <XCircle className="size-4" />
- <span>{t("common.error")}</span>
- <span>{planCheckSummary.error}</span>
- </span>
- )}
- {planCheckSummary.warning > 0 && (
- <span className="flex items-center gap-1 text-warning">
- <AlertCircle className="size-4" />
- <span>{t("common.warning")}</span>
- <span>{planCheckSummary.warning}</span>
- </span>
- )}
- {planCheckSummary.success > 0 && (
- <span className="flex items-center gap-1 text-success">
- <CheckCircle className="size-4" />
- <span>{t("common.success")}</span>
- <span>{planCheckSummary.success}</span>
- </span>
- )}
- </div>
- </div>
+ {planCheckSummary.total > 0 && (
+ <PlanCheckSection
+ canRun={allowRunChecks}
+ headingClassName="textinfolabel"
+ includeRunFailure
+ isRunning={isRunningChecks}
+ onRefreshOnOpen={refreshChecks}
+ onRun={runChecks}
+ planCheckRuns={page.planCheckRuns}
+ summaryOverride={planCheckSummary}
+ />
)}
</div>
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
new file mode 100644
index 0000000000..58243c59e5
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
@@ -0,0 +1,90 @@
+import { create } from "@bufbuild/protobuf";
+import { useCallback, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { planServiceClientConnect } from "@/connect";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ projectNamePrefix,
+ pushNotification,
+ useCurrentUserV1,
+ useProjectV1Store,
+} from "@/store";
+import { extractUserEmail } from "@/store/modules/v1/common";
+import {
+ GetPlanCheckRunRequestSchema,
+ GetPlanRequestSchema,
+ type PlanCheckRun,
+ RunPlanChecksRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+
+// Wraps the run / refresh logic shared between PlanDetailChecks (per-spec
+// section in the body) and the plan-level summary in PlanDetailMetadataSidebar.
+// The running flag lives on the page context so both surfaces disable their
+// Run buttons together — otherwise the user could trigger two concurrent
+// runPlanChecks calls from the same page.
+export function usePlanCheckActions() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, isRunningChecks, setIsRunningChecks } = page;
+ const projectStore = useProjectV1Store();
+ const currentUser = useCurrentUserV1().value;
+ const projectName = `${projectNamePrefix}${page.projectId}`;
+ const project = useVueState(() => projectStore.getProjectByName(projectName));
+
+ const allowRunChecks = useMemo(() => {
+ if (page.plan.hasRollout) return false;
+ if (extractUserEmail(page.plan.creator) === currentUser.email) return true;
+ return hasProjectPermissionV2(project, "bb.planCheckRuns.run");
+ }, [currentUser.email, page.plan.creator, page.plan.hasRollout, project]);
+
+ const refreshChecks = useCallback(async (): Promise<PlanCheckRun[]> => {
+ const [nextPlan, runOrNull] = await Promise.all([
+ planServiceClientConnect.getPlan(
+ create(GetPlanRequestSchema, { name: page.plan.name })
+ ),
+ planServiceClientConnect
+ .getPlanCheckRun(
+ create(GetPlanCheckRunRequestSchema, {
+ name: `${page.plan.name}/planCheckRun`,
+ })
+ )
+ .catch(() => null),
+ ]);
+ const nextPlanCheckRuns = runOrNull ? [runOrNull] : [];
+ patchState({ plan: nextPlan, planCheckRuns: nextPlanCheckRuns });
+ return nextPlanCheckRuns;
+ }, [page.plan.name, patchState]);
+
+ const runChecks = useCallback(async () => {
+ try {
+ setIsRunningChecks(true);
+ await planServiceClientConnect.runPlanChecks(
+ create(RunPlanChecksRequestSchema, { name: page.plan.name })
+ );
+ await refreshChecks();
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("plan.checks.started"),
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("plan.checks.failed-to-run"),
+ description: String(error),
+ });
+ } finally {
+ setIsRunningChecks(false);
+ }
+ }, [page.plan.name, refreshChecks, t]);
+
+ return {
+ allowRunChecks,
+ isRunningChecks,
+ refreshChecks,
+ runChecks,
+ };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
index 153b28d7bc..0e6ed183c7 100644
--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
@@ -106,6 +106,8 @@ export interface PlanDetailPageSnapshot {
export interface PlanDetailPageState extends PlanDetailPageSnapshot {
isEditing: boolean;
isRefreshing: boolean;
+ isRunningChecks: boolean;
+ setIsRunningChecks: (running: boolean) => void;
lastRefreshTime: number;
activePhases: Set<PlanDetailPhase>;
routeName?: string;
@@ -318,6 +320,7 @@ export const usePlanDetailPage = ({
);
const [editingScopes, setEditingScopes] = useState<Record<string, true>>({});
const [isRefreshing, setIsRefreshing] = useState(false);
+ const [isRunningChecks, setIsRunningChecks] = useState(false);
const [lastRefreshTime, setLastRefreshTime] = useState(0);
const [pendingLeaveConfirm, setPendingLeaveConfirm] = useState(false);
const latestSnapshotRef = useRef(snapshot);
@@ -691,6 +694,8 @@ export const usePlanDetailPage = ({
...snapshot,
isEditing,
isRefreshing,
+ isRunningChecks,
+ setIsRunningChecks,
lastRefreshTime,
activePhases,
routeName,
@@ -715,6 +720,7 @@ export const usePlanDetailPage = ({
closeTaskPanel,
isEditing,
isRefreshing,
+ isRunningChecks,
lastRefreshTime,
patchState,
pendingLeaveConfirm,
diff --git a/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts b/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts
index 3a4170d752..14d0194dba 100644
--- a/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts
+++ b/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts
@@ -28,6 +28,27 @@ export interface ResultGroup {
results: PlanCheckRun_Result[];
}
+export const getPlanCheckSummaryWithFallback = (
+ planCheckRuns: PlanCheckRun[],
+ statusCount: Record<string, number> | undefined
+): PlanCheckSummary => {
+ if (planCheckRuns.length > 0) return getPlanCheckSummary(planCheckRuns);
+ const counts = statusCount ?? {};
+ const running = counts[PlanCheckRun_Status[PlanCheckRun_Status.RUNNING]] || 0;
+ const success = counts[Advice_Level[Advice_Level.SUCCESS]] || 0;
+ const warning = counts[Advice_Level[Advice_Level.WARNING]] || 0;
+ const error =
+ (counts[Advice_Level[Advice_Level.ERROR]] || 0) +
+ (counts[PlanCheckRun_Status[PlanCheckRun_Status.FAILED]] || 0);
+ return {
+ error,
+ running,
+ success,
+ total: running + success + warning + error,
+ warning,
+ };
+};
+
export const getPlanCheckSummary = (
planCheckRuns: PlanCheckRun[]
): PlanCheckSummary => {
@@ -178,6 +199,22 @@ export const transformReleaseCheckResultsToPlanCheckRuns = (
const allResults: PlanCheckRun_Result[] = [];
for (const result of results) {
+ if (result.advices.length === 0) {
+ // checkRelease succeeded for this target with no advices. Emit a
+ // synthetic SUCCESS result so the summary shows a Success badge —
+ // otherwise a clean run looks identical to "checks never ran".
+ allResults.push(
+ create(PlanCheckRun_ResultSchema, {
+ code: 0,
+ content: "",
+ status: Advice_Level.SUCCESS,
+ target: result.target,
+ title: "OK",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ })
+ );
+ continue;
+ }
for (const advice of result.advices) {
allResults.push(
create(PlanCheckRun_ResultSchema, {