Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(plan-detail): spec management UX (#20271)
boojackbba046f90ffb
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 72ce1c1a3a..1fe40f4530 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -163,6 +163,7 @@},"bbkit": {"confirm-button": {+ "cannot-undo": "You cannot undo this action.","sure-to-delete": "Are you sure to delete?"}},@@ -1588,6 +1589,7 @@}},"plan.add-spec": "Add Change",+ "plan.add-spec-pending-draft": "Save or discard the pending change before adding another","plan.checks.failed-to-run": "Failed to run plan checks","plan.checks.no-check-results": "No check results","plan.checks.no-results-match-filters": "No results match your filters",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex fc22edf5a9..7046003623 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -162,6 +162,7 @@},"bbkit": {"confirm-button": {+ "cannot-undo": "Esta acción no se puede deshacer.","sure-to-delete": "¿Estás seguro de que deseas eliminar?"}},@@ -1580,6 +1581,7 @@}},"plan.add-spec": "Agregar cambio",+ "plan.add-spec-pending-draft": "Guarda o descarta el cambio pendiente antes de agregar otro","plan.checks.failed-to-run": "No se pudieron ejecutar las verificaciones del plan","plan.checks.no-check-results": "No hay resultados de verificación","plan.checks.no-results-match-filters": "No hay resultados que coincidan con los filtros",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex ebde265d18..121dc1ee66 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -162,6 +162,7 @@},"bbkit": {"confirm-button": {+ "cannot-undo": "この操作は元に戻すことができません。","sure-to-delete": "本当に削除してもよろしいですか?"}},@@ -1580,6 +1581,7 @@}},"plan.add-spec": "変更を追加",+ "plan.add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください","plan.checks.failed-to-run": "プランチェックの実行に失敗しました","plan.checks.no-check-results": "チェック結果はありません","plan.checks.no-results-match-filters": "フィルターに一致する結果はありません",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex eeccbe8947..08554c8d03 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -162,6 +162,7 @@},"bbkit": {"confirm-button": {+ "cannot-undo": "Bạn không thể hoàn tác hành động này.","sure-to-delete": "Bạn có chắc chắn muốn xóa?"}},@@ -1580,6 +1581,7 @@}},"plan.add-spec": "Thêm thay đổi",+ "plan.add-spec-pending-draft": "Lưu hoặc hủy thay đổi đang chờ trước khi thêm thay đổi khác","plan.checks.failed-to-run": "Không thể chạy kiểm tra kế hoạch","plan.checks.no-check-results": "Không có kết quả kiểm tra","plan.checks.no-results-match-filters": "Không có kết quả khớp với bộ lọc",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 2d0b33920c..be86509f39 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -162,6 +162,7 @@},"bbkit": {"confirm-button": {+ "cannot-undo": "此操作无法撤销。","sure-to-delete": "确定要删除吗?"}},@@ -1580,6 +1581,7 @@}},"plan.add-spec": "添加变更",+ "plan.add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更","plan.checks.failed-to-run": "运行计划检查失败","plan.checks.no-check-results": "暂无检查结果","plan.checks.no-results-match-filters": "没有符合筛选条件的结果",diff --git a/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/ProjectPlanDetailPage.tsxindex ebebc9a943..9c720389b2 100644--- a/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx+++ b/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx@@ -251,15 +251,22 @@ export function ProjectPlanDetailPage({};}, [page.isCreating, page.issue, page.rollout, t]);+ // Mirror the URL specId into local state. We deliberately don't include+ // selectedSpecId in the deps — children (e.g. PlanDetailChangesBranch) may+ // set selectedSpecId to a draft spec that has no URL yet, and snapping it+ // back to specId here would defeat the selection.useEffect(() => {if (!page.isCreating && specId) {setSelectedSpecId(specId);- return;}+ }, [page.isCreating, specId]);++ // Default to the first spec when nothing is selected.+ useEffect(() => {if (!selectedSpecId && page.plan.specs.length > 0) {setSelectedSpecId(page.plan.specs[0].id);}- }, [page.isCreating, page.plan.specs, selectedSpecId, specId]);+ }, [page.plan.specs, selectedSpecId]);return (<PlanDetailProvider value={page}>diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 7de0220c61..854658c4ae 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -19,6 +19,13 @@ import {import { EngineIcon } from "@/react/components/EngineIcon";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { Alert } from "@/react/components/ui/alert";+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogTitle,+} from "@/react/components/ui/alert-dialog";import { Badge } from "@/react/components/ui/badge";import { Button } from "@/react/components/ui/button";import { Checkbox } from "@/react/components/ui/checkbox";@@ -109,11 +116,7 @@ import {updateRoleSetter,updateTransactionMode,} from "../utils/directiveUtils";-import {- getLocalSheetByName,- getNextLocalSheetUID,- removeLocalSheet,-} from "../utils/localSheet";+import { getLocalSheetByName, getNextLocalSheetUID } from "../utils/localSheet";import {allowGhostForDatabase,getPlanOptionVisibility,@@ -177,20 +180,40 @@ export function PlanDetailChangesBranch({const project = useVueState(() =>projectStore.getProjectByName(`projects/${page.projectId}`));- const sheetStore = useSheetV1Store();const [showAddSpecSheet, setShowAddSpecSheet] = useState(false);const [showTargetSelectorSheet, setShowTargetSelectorSheet] = useState(false);+ const [specPendingDelete, setSpecPendingDelete] = useState<Plan_Spec | null>(+ null+ );+ // Locally-held new spec for an already-created plan. We don't persist a new+ // spec to the backend at the "pick targets" step — that would create a spec+ // with an empty SQL statement. The spec lives here until the user fills in+ // a statement and saves; that single save commits the sheet and the spec+ // together via PlanDetailStatementSection's existing save flow.+ const [pendingNewSpec, setPendingNewSpec] = useState<Plan_Spec | null>(null);+ // Whether the draft tab is the active selection. Tracked separately from+ // selectedSpecId (which mirrors the URL) so a draft can be selected even+ // when the URL still points at a real spec.+ const [isPendingSelected, setIsPendingSelected] = useState(false);const [draftCheckRunsBySpecId, setDraftCheckRunsBySpecId] = useState<Record<string, PlanCheckRun[]>>({});const [draftCheckResultsBySpecId, setDraftCheckResultsBySpecId] = useState<Record<string, CheckReleaseResponse_CheckResult[] | undefined>>({});- const { emptySpecIdSet } = usePlanDetailSpecValidation(page.plan.specs ?? []);const specs = page.plan.specs ?? [];+ // Specs visible in the tab strip — real specs plus any pending draft.+ const visibleSpecs = useMemo(+ () => (pendingNewSpec ? [...specs, pendingNewSpec] : specs),+ [specs, pendingNewSpec]+ );+ const { emptySpecIdSet } = usePlanDetailSpecValidation(visibleSpecs);const selectedSpec = useMemo(() => {+ if (pendingNewSpec && isPendingSelected) {+ return pendingNewSpec;+ }return getSelectedSpec({ selectedSpecId, specs });- }, [selectedSpecId, specs]);+ }, [pendingNewSpec, isPendingSelected, selectedSpecId, specs]);const canModifySpecs = useMemo(() => {if (page.plan.state === State.DELETED) return false;if (page.readonly) return false;@@ -234,10 +257,15 @@ export function PlanDetailChangesBranch({const selectSpec = useCallback((specId: string) => {- onSelectedSpecIdChange(specId);- if (!page.isCreating) {- void pushSpecDetailRoute(page.projectId, page.planId, specId);+ if (page.isCreating) {+ // No URL drives the selection during plan creation.+ onSelectedSpecIdChange(specId);+ return;}+ // Let the URL change drive selectedSpecId via the sync effect in the+ // parent. Updating local state optimistically would bypass the leave+ // confirm dialog when the navigation is cancelled.+ void pushSpecDetailRoute(page.projectId, page.planId, specId);},[onSelectedSpecIdChange, page.isCreating, page.planId, page.projectId]);@@ -259,24 +287,24 @@ export function PlanDetailChangesBranch({},});- if (!page.isCreating) {- const createdSheet = await sheetStore.createSheet(- project.name,- localSheet- );- removeLocalSheet(localSheet.name);- if (spec.config.case === "changeDatabaseConfig") {- spec.config.value.sheet = createdSheet.name;- }+ if (page.isCreating) {+ // The whole plan is local during creation; just append to plan.specs.+ await commitSpecs([...page.plan.specs, spec]);+ selectSpec(spec.id);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ setShowAddSpecSheet(false);+ return;}- await commitSpecs([...page.plan.specs, spec]);- selectSpec(spec.id);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });+ // Already-created plan: hold the spec as a draft. The first statement+ // save commits the sheet and the spec together, so we never persist an+ // empty-statement spec to the backend.+ setPendingNewSpec(spec);+ setIsPendingSelected(true);setShowAddSpecSheet(false);return;} catch (error) {@@ -290,10 +318,12 @@ export function PlanDetailChangesBranch({}};- const handleDeleteSpec = async (specToDelete?: Plan_Spec) => {- const targetSpec = specToDelete ?? selectedSpec;- if (!targetSpec || page.plan.specs.length <= 1) return;- if (!window.confirm(t("common.delete"))) return;+ const handleDeleteSpec = async () => {+ const targetSpec = specPendingDelete;+ if (!targetSpec || page.plan.specs.length <= 1) {+ setSpecPendingDelete(null);+ return;+ }const nextSpecs = page.plan.specs.filter((spec) => spec.id !== targetSpec.id);@@ -315,11 +345,26 @@ export function PlanDetailChangesBranch({title: t("common.error"),description: String(error),});+ } finally {+ setSpecPendingDelete(null);}};const handleTargetsUpdate = async (targets: string[]) => {if (!selectedSpec) return;+ // Pending draft is local only — update in place without hitting the API.+ if (pendingNewSpec && selectedSpec.id === pendingNewSpec.id) {+ const patched = clone(Plan_SpecSchema, pendingNewSpec);+ if (+ patched.config.case === "changeDatabaseConfig" ||+ patched.config.case === "exportDataConfig"+ ) {+ patched.config.value.targets = targets;+ }+ setPendingNewSpec(patched);+ setShowTargetSelectorSheet(false);+ return;+ }const nextSpecs = page.plan.specs.map((spec) => {if (spec.id !== selectedSpec.id) return spec;const patched = clone(Plan_SpecSchema, spec);@@ -350,10 +395,48 @@ export function PlanDetailChangesBranch({};useEffect(() => {- if (selectedSpec && selectedSpec.id !== selectedSpecId) {+ // Skip when the draft is the active selection — the parent's+ // selectedSpecId mirrors the URL, and the draft has no URL yet.+ if (+ selectedSpec &&+ selectedSpec.id !== selectedSpecId &&+ selectedSpec.id !== pendingNewSpec?.id+ ) {onSelectedSpecIdChange(selectedSpec.id);}- }, [onSelectedSpecIdChange, selectedSpec, selectedSpecId]);+ }, [onSelectedSpecIdChange, pendingNewSpec, selectedSpec, selectedSpecId]);++ // Once the URL (and therefore selectedSpecId) lands on a real spec, the+ // draft is no longer the active selection. We don't clear pending eagerly+ // on tab click so the leave-confirm dialog can intercept and keep the+ // draft visible until the user discards.+ useEffect(() => {+ setIsPendingSelected(false);+ }, [selectedSpecId]);++ // Once the draft spec has been committed (the statement save adds it to+ // page.plan.specs), drop the local pending state so it's no longer rendered+ // as a separate tab. Selection follows the freshly-persisted spec.+ useEffect(() => {+ if (+ pendingNewSpec &&+ page.plan.specs.some((spec) => spec.id === pendingNewSpec.id)+ ) {+ const committedId = pendingNewSpec.id;+ setPendingNewSpec(null);+ setIsPendingSelected(false);+ // Push the URL now that the spec is persisted, so refresh keeps state.+ if (!page.isCreating) {+ void pushSpecDetailRoute(page.projectId, page.planId, committedId);+ }+ }+ }, [+ page.isCreating,+ page.plan.specs,+ page.planId,+ page.projectId,+ pendingNewSpec,+ ]);const selectedSpecIdForDraftChecks = selectedSpec?.id;const handleDraftCheckResultsChange = useCallback(@@ -398,23 +481,31 @@ export function PlanDetailChangesBranch({<PlanDetailTabStripaction={canModifySpecs ? (- <Button- onClick={() => setShowAddSpecSheet(true)}- size="xs"- variant="outline"+ <Tooltip+ content={+ pendingNewSpec ? t("plan.add-spec-pending-draft") : undefined+ }>- {t("plan.add-spec")}- </Button>+ <Button+ disabled={Boolean(pendingNewSpec)}+ onClick={() => setShowAddSpecSheet(true)}+ size="xs"+ variant="outline"+ >+ {t("plan.add-spec")}+ </Button>+ </Tooltip>) : undefined}>- {specs.map((spec, index) => {+ {visibleSpecs.map((spec, index) => {const isSelected = selectedSpec.id === spec.id;+ const isPending = pendingNewSpec?.id === spec.id;return (<PlanDetailTabItemkey={spec.id}action={- canModifySpecs && specs.length > 1 ? (+ canModifySpecs && visibleSpecs.length > 1 ? (<DropdownMenu><DropdownMenuTriggerclassName={cn(@@ -426,7 +517,16 @@ export function PlanDetailChangesBranch({<DropdownMenuContent><DropdownMenuItemclassName="text-error"- onClick={() => void handleDeleteSpec(spec)}+ onClick={() => {+ if (isPending) {+ // Drafts only live in local state; clear and+ // fall back to the first real spec.+ setPendingNewSpec(null);+ setIsPendingSelected(false);+ return;+ }+ setSpecPendingDelete(spec);+ }}>{t("common.delete")}</DropdownMenuItem>@@ -435,6 +535,15 @@ export function PlanDetailChangesBranch({) : undefined}onSelect={() => {+ if (isPending) {+ // Draft has no backend URL — only update local selection.+ setIsPendingSelected(true);+ return;+ }+ // Don't clear isPendingSelected here — if a leave-confirm+ // dialog intercepts the navigation, we want the draft to+ // stay visible behind the dialog. The URL-sync effect+ // below clears it once selectedSpecId actually changes.selectSpec(spec.id);}}selected={isSelected}@@ -506,6 +615,36 @@ export function PlanDetailChangesBranch({projectName={project.name}title={t("plan.add-spec")}/>++ <AlertDialog+ open={specPendingDelete !== null}+ onOpenChange={(open) => {+ if (!open) setSpecPendingDelete(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogTitle>+ {t("bbkit.confirm-button.sure-to-delete")}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t("bbkit.confirm-button.cannot-undo")}+ </AlertDialogDescription>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={() => setSpecPendingDelete(null)}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant="destructive"+ onClick={() => void handleDeleteSpec()}+ >+ {t("common.delete")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsxindex 2a99b669a9..c9ef1bb090 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -23,6 +23,7 @@ import {import { VCSType } from "@/types/proto-es/v1/common_pb";import {type Plan_Spec,+ Plan_SpecSchema,type PlanCheckRun,PlanSchema,UpdatePlanRequestSchema,@@ -153,10 +154,18 @@ export function PlanDetailStatementSection({return () => setEditing(editingScope, false);}, [editingScope, isEditing, setEditing]);+ // Pending draft specs (not yet on the backend) start in edit mode so the+ // user can immediately type the SQL that will commit the spec.+ const isPendingDraft = !page.plan.specs.some(+ (candidate) => candidate.id === spec.id+ );useEffect(() => {- setIsEditing(page.isCreating);+ // Depend on the boolean (not the specs array) so poll-driven refreshes+ // — which produce a new specs reference but the same membership — don't+ // wipe the user's in-progress edits.+ setIsEditing(page.isCreating || isPendingDraft);setDraftStatement("");- }, [page.isCreating, spec.id]);+ }, [page.isCreating, isPendingDraft, spec.id]);useEffect(() => {let canceled = false;@@ -294,10 +303,30 @@ export function PlanDetailStatementSection({const patchPlanStatement = (nextSheetName: string) => {const planPatch = clone(PlanSchema, page.plan);- const specToPatch = planPatch.specs.find(+ const existingIdx = planPatch.specs.findIndex((candidate) => candidate.id === spec.id);- if (!specToPatch) return undefined;+ if (existingIdx === -1) {+ // Pending new spec — append it on the first save so the spec and+ // its sheet are committed together. This avoids creating an+ // empty-statement spec on the backend.+ if (+ spec.config?.case !== "changeDatabaseConfig" &&+ spec.config?.case !== "exportDataConfig"+ ) {+ return undefined;+ }+ const newSpec = clone(Plan_SpecSchema, spec);+ if (+ newSpec.config.case === "changeDatabaseConfig" ||+ newSpec.config.case === "exportDataConfig"+ ) {+ newSpec.config.value.sheet = nextSheetName;+ }+ planPatch.specs = [...planPatch.specs, newSpec];+ return planPatch;+ }+ const specToPatch = planPatch.specs[existingIdx];if (specToPatch.config?.case !== "changeDatabaseConfig" &&specToPatch.config?.case !== "exportDataConfig"diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.tsindex affff6c6c9..153b28d7bc 100644--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts@@ -323,10 +323,9 @@ export const usePlanDetailPage = ({const latestSnapshotRef = useRef(snapshot);const bypassLeaveGuardOnceRef = useRef(false);const pollTimerRef = useRef<number | undefined>(undefined);- // Resolver for the most recent in-flight navigation guard. Vue Router's- // beforeEach is synchronous; we capture next() and resolve it after the- // user answers the leave-confirmation dialog.- const leaveResolverRef = useRef<((confirmed: boolean) => void) | null>(null);+ // Target route captured when the guard intercepts a navigation. We cancel+ // that navigation synchronously and re-issue it after the user confirms.+ const pendingLeaveTargetRef = useRef<string | null>(null);const isEditing = Object.keys(editingScopes).length > 0;// routeQuery is a fresh object on every router navigation. Stash the latest@@ -481,14 +480,27 @@ export const usePlanDetailPage = ({}, [patchState, planId, projectId, specId]);const resolveLeaveConfirm = useCallback((confirmed: boolean) => {- const resolver = leaveResolverRef.current;- leaveResolverRef.current = null;+ const target = confirmed ? pendingLeaveTargetRef.current : null;+ pendingLeaveTargetRef.current = null;setPendingLeaveConfirm(false);- resolver?.(confirmed);+ if (target) {+ bypassLeaveGuardOnceRef.current = true;+ // Replace (not push) so a confirmed-discard navigation doesn't leave+ // an extra entry that lets Back return to the discarded plan. Works+ // correctly whether the original navigation was push, replace, or+ // browser back/forward.+ void router.replace(target);+ }}, []);useEffect(() => {if (!isEditing) {+ // Editing scope ended (e.g. async save completed) while a leave+ // prompt is open — there's nothing unsaved anymore, so navigate to+ // the captured target without further confirmation.+ if (pendingLeaveTargetRef.current) {+ resolveLeaveConfirm(true);+ }return;}@@ -497,35 +509,25 @@ export const usePlanDetailPage = ({event.preventDefault();};window.addEventListener("beforeunload", onBeforeUnload);- const removeGuard = router.beforeEach((_to, _from, next) => {+ const removeGuard = router.beforeEach((to, _from, next) => {if (bypassLeaveGuardOnceRef.current) {bypassLeaveGuardOnceRef.current = false;next();return;}- // If a previous prompt is still open, cancel this navigation.- if (leaveResolverRef.current) {- next(false);- return;- }- leaveResolverRef.current = (confirmed: boolean) => {- next(confirmed ? undefined : false);- };+ // Cancel the navigation synchronously and remember the target so we+ // can re-issue it from resolveLeaveConfirm after the user confirms.+ // Always overwrite the pending target — the latest navigation wins.+ pendingLeaveTargetRef.current = to.fullPath;setPendingLeaveConfirm(true);+ next(false);});return () => {window.removeEventListener("beforeunload", onBeforeUnload);removeGuard();- // If the guard tears down with a prompt still open (e.g. user stops- // editing while the dialog is up), release the pending navigation.- if (leaveResolverRef.current) {- leaveResolverRef.current(false);- leaveResolverRef.current = null;- setPendingLeaveConfirm(false);- }};- }, [isEditing, t]);+ }, [isEditing, resolveLeaveConfirm, t]);useEffect(() => {if (snapshot.isCreating) {